Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LocationParseError django-allauth google
I am using (on Windows): Python: 3.6.1 Django: 1.11.1 django-allauth: 0.32.0 I went through django-allauth documentation to install google provider. And after I click google login on my login page I get this error: LocationParseError at /accounts/google/login/callback/ Failed to parse: 165.225.84.34:10066;PROXY Request Method: GET Request URL: http://127.0.0.1:8000/accounts/google/login/callback/?state=IaOTlswJaK86&code=4%2FhYTCDmnzSQBJbiUPnAKBIrsGo1WSS7ueEJCLiUDypUY Django Version: 1.11.1 Exception Type: LocationParseError Exception Value: Failed to parse: 165.225.84.34:10066;PROXY Exception Location: C:\Anaconda3\envs\MyDjangoEnv\lib\site-packages\urllib3\util\url.py in parse_url, line 199 Python Executable: C:\Anaconda3\envs\MyDjangoEnv\python.exe Python Version: 3.6.1 Python Path: ['C:\Users\splasi\Documents\wd\allauth_login\allauth_login', 'C:\Anaconda3\envs\MyDjangoEnv\python36.zip', 'C:\Anaconda3\envs\MyDjangoEnv\DLLs', 'C:\Anaconda3\envs\MyDjangoEnv\lib', 'C:\Anaconda3\envs\MyDjangoEnv', 'C:\Anaconda3\envs\MyDjangoEnv\lib\site-packages', 'C:\Anaconda3\envs\MyDjangoEnv\lib\site-packages\setuptools-27.2.0-py3.6.egg'] I am new to Django and Ill be grateful for any help. -
django: avoid firefox back button restore the user session
Let me put you in context: Say that I'm logged in and I close my session. After loggout if I click on back button in firefox my private page is showed, my session is restored! That does not happen in chrome. If I try to do it in chrome I'm redirected to login page with next get param set to url I'm trying to go. So how can avoid this firefox behavior, or it's matter of django? -
How to format date so django modelform will validate and save?
I have a modelform based on this model: # Trips class Trip(models.Model): start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_start_locations', blank=False) end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='trip_end_locations', blank=False) miles = models.DecimalField(max_digits=7, decimal_places=2) user = models.ForeignKey(User, on_delete=models.PROTECT) trip_date = models.DateTimeField('trip date') def __str__(self): return self.id It looks like this in the view: # Create trip def trip_create(request): # if this is a POST request we need to process the form data if request.method == 'POST': trip_date = datetime.datetime.strptime(request.POST['trip_date'], '%m/%d/%Y %I:%M:%S %p') trip_date = trip_date.strftime("%Y-%m-%d %H:%M:%S") # Store this! form = TripsForm(request.POST) # check whether it's valid: if form.is_valid(): user_id = request.user.id start_location = form.cleaned_data['start_location'] end_location = form.cleaned_data['end_location'] miles = form.cleaned_data['miles'] trip_date = trip_date # Save the form and move the end to the start trip = Trip(user_id=user_id, start_location=start_location, end_location=end_location, miles=miles, trip_date=trip_date) trip.save() return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a blank form else: form = TripsForm() user = request.user # Return to trips with list of date return render(request, 'trips/create.html', {'form': form}) Everything on the form works great (I'm using a jquery datepicker to help the user 'select' the date), the problem lies with the date. The date the user sees is like this: "06/05/2017 01:44:07 PM" So when they … -
Elegant way of `get or none` in Django? [duplicate]
This question already has an answer here: In Django, how do I objects.get, but return None when nothing is found? 14 answers In Python dict, we have a way of getting value or none if key does not exist, as in some_dict = {'id0': 'value0'} some_dict.get('id1', None) In Django, the similar way is try: instance = Class.objects.get(pk='id1') except DoesNotExist: instance = None I just think to raise an exception (which is often expected) and to catch it is not an elegant way to deal with a frequently happening situation. Any thoughts? -
Django Static Image in Form Update
In dev environment I can load the form and update any text field, django automatically handles the static images. Where as in production static image handled by webservice, it loads the image in form update view, but it asks again to select the image in every update. It does not recognize the existing image, I know I have to handle it in views, but not sure how it is done generally. -
django display uploaded by user images
I have ImageUploadField I save images at my_project/forum_attachments directory. But when I try to display them and see by this link: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg I get an error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/forum_attachments/1466786056166112161_Nrns2WL.jpg What do I do? -
Django Rest-Framework: How to cross object in ModelSerializer
So, I know ModelSerializer supports nested model object based on the foreign key in the current object. However, I am wondering how to do a cross join models with specific the field equals to another object? i.e. class classroom(models.Model): id = models.AutoField(primary_key = True, editable = False) class student(models.Model): id = models.AutoField(primary_key = True, editable = False) classroom = models.ForeignKey(classroom, on_delete=models.CASCADE) Now I would like to do a ModelSerializer with classroom model. The idea I would like to archive is returning student.objects.filter(classroom = self.id) [self is classrom] How can I get the data from the student as well? (There is no ForeignKey in classroom targeting student) class classroomSerializer(ModelSerializer): # students = ?? class Meta: model = classroom fields = [ 'id', 'students', ] -
Outbound Link Tracking with Google Analytics with Django not working in production
I am attempting to track outbound link clicks with Google Analytics (GA). Basic page logging works with GA. In my development environment, outbound link tracking works. Here is the script I have in my base page: <script> var trackOutboundLink = function(url) { ga('send', 'event', 'outbound', 'click', url, { 'transport': 'beacon', 'hitCallback': function(){document.location = url;} }); } </script> Here is an example anchor tag: <a href="http://www.example.com/" onclick="trackOutboundLink('http://www.example.com'); return false;">Example Site</a> I am running the site on a Digital Ocean app using nginx and gunicorn. When a link is clicked, the status bar on the banner shows traffic to GA and then the browser is redirected to the original page with the link url appended to it. https://original-site.com/slug_of_page/www.example.com This generates a 404 -
Django DRF authentication and permissions
I am currently using DRF and django-allauth for authentication to my website. What should I use to only allow specific users who have an account on my website to use the DRF on the website? Some users I would like to only allow GET and some users I would like to allow GET, PUT, POST for the API. -
Shows "Unable to get repr for <class 'django.db.models.query.QuerySet'>" while retrieving data
I've been trying to retrieve all data from model StudentInfo. But it shows the following error. django.db.utils.ProgrammingError: column student_studentinfo.gurdians_mobile does not exist After debugging my code, I found the line that causes error is allStudent = StudentInfo.objects.all() And the debugging messages Shows: Unable to get repr for class 'django.db.models.query.QuerySet' Here is my model StudentInfo class StudentInfo(models.Model): student_name = models.CharField("Student Name",max_length=20) admission_date = models.DateField("Admission Date") mobile_no1 = models.CharField("Mobile No.",max_length=12) current_address = models.CharField("Current Address",max_length=20,blank=True) batch_number = models.ForeignKey(BatchInfo) coaching_id = models.IntegerField("Coaching ID") def __unicode__(self): return self.student_name def __repr__(self): return str(self.student_name) And the other model BatchInfo that is related to StudentInfo class BatchInfo(models.Model): batch_name = models.CharField("Batch Name",max_length=20) batch_started_from = models.DateField("Batch Started From") no_of_registered_student = models.IntegerField("Number of Registered Student so far",default=0) def __str__(self): return self.batch_name def __unicode__(self): return self.batch_name The strange part is that I've used the same style of code in other places which are perfectly functioning. all_batch = BatchInfo.objects.all() I try my best to solve it by my own but as a newbie, I found it very difficult for me. So I ask your help. Thanks in advance. -
PasswordResetView.as_view Reverse for '' not found. '' is not a valid view function or pattern name
urls.py url(r'^password/reset/$', PasswordResetView.as_view( success_url=reverse_lazy('password_reset_done'), template_name='registration/password_reset_form.html', email_template_name='registration/password_reset_email.html', subject_template_name='registration/email/password_reset_subject.txt' ), name='password_reset'), url(r'^password/reset/done/$', PasswordResetDoneView.as_view( template_name='registration/password_reset_confirm.html' ), name='password_reset_done'), error Internal Server Error: /accounts/password/reset/done/ Traceback (most recent call last): File "/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/lib/python3.5/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/lib/python3.5/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/lib/python3.5/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 199, in _render return self.nodelist.render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 990, in render bit = node.render_annotated(context) File "/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/lib/python3.5/site-packages/django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "/lib/python3.5/site-packages/django/template/loader_tags.py", line 72, in render result = block.nodelist.render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/lib/python3.5/site-packages/django/template/loader_tags.py", line 72, in render result = block.nodelist.render(context) File "/lib/python3.5/site-packages/django/template/base.py", line 957, in render_annotated return self.render(context) File "/lib/python3.5/site-packages/django/template/defaulttags.py", line 458, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "/lib/python3.5/site-packages/django/urls/base.py", line 91, in reverse return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) File "/lib/python3.5/site-packages/django/urls/resolvers.py", line 497, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: … -
Url change but still on the same page django
When i change to the page "lostitems" it successfull show up, but when i change to another page "addlostitem" it's still on the same page as before, but the url change the way that i want Urls.py url(r'lostitems/$', views.LostItemsView.as_view(), name='lost_items'), url(r'lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'), Views.py class LostItemsView(generic.ListView): model = Wallet template_name = 'lostfound/lost_items.html' class RegisterLostView(View): model = Wallet template_name = 'lostfound/register_lost.html' -
Partial matches with Django Postgres full text search
Django's documentation for the Postgres full text search uses the following example: >>> Entry.objects.filter(body_text__search='Cheese') [<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>] I would like to use this, but to get the same results by searching for only part of the word. Currently this results in no results: >>> Entry.objects.filter(body_text__search='Chee') [] Basically I would like to get the same results that I would get using body_text__icontains. I would like to use full text search so that after I get this working I can take advantage of things such as reusable search vectors, weighting queries and ranking. Is there some way to get results with partial word queries? -
unicode to ASCII (getting junk value when i try to publish values from database)
I have models.py from future import unicode_literals # -- coding: utf-8 -- from django.db import models from django.utils import timezone import datetime from datetime import datetime, timedelta from django.contrib.auth.models import User class some_model(models.Model): info=models.CharField(max_length=200) message=models.TextField() time=models.DateTimeField(auto_now_add=True,) def __unicode__(self): return self.info I have forms.py: class someForm(forms.ModelForm): class Meta: model = some_model fields = ('info', 'message',) I have views.py: def some_view(request): if request.method == "POST": form = someForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('some_all') else: form = chatForm() return render(request, 'some_view.html', {'form': form,}) Now i have filled massage field with some regional language . saving this form to mysql database , every thing is fine . I can see my message column regional language saved as it is in mysql database . After when i try to fetch the data from database like , for i in some_model.objects.filter(info='some thing'): i.message I get some junk value like bellow . u'\u09b9\u0987' u'\u09b9\u0987' But if i print those value like : for i in some_model.objects.filter(info='some thing'): print i.message I get the correct input . But i cat print out any thing in django to webpages . So what should i do ? -
Heroku error code=H10
I'm trying to deploy my first django app on Heroku. I get the following error- 2017-06-05T17:20:16.947355+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xyz.herokuapp.com request_id=1c8fc84d-5edd-406e-b601-2d4fbcb94453 fwd="xxx.xxx.xxx.xx" dyno= connect= service= status=503 bytes= protocol=https 2017-06-05T17:20:18.050308+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=xyz.herokuapp.com request_id=5b81e441-895e-4115-af15-ae82496dc8a8 fwd="xxx.xxx.xxx.xx" dyno= connect= service= status=503 bytes= protocol=https How should I resolve it? -
Django handle photo upload
I have model whiuch has photo attachment. class Forum_message(models.Model): text = models.TextField() photo = models.ImageField(upload_to= 'forum_attachments') I have my form(I prefer writing forms in pure html so I can have full access to modifying them) <form action="/forum_new" method="post" enctype="multipart/form-data"> {% csrf_token %} <input id="img_msg" type="file"> <textarea name="new_msg"></textarea> <input type="submit" value="Submit"/> </form> What do I write in my function def forum_new(request): in views.py to handle file upload and save new forum message to database? -
How to encode a not equal to operator to filter a URL? Django
I am trying to filter out some values from a Web API and I am encoding my requests into python dictionaries to avoid receiving the complete data set from the URL, however, I want to implement a not equal operator where purchase is not equal to pets. How can I do that? from django.shortcuts import render from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.response import Response from collections import Counter from datetime import datetime, timedelta import json, urllib.request, dateutil.parser, urllib.parse url = "http://10.61.202.98:8081/T/ansdb/api/rows/dev/data/tickets" #not equal to parameter should be applied here parameters = {'user': 'P. J.', 'purchase':'pets'} encoded_parameters = urllib.parse.urlencode(parameters) encoded_parameters = encoded_parameters.encode('utf-8') make_request = urllib.request.Request(url,encoded_parameters) with urllib.request.urlopen(make_request, timeout=15) as url: complete_data_user = json.loads(url.read().decode()) -
mysqlclient pip failure on Linux
I'm working on a Python3.4/Django project (on CentOS 6.8x64) and am trying to install the mysqlclient driver. Despite hours of googling I can't figure out how to sort out what looks like a compile error during install. As far as I can tell I have all the necessary library packages installed but so far no luck. Here's the output (sorry for the verbosity): $ sudo pip3 install mysqlclient Collecting mysqlclient Using cached mysqlclient-1.3.10.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command /usr/bin/python3.4 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-qqqgbh_2/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-cwqrqsw1-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-3.4 copying _mysql_exceptions.py -> build/lib.linux-x86_64-3.4 creating build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.4/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.4/MySQLdb creating build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-3.4/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-3.4 gcc -pthread -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE … -
DjStripe webhooks during localhost development
Webhooks in local dev I believe Dj-Stripe only creates DB entries for Charges and Invoices via webhooks -- correct me if I'm wrong. I'm currently using Customer.get_or_create, then doing customer.subscribe(plan_id). I've noticed this subscribes the customer but doesn't create any affiliated model entries such as charges and invoices. In production, I know I can set up webhooks so that these entries are created, but is it possible during localhost (without some weird network forwarding things). I want my local dev environment to be as close to production, but obviously if I can't get these models being created it will be quite different. Subscribing customers Also, is there a better way to subscribe customers than having to use the deprecated settings plan_id? I'm currently doing a look-up in my settings with stripe_plan_id in order to find the correct settings plan_id to pass to customer.subscribe, I'm assuming this isn't the correct method. -
django: celery vs channels vs in-view
Assume a button on my page which when clicked fires off an ajax request to my api endpoint which then fetches data from a 3rd party site. Let's say this task takes around 2-5 seconds with a timeout at 5 seconds. What's the ideal way to do this: celery task.delay() in the api endpoint and return a url to poll every x intervals for the result. just do it in the view It would seem that all tutorials suggest the celery way, but that seems like a lot of machinery/overhead for a simple request with minimal processing. Is there some generally accepted threshold (seconds till completion, etc..) in which one would choose one over the other? Then there is django-channels which seems like it would be ideal for this. But, on first glance, the distinguishing line between channels workers and celery tasks seems blurred. Can I replace celery with the channels workers and just use that for the above stated task? Would channels also handle my longer running tasks? What would be the advantages/drawbacks with channels (either with celery or replacing celery)? Finally, which of the 3 (celery/channels/in-view) would be the recommended approach to the example scenario given? -
Django Template Foreign Key BooleanField: Get Unread Article
Thank you for taking your time. I would like to establish a function for users to see which posts they have not read yet and which ones they have. What I have done: I managed to show what a user has already read. My Problem: I cannot manage to show a user what he or she has not read. Because An article which has been read by A should still remain "Unread" to B. My model: class Posts(models.Model): title = models.CharField(max_length=255) content_url = models.URLField(unique=True) content = models.CharField(max_length=255) post_date = models.DateField(default="2999-12-12") Another class readstatus(models.Model): reading_status = models.BooleanField(default=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) article = models.ForeignKey(piaoyou, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) My View: class DailyReading(ListView): model = piaoyou template_name = 'reading.html' context_object_name = "data" paginate_by = 20 My Template: {% if "/read/" in request.path %} {% for info in data %} {% for read in info.readstatus_set.all %} {% if request.user == read.user %} <quoteblock> <ul> <li><a href="{{ info.get_absolute_url }}">{{ info.title }} <footnote></footnote> </a>{{ info.post_date }}</li> <footnote>{{ info.get_abstract_content }}</footnote> </ul> </quoteblock> {% endif %} {% endfor %} {% endfor %} {% else %} {% for info in data %} {#NEED HELP HERE, HOW DO I SHOW A UNREAD ARTICLE WHICH HAS BEEN READ BY ANOTHER … -
Django - Accessing sublist of list in for loop
I have a query that outputs data in the following format: [["W/E 6/11/17", "Carter, Jon", 40.0], ["W/E 6/18/17", "Carter, Jon", 40.0], ["W/E 6/11/17", "Linn, Kenneth", 27.0], ["W/E 6/18/17", "Linn, Kenneth", 27.0], ["W/E 6/11/17", "Massey, Smiley", 55.0], ["W/E 6/18/17", "Massey, Smiley", 45.0]] My query: emp3 = ( Projectsummaryplannedhours.objects.values( 'employeename', 'displayval') .order_by() .filter(businessunit='a') .filter(billinggroup__startswith='PLS - Pip') .filter(Q(displayval=sunday2)|Q(displayval=sunday)) .annotate(plannedhours__sum=Sum('plannedhours')) ) In my template, I'm currently using a for loop, but it returns all items in the list, rather than just the first list of lists. {% for x in emp3 %} {{x.employeename}} {{x.plannedhours__sum}} What I would like to do is iterate through the list and display Employee: Value for W/E 6/11, Value for W/E 6/18 in a horizontal form. Any ideas? I'm at a loss. -
Django: asynchronously load data when page is requested?
I am new to Django and have completed the 7 part tutorial and am now trying to learn more by making my own app. Suppose you are making an interactive data visualization application where the front end is powered by d3 (or your favorite JS library) and your data is coming from the server. Since your data is large, you first have to load it into server memory (maybe from a binary file, or however you store it). Yet you don't want your user to be looking at a blank page when they could be seeing the rest of the site (maybe filling in some parameters for the interactive data). How can you, when a user requests a web-page, load and maintain data in memory on the server while Django still renders the page as well as maybe sends POST requests to update some server side information? -
Auto define name of multi upload-images
can you tell me someone how can auto define names for name field in my model using name from path image ?because i use multi upload images i want to define names of images automate. in simple python that look like this this : filepath = 'C:/Users/username/Desktop/dj/imagename.png' layer_name = filepath[:-4].split('/')[-1] # get the layer name my model : class MyModel(models.Model): name = models.CharField() user = models.ForeignKey(User, unique=False) upload = models.ImageField(upload_to=user_directory_path) -
Django deepcopy object with foreign keys
A usual copy of a certain object of class A in Django would look like this: obj = A.objects.get(...) # get the object obj.id = None obj.save() However if class A has a foreign key of some class B than the copy will reference the same object as the initial object, which will break constraints sometimes. How can I make django recursively duplicate all the referenced objects as well? I suppose it would look something like this: def duplicate(obj): obj.id = None obj.save() refs = ? # somehow get the inner objects which are foreign keys for inner_obj in refs: duplucate(inner_obj) obj = A.objects.get(...) # get the object duplicate(obj)