Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Limit to size of database-backed sessions?
Django's documentation (here) state that cookie-based sessions can exceed the 'standard' of 4096 bytes per cookies. What about database-backed sessions, is there a limit to the amount of data that can be stored in the session? I didn't see anything in the documentation, nor on SO. For my project, I'll need to save ~50KB to a user's database-backed session. Let me know if you need more info. -
Cannot send email using django and nginx(gunicorn) on digital ocean droplet
I deployed a website using django + nginx + gunicorn on a ubuntu droplet. And I use the email function of django. However, every time I tried to send email, I got a 502 error in my website. And my nginx error log is: [error] 24933#24933: *30944 upstream prematurely closed connection while reading response header from upstream, client: 45.34.23.99, server: server.cn request: "GET /confirmation-email-send/3/ HTTP/1.1", upstream: "http://unix:/tmp/server.cn.socket:/confirmation-email-send/3/", host: "server.cn", referrer: "https://server.cn/signup/contestant" Settings.py in django: EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.sina.com' EMAIL_HOST_USER = '****@sina.com' EMAIL_HOST_PASSWORD = '****' EMAIL_PORT = 465 EMAIL_FROM = '****h@sina.com' /etc/nginx/sites-available/server.cn: server{ charset utf-8; listen 80; listen 465; server_name server.cn; location /static { alias /path/to/static; } location / { proxy_set_header Host $host; proxy_pass http://unix:/tmp/server.cn.socket; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/server.cn/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/server.cn/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot if ($scheme != "https") { return 301 https://$host$request_uri; } # managed by Certbot } The function of sending email works well when I run the website at localhost. So I think the problem is in deploying. I've seen some similar questions but the methods provided can not solve my problem. -
Need helping creating a Poke (think Facebook) app using Django
So I'm having trouble completing this task. Basically, it's supposed to only be two pages. One is a login/registration page. The other is a page with a table that allows you to Poke other users. I've made the login/reg page work (with validations) and I've gotten the logged in user to not appear on the table on the 2nd page. I've also used Jinja to display the logged in user's name on the html. Now, I'm still missing a few things. How to display the number of people that have poked you using Jinja. A list of people that have poked you and how many times they have done so. Getting the actual poke buttons to function and track the logged in user poking the corresponding user on the table. I think I'm heading in the right direction but am really struggling with the Poke functionality. Can you guys and girls lend a hand? Thanks! Here is the link to a pastebin containing all the code from both apps, or see the code below. Edit: Please see the link here to see my progress so far. Please use the username: jdoe@gmail.com and password: password in order to login and view … -
Correct way of starting a session with Django REST Framework
I want to use the SessionAuthentication of DRF, so I looked for solutions for starting the session. I found several answers suggesting to create a basic password authentication which calls Django's login function in the end, so it looks something like this: def authenticate(self, request): #Check credentials, etc login(request, user) return user, None This however didn't work for me, because the login functions tries to get the request.user attribute, which triggers DRF to start it's own authentication process calling my basic authenticationen and thus creating an infinite loop. My next approach was to call the login function inside of the post function of my authentication view: def post(self, request, format=None): #Authentication already done by DRF, so no errors expected username = request.data.get('user') password = request.data.get('password') user = authenticate(request=request, username=username, password=password) login(request, user) But now everything is done multiple times for each login, because DRF launches the authentication before the function, then I need to get the user again and lastly DRF authentication is launched a second time by the login function. This works so far, but isn't very effective and I am pretty sure there are better ways of doing that (without bypassing DRF). -
JQuery Validator and Django
I have a code in views: def check_username(request): if HttpRequest.is_ajax and request.method == 'GET': username = request.GET['username'] if User.objects.filter(username=username).exists(): print('duplicate') # have this for checking in console return HttpResponse(False) else: return HttpResponse(True) else: return HttpResponse("Zero") It takes the request from JQuery and that print('duplicate') works right, printing only when I have duplicate. My JS code: $("#formregister").validate({ rules: { username: { required: true, remote: "http://127.0.0.1:8000/accounts/checkname" } }, messages: { username: { required: 'you MUST have username', remote: 'gogogog' } } }); }); "You MUST have username" works properly, but I can't get remote message. What am I doing wrong? Thanks! -
Using for loop in Python HTML template to load images
I'm pretty new to Python so sorry for the newbie question. Using Django, I'm trying to load a few hundred images from a remote server. I simply want to load three per row. I've created an object in the view which does a images.object.all() query and returns it to the template. All I want to do is loop through the images and place a break at the end of each 3rd image. My code is {% for image in images %} <img width="200px" src="http://www.somewebsite.com/{{ image.url_pre_string }}{{ image.filename }}.{{ image.extension }}" /> {% endfor %} I've tried doing an if else inside the for loop but I need a counter variable to count the images and that just fails badly. Is there an easy way to do this in Django? -
UnboundLocalError: local variable 'form' referenced before assignment in Django
So i'm working on a django project and this is my views.py file: def new_topic(request, pk): board = get_object_or_404(Board, pk=pk) user = User.objects.first() # TODO: get the currently logged in user if request.method == 'POST': form = NewTopicForm(request.POST) if form.is_valid(): topic = form.save() return redirect('board_topics', pk=board.pk) else: form = NewTopicForm() return render(request, 'new_topic.html', {'form': form}) When i ran my server, i got an error saying UnboundLocalError: local variable 'form' referenced before assignment This is my new_topic.html file {% extends 'base.html' %} {% block title %}Start a New Topic{% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{ board.name }}</a></li> <li class="breadcrumb-item active">New topic</li> {% endblock %} {% block content %} <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Post</button> </form> {% endblock %} -
Displaying word/pdf document with django in html giving problems
I am trying to display word files and pdf files that are user uploads. I am getting the error: Reverse for 'project.file.path' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []. This is my iframe <iframe src="https://view.officeapps.live.com/op/embed.aspx?src={% url 'project.file.url' %}"> </iframe> I am using office 360 to read the word file. My urls are like this: urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How can I fix this error, and are there better alternatives for displaying word documents with Django? My user uploads are stored within the media directory folder. The media folder and the Django project folder are at the same directory level. -
Django dynamic model design
I have a table that contains a dynamic number of entries, each entry contains data (like id, name, date) and also 3 radio buttons. class Entry(models.Model): id = ... name = ... data = ... selected_option = ... I want to save all of the entries in the DB when the user submits the form. I was wondering what would be the best way to design the model for this. -
Copy file into another folder with django?
I need to upload profile images into diferent folders in Django. So, I have a folder for each account, and the profile image have to go to the specific folder. How can I do that? Here is my uploadprofile.html <form action="{% url 'uploadimage' %}" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" name="avatar" accept="image/gif, image/jpeg, image/png"> <button type="submit">Upload</button> </form> And here is my view in views.py def uploadimage(request): img = request.FILES['avatar'] #Here I get the file name, THIS WORKS #Here is where I create the folder to the specified profile using the user id, THIS WORKS TOO if not os.path.exists('static/profile/' + str(request.session['user_id'])): os.mkdir('static/profile/' + str(request.session['user_id'])) #Here is where I create the name of the path to save as a VARCHAR field, THIS WORKS TOO avatar = "../../static/profile/" + str(request.session['user_id']) + "/" + str(img) #THEN I HAVE TO COPY THE FILE IN img TO THE CREATED FOLDER return redirect(request, 'myapp/upload.html') -
Django queryset union appears not to be working when combined with .annotate()
I have the following queryset photos = Photo.objects.all() I filter out two queries. a = photos.filter(gallery__name='NGL') b = photos.filter(gallery__name='NGA') I add them together, and they form one new, bigger queryset. c = a | b Indeed, the length of a+b equals c. a.count() + b.count() == c.count() >>> true So far so good. Yet, if I introduce a .annotate(), the | no longer seems to work. one = photos.annotate(c=Count('label').exclude(c__lte=4) two = photos.filter(painting=True) all = one | two one.count() + two.count() == all.count() >>> False How do I combined querysets, even when .annotate() is being used? Note that query one and two both work as intended in isolation, only when combining them using | does it seem to go wrong. -
Limiting one appointment per user
I'm trying to make it so users are only able to schedule one appointment. Here I am modifying the save method. What I am trying to figure out is how to see if that user already has an appointment. def save(self, *args, **kwargs): if Appointment.objects.filter(owner=user_pk).exists() and not self.pk: # if you'll not check for self.pk # then error will also raised in update of exists model raise ValidationError('You have already scheduled an appointment.') return super(Appointment, self).save(*args, **kwargs) In my views.py I already have something that will raise an error if an appointment with that user already exists. But i'm thinking this is not enough and that there should be something at the model level. appointments = Appointment.objects.filter(owner=request.user) if appointments.exists(): raise PermissionDenied('You have already scheduled an appointment.') -
AttributeError: 'module' object has no attribute 'lru_cache' while installing Django 2
I'm using ubuntu and I got python 2.7 and python 3.4.3 installed on my OS. I'm trying to install Django 2 and it does not supports python 3, I get this error while trying to install it using pip install -U Django or pip install Django --upgrade: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 17, in File "/tmp/pip_build_alex/Django/setup.py", line 32, in version = import('django').get_version() File "django/init.py", line 1, in from django.utils.version import get_version File "django/utils/version.py", line 61, in @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' I've read this question and another one, only to see that answers are offering OP to install a lower version of django!, but that's not a real answer to such question. I tried alias python=python3 to set python 3 as default python but failed to get a working solution. How can I install Django 2 in a OS with 2 versions of python without getting this … -
Django - could not parse the remainder: '[loop.index] [duplicate]
This question already has an answer here: Django - iterate number in for loop of a template 2 answers Both name and data are lists being returned from a view template: {% for row in data %} <table class="table"> <tr> <td>{{% name[loop.index] %}}</td> </tr> {% for league in row %} <tr> <td>{{ league.name }}</td> </tr> {% endfor %} </table> {% endfor %} Exception: Django Version: 1.11.7 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '% name[loop.index] %' from '% name[loop.index] %' any help would be appreciated -
Exited with exit code 3 on running heroku local
I tried to use the heroku command line tool following the tutorial on https://devcenter.heroku.com/articles/heroku-local It exited with exit code 3. $ heroku local [OKAY] Loaded ENV .env File as KEY=VALUE Format 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Starting gunicorn 19.4.5 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Listening at: http://0.0.0.0:5000 (13114) 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13114] [INFO] Using worker: sync 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [INFO] Booting worker with pid: 13119 01:53:43 web.1 | [2017-12-30 01:53:43 +0000] [13119] [ERROR] Exception in worker process: 01:53:43 web.1 | Traceback (most recent call last): 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker 01:53:43 web.1 | worker.init_process() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process 01:53:43 web.1 | self.load_wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi 01:53:43 web.1 | self.wsgi = self.app.wsgi() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi 01:53:43 web.1 | self.callable = self.load() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load 01:53:43 web.1 | return self.load_wsgiapp() 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 01:53:43 web.1 | return util.import_app(self.app_uri) 01:53:43 web.1 | File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app 01:53:43 web.1 | __import__(module) 01:53:43 web.1 | File "/home/palak/python-getting-started/gettingstarted/wsgi.py", … -
Highcharts Data Parsing List of lists
I'm using Django and I am trying to parse the data I am putting into my template to load into high charts. This is the first I'm using High Charts and I was unable to locate a way of parsing it this way. Right now my data is presented like [["Date", "Product1", "Product2"],["Dec 28 2017", 2, 2], ["Dec 29 2017", 2, 2]] How do I make a column chart where the bars are under each day. Thanks -
Does Django automatically detect the end user's timezone?
I am building an application in Django which allows the end-user to retrieve information which is sensitive to the time of day (12 am to 12 am) on a given day. I store this information in my database as an integer representing the seconds since midnight in 30-minute increments. I was looking at Django's timezone documentation: https://docs.djangoproject.com/en/2.0/topics/i18n/timezones/ and found myself confused on whether or Django automatically uses the end-users time, or if I must collect this information and account for it in my views. Any information would be helpful! Thanks. -
Get parameter value in template
I have such url pattern: url(r'^drinks/(?P<drink_name>\D+)/',TemplateView.as_view(template_name='drinks/index. html'),name="drink") How can I get access to drink_name parameter value in template. -
Django foreign key name on select
I'm working with 2 models each one in a different Django application: App products class Product(models.Model): name = models.CharField(max_length=256) price = models.FloatField() warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) def __unicode__(self): return self.name App warehouses class Warehouse(models.Model): name = models.CharField(max_length=256) def __unicode__(self): return self.name The probles is that in the admin site, when I want to create a product and I need to select a warehouse, in the select list I only see: Warehouse object Warehouse object Warehouse object What I have to do to see warehouse name? -
How To Upload Image From Admin Side In Pycharm (Django)
In Models.py, from django.db import models class Question(models.Model): question_text = models.CharField(max_length= 100) pub_date = models.DateTimeField('Date Is Published') image = models.ImageField(upload_to="Question_Image", blank=True) def __str__(self): return self.question_text class Choice(models.Model): choice_text = models.CharField(max_length= 200) votes = models.IntegerField(default= 0) question = models.ForeignKey(Question, on_delete= models.CASCADE) def __str__(self): return self.choice_text In settings.py, i added MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mysite/media') In mysite/urls.py, from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^polls/', include('polls.urls', namespace= "polls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In index.html, {% extends 'polls/base.html' %} {% block main_content %} {% if latest_questions %} <ul> {% for question in latest_questions %} <li><a href={% url 'polls:detail' question.id %}> <b>{{question.question_text}}</b> <img src="{{question.question_text.image.url}}"> </a> </li> {% endfor %} </ul> {% else %} <p> You have no questions. Please add some.</p> {% endif %} {% endblock %} but there seems to be no uploading of image which was what i wanted to add to poll app created from 'my first django app' videos on youtube. Please help. -
google cloud sotrage download file with encoded path included
I am using Google Cloud Storage API to manage my files. and when I download a file from link created. it downloads path together like this. movie%2F316029%2Fko%2FThe.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi instend The.Passion.Of.the.Christ.2004.DVDRip.XviD.AC3.CD2-CiPA.smi is there have a way that fixes or turn off encoding path problem? I am using python3.5.2 Django 2.0 with Google Cloud Library. -
How to set User in request.user in Django
How i can set my own user in request.user or request.session.user my own models: class User(Document): id = fields.IntField(primary_key=True) username = fields.StringField(required=True) email = fields.EmailField() .... @property def is_authenticated(self): return False I set this in my view user = User.objects.get(email=email) request.session.user = user but didn't work. -
Is it ok to use the anaconda distribution for web development?
I started learning Python working on projects involving data and following tutorials advising to install the anaconda bundle, to take advantage of the other libraries coming with it. So did I and I got confortable with it, I liked the way it manages environments. During the last months, I have been teaching myself web development with django, flask, continuing to use the anaconda python. But most of the time I install the dependencies I need with pip install though (inside the conda environment). I've never seen any tutorials or podcasts mentioning the conda environment as an option for developing web apps so I start to get worried. Is it for a good reason? Everywhere its the combination of pip and virtualenv that prevail. And virtualenv isn't compatible with anaconda that has its own env management system. My newbie question is: Will I run into problems later (dependencies management in production or deployment maybe?) using the anaconda distribution to develop my web apps? -
Django Email Confirmation activation view not working
I am trying to set up an email confirmation for my django application. This is the activation URL: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), and this is the activate view: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = get_user_model().objects.get(pk=uid) except (TypeError, ValueError, OverflowError, get_user_model().DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.email_confirmed = True user.save() login(request, user) return redirect('profile') else: return render(request, 'email/invalid_token.html') This is the error I am getting: TypeError at /activate/MzQ/4se-cb054dd0a60fb9f85110/ activate() got an unexpected keyword argument 'uidb64' Any help would be appreciated. -
How to re-sort search results in-place without having to re-send a request in django?
Here is the scenario: I have a search page, with some form elements providing multiple filter conditions (something like 'advanced search'), and probably a nested ListView to display the search results in-place. What I would like to achieve: Whenever the user changes some filter conditions, the result list below responds in-place (taking another request for this could be accepted); When the user changes the sorting option, the results change their ordering immediately, without sending another request, either synchronous or by ajax. From the server side it would be as simple as changing the order_by attribute of a QuerySet, but I would like it in a front-end way. So I wonder if it is possible to achieve that. It seems to me that the filtered QuerySet could be somehow kept at the client side. Is it possible by pure Django using some mechanism like session? Or will it have to take some front-end frameworks such as AngularJS or Vue.js? Or is it not even possible (If so, is there any approach taking the minimal extra network payload?)