Posts

Showing posts with the label django

Social login flow with Django backend and ionic frontend

Image
Clash Royale CLAN TAG #URR8PPP Social login flow with Django backend and ionic frontend I am trying to integrate social login with my ionic app, which is consuming data from a DRF server. The idea is that an user can login through fb, do some magic, the data will be sent back to the django server, and next time they log in they can retrieve their personal data again. So far I'm using native Cordova Fb plugin on ionic and I have managed to successfully log in with it. The problem now is I'm lost on what to do in the next step or the flow of the entire process. How do I register an user from Facebook to my django server so that the next time the user login I can retrieve the data from that respective user correctly? Let's say after I login with FB, I got an access token, do I pass that token back to django to register the new user and if so what tool should I use? For authentication I plan to have Django passing JWT back to the ionic app, but the part in the middle is where I...

django orm group by json key in json field

Image
Clash Royale CLAN TAG #URR8PPP django orm group by json key in json field I'm using json field on my django model: class JsonTable(models.Model): data = JSONField() type = models.IntegerField() I tried next query, which works for normal sql fields: JsonTable.objects.filter(type=1).values('type').annotate(Avg('data__superkey')) But this throws next error: FieldError: Cannot resolve keyword 'superkey' into field. Join on 'data' not permitted. Is there way to make group by on json key, using Django ORM or some python lib, without use of raw sql? Versions: Django 1.9b, PostgreSQL 9.4 UPDATE Example 2: JsonTable.objects.filter(type=1).values('data__happykey').annotate(Avg('data_superkey')) throws same error on happykey happykey 2 Answers 2 If you are using this package https://github.com/bradjasper/django-jsonfield, there is nothing in the code ...

Read Description list in selenium python

Image
Clash Royale CLAN TAG #URR8PPP Read Description list in selenium python How can I read text of <dd> tag which has <dt> like Commodity code. <dd> <dt> `<dl class="dl"> <dt>Trading Screen Product Name</dt> <dd>Biodiesel Futures (balmo)</dd> <dt>Trading Screen Hub Name</dt> <dd>Soybean Oil Pen 1st Line</dd> <dt>Commodity Code</dt> <dd><div>S25-S2Z</div></dd> <dt>Contract Size</dt> <dd><div>100 metric tonnes (220,462 pounds)</div></dd> </dl>` from selenium import webdriver driver = webdriver.Chrome("C:\Python36-32\selenium\webdriver\chromedriver.exe") link_list = ["http://www.theice.com/products/31500922","http://www.theice.com/products/243"] driver.maximize_window() for link in link_list: driver.get(link) desc_list = driver...

Django Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS

Image
Clash Royale CLAN TAG #URR8PPP Django Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS I started learning Django, I'm in the middle of implementing "Test a view" functionality. When I use test Client in the shell, the exception has occurred as follows. Invalid HTTP_HOST header: 'testserver'. You may need to add u'testserver' to ALLOWED_HOSTS. I run the command in the shell as follows. >>> from django.test.utils import setup_test_environment >>> setup_test_environment() >>> from django.test import Client >>> client = Client() >>> response = client.get('/') >>> response.status_code 400 In the tutorial, 404 should be appeared, but I get 400. When I continue running the command as follows, same exception has occurred. >>> response = client.get(reverse('polls:index')) >>> response.status_code 400 but the result must ...

Why is SECURE_SSL_REDIRECT always getting set to True?

Image
Clash Royale CLAN TAG #URR8PPP Why is SECURE_SSL_REDIRECT always getting set to True? I currently have a local .env file which contains parameters for my local environment. I have a Django App hosted on Heroku where I assign my config variables. I figured using python-decouple 's .env file to set SECURE_SSL_REDIRECT=False and then in my settings.py use SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT') would work. However, no matter the case, if Django sees SECURE_SSL_REDIRECT = True ANYWHERE, it tries to load as HTTPS and my god is it frustrating. .env python-decouple SECURE_SSL_REDIRECT=False settings.py SECURE_SSL_REDIRECT = config('SECURE_SSL_REDIRECT') SECURE_SSL_REDIRECT = True By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Using font-awesome in python django application

Image
Clash Royale CLAN TAG #URR8PPP Using font-awesome in python django application I'm trying to load a local copy of font awesome icons in my python django app. My template base.html contains: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'appointments/css/all.css' %}" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> <title>{% block ...

Get() a Model object from it's UUID

Image
Clash Royale CLAN TAG #URR8PPP Get() a Model object from it's UUID AIM As part of a weather-dependent alarm clock project, each alarm will contain three categories of info: 1) date/time, 2) weather conditionals, 3) location. EDIT Once the User completes the SetAlarmForm , I am trying to create an Alarm object based on the Form-input and timezone , city and country based on the User's IP address. SetAlarmForm Alarm timezone city country I am attempting to retrieve the information inputted by the User in the Form , and assign that information to an Alarm object (identifiable by a UUID reference). Form Alarm As requested in a comment, the URL is https://jqlc3gdp.apps.lair.io/login/ CODE Models.py class User(models.Model): """ Model representing each User """ username = models.CharField(max_length=10, unique=True) class Alarm(models.Model): """ Model representing each Alarm """ alarm_id = models.UUID...

Performing operations on Django Querysets

Image
Clash Royale CLAN TAG #URR8PPP Performing operations on Django Querysets I have very large Querysets with the following general form: ( {id: x} {termVector: [ '.00035 .00052...' ]} ) If I want to convert the termVectors from a string to a list of float s, is there a standard way of doing that? I've been using the .values() method and iterating through the resulting dict , but it seems to be pretty computationally heavy given the size of the querysets. termVectors string float .values() dict I feel like there must be a better way but I can't seem to find any way of doing it in the documentation. EDIT: My current placeholder method looks like this: for vectorList in termVectorQS: termVector.append(vectorList['termVector'].split()) for x in termVector: for y in x: termList.append(float(y)) It just splits the vector string by whitespace, then converts each string to a float and adds it to an array (termList) that I use ...

Setting Up S3 with Heroku and Django with Images

Image
Clash Royale CLAN TAG #URR8PPP Setting Up S3 with Heroku and Django with Images so I currently have my static files (js and css) just being stored on Heroku which is no biggie. However, I have objects that I need to store multiple images too and be able to get those images on request. How would I store a reference to those images? I was planning to use a S3 Direct File Upload using these steps on Heroku here. Is this also going to be the best way for me to do so? Thank you in advance. By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Celery get() works in python shell but not in Django view

Image
Clash Royale CLAN TAG #URR8PPP Celery get() works in python shell but not in Django view I want to check basic Celery functionality inside official demo Celery project for django with code available here. My modification is the demoapp/views.py (and of course urls.py to point to this view): from __future__ import absolute_import, unicode_literals from django.http import HttpResponse from demoapp.tasks import add, mul, xsum def home(request): return HttpResponse("Your output is: %s" % mul.delay(22,4).get(timeout=1) ) which always gives timeout error, though the terminal of running Celery worker shows that task was received and displays correct return value. However, if I start python shell python ./manage.py shell and then run python ./manage.py shell from demoapp.tasks import add, mul, xsum mul.delay(22,4).get(timeout=1) I immediately get the expected result. What may be the problem? Rabbitmq server is running, I use Celery 4.2.1, django 2.0.6. demoapp/tasks.py: from __f...

URL pattern python Django

Image
Clash Royale CLAN TAG #URR8PPP URL pattern python Django I am learning python django i am developing one website but i am struggling with URL pattern I am Sharing my code for URL pattern i don't understand where i am getting wrong url.py urlpatterns = [ url(r'^$',views.IndexView.as_view(),name='index'), # /music/id/ url(r'^picture/(?P<pk>[0-9]+)$',views.DetailView.as_view(),name='detail'), #for PictureDetail view url(r'^detail/(?P<pk>[0-9]+)/(?P<alb_title>[w%20+A-Za-z]+)/(?P<song_title>[w%20+A-Za-z]+)$', views.PicturedetailView.as_view(), name='picturedetail'), ] My Detail.html:- <ul> {% for picture in album.picture_set.all %} <div class="col-sm-4 col-lg-2"> <div class="thumbnail"> <a href="{% url 'music:picturedetail' pk=picture.pk alb_title=picture.album.album_title so...

Celery Function not called

Image
Clash Royale CLAN TAG #URR8PPP Celery Function not called I try to create a progress bar with celery. Unfortunately my worker function get not called. def checkconfig_post_new (request): job = do_work.delay() print ("Work started") return HttpResponseRedirect ( reverse ( 'poll_state' ) + '?job=' + job.id ) # this decorator is all that's needed to tell celery this is a worker task @task() def do_work(): for i in range(10): sleep(0.1) print (i) current_task.update_state(state='PROGRESS', meta={'current': i, 'total': 10}) The print statement "Work started" will never be printed out. Also the "i" will never be printed. It seems, that the program will stop working. By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie poli...

Django - detect which form was submitted in a page

Image
Clash Royale CLAN TAG #URR8PPP Django - detect which form was submitted in a page I have multiple form fields, and multiple submit buttons on a same page. I want to detect by which form field a POST request is triggered. I am using CBV and my post() method has this: CBV post() def post(self, request, **kwargs): .... form1 = Form1(request.POST, instance=Model1.objects.filter(some_filtering...) form2 = Form2(request.POST, instance=Model2.objects.filter(some_filtering...) form3 = Form3(request.POST, instance=Model3.objects.filter(some_filtering...) form4 = Form4(request.POST, instance=Model4.objects.filter(some_filtering...) # this is the code I want to know if POST request is triggered by form1... # do something.... return super().post(request, **kwargs) return super().post(request, **kwargs) How can I detect which form triggered POST request? 2 Answers 2 ...

Add Text on Image using PIL

Image
Clash Royale CLAN TAG #URR8PPP Add Text on Image using PIL I have an application that loads an Image and when the user clicks it, a text area appears for this Image (using jquery ), where user can write some text on the Image. Which should be added on Image. jquery After doing some research on it, I figured that PIL (Python Imaging Library ) can help me do this. So I tried couple of examples to see how it works and I managed to write text on an image. But I think there is some difference when I try it using Python Shell and in web environment. I mean the text on the textarea is very big in px. How can I achieve the same size of text when using PIL as the one on the textarea? PIL Python Shell The text is Multiline. How can i make it multiline in image also, using PIL ? PIL Is there a better way than using PIL? I am not entirely sure, If this is the best implementation. html: <img src="images/test.jpg"/> its the image being edited var count = 0; $('textarea').a...

Got “ValueError: invalid literal for int() with base 10: 'Trancel'” when using two paramenters in detailview in Django

Image
Clash Royale CLAN TAG #URR8PPP Got “ValueError: invalid literal for int() with base 10: 'Trancel'” when using two paramenters in detailview in Django I am trying to use two other url tags other then pk and slug in a detail view. I have the following code snippet: 1 Answer 1 Do you have the ability to rename Trance1 to something like TranceOne ? So that it doesn't include an integer? Trance1 TranceOne I think your issue is that 1 when it comes time to parse the URL..( as its expecting a sting, but it gets string w/ a 1 in it). 1 1 By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

django haystack whoosh not showing any errors also no results

Image
Clash Royale CLAN TAG #URR8PPP django haystack whoosh not showing any errors also no results I am trying to django-haystack whoosh. Django Haystack & Whoosh search working but in page no giving result. I have looked up this similar question too Django-haystack-whoosh is giving no results Django Haystack & Whoosh Search Working, But SearchQuerySet Return 0 Results pip freeze python==3.6 django==2.0.7 Whoosh==2.7.4 -e git://github.com/django-haystack/django.haystack.git#egg=django-haystack Here is my code: search_indexes.py import datetime from haystack import indexes from search.models import Articles class ArticlesIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document = True, use_template = true pub_date = indexes.DateTimeField(model_attr = 'pub_date') content_auto = indexes.EdgeNgramField(model_attr='title') def get_model(self): return Articles def index_queryset(self, using=None) return self.get_mod...

Overwriting a border on an image in Python PIL

Image
Clash Royale CLAN TAG #URR8PPP Overwriting a border on an image in Python PIL I have a gallery application where the users upload photos and my code gives it a border, writes some of the photo attributes on the border and stores it. image2 = Image.open('media/' + str(image.file)) width, height = image2.size; image2 = ImageOps.expand(image2, border=(int(width/25),int(height/20),int(width/25),int(height/10)), fill='rgb(0,0,0)') (Note that here my bottom border is longer than the top because I am writing attributes on the bottom border.) Now I'm building an edit feature for the uploaded images where the user can change the attributes of the uploaded images. But the attributes that are already written on the border have to be overwritten. So here, my approach is to put a black patch on the bottom border and re-write the new attributes without changes the top and side borders and without changing the aspect ratio. All of this has to be done using PIL. Question is how do ...