Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Class based view - Validate form per step on a multistep registration form?
Context: I'm creating a multi-step registration form using Createview, and I would like to validate some data entered in, say, step 1 and notify the user before we proceed to the next stage. I'd also like the validation to not impact the type in which data were entered (eg date fields being rendered to a date object after validation). Data entered need to be preserved between transition as well. I'm used to doing front-end validation first, in combination with backend, but since I'm using Createview, I don't have direct access to the data entered, so it's gone a bit different and I can't think of a better way of accomplishing this. Any help would be greatly appreciated. -
Is it bad to pass my entire `request` object to my `Models.py` for validations in Django when using django-messages?
Having trouble finding a totally clear answer to this question. In my learning, I was taught to not pass along the entire request object when trying to pass data from views.py to models.py (and to take advantage of Django Managers to do validations). However, in my current scenario, I'm trying to setup validation methods in my models.py (using a Manager) whereby I utilize django-messages (https://docs.djangoproject.com/en/1.11/ref/contrib/messages/), to whom one requirement is the request object itself when generating custom errors, such as: messages.add_message(request, REG_ERR, 'First and last name are required must be at least 2 characters.', extra_tags="reg_errors") I am trying to keep all validations, error message generation, and creation or retrieval actions inside of my models.py using a manager (https://docs.djangoproject.com/en/1.11/topics/db/managers/), and simply hand back the relevant data to my views.py. To achieve this, in my views.py, I create a dictionary with the full request object itself, I send this off for all validations/creations, and then check for errors upon the return, as a False is returned if any validation errors were flagged. Otherwise the success page will load with the new user. views.py: def register(request): if request.method == "POST": # Prepare form data as dict for validation: register_data = { "request": request, … -
Django doesn't render variable after a few lines
I just don't get it. Somehow django does't want to render a variable even if django to it 2 line before. This is my definition in my views.py: def BrandDetails(request, brand_id): brand = Brands.objects.get(id=brand_id) brand_name = brand.name brand_pic = brand.img brand_concern = Concerns.objects.get(id=brand.concern_id).name brand_company = Companies.objects.filter(id=brand.company_id) brand_fair = brand.fair brand_eco = brand.eco context = { "brand_id": brand.id, "brand_name": brand.name, "brand_pic": brand.img, "brand_company": brand_company, "brand_concern": brand_concern, "brand_fair": brand_fair, "brand_eco": brand_eco, } return render_to_response("database/details.html", context) an here is my html-snipped: {% extends "database/index.html" %} {% block details %} <div id="DetailsContent"> <img src="{{brand_pic}}"></img><br> Markenname: {{ brand_name }}<br> Unternehmen: {{ brand_company }}<br> Konzern: {{ brand_concern }}<br> Fair: {% if brand_fair > 0 %}Ja{% endif %}Nein<br> Öklogisch: {% if brand_eco > 0 %}Ja{% endif %}Nein<br> <h3><a href="http://localhost:8000/database/"> Neue Suche? Einfach hier klicken </a></h3> </div> {% endblock %} The result looks like this: enter image description here I tested the query in the manage.py shell and there it works perfectly. You can also see that the brand.name and the brand.img are shown, also brand.fair and brand.eco (even if the if-statement doesn't work, but that's another problem, but the become displayed). Maybe the model helps also, this is the model of Brands: class Brands(models.Model): name = models.CharField(max_length=50, … -
Create a Django Model which can trace url infomations automaticlly
I use Django, and i want to create a Model which can trace url information automatically. Just like model Contentype from django.contrib.contenttype.models can trace app and models automatically. The Model i want create like below: class UrlsModel(models.Model): app_label = models.CharField(max_length=30) url_pattern = models.CharField(max_length=100) url_name = models.CharField(max_length=50) just create the Model is easy, but how can i make it track the urls infomations automatically? -
Within a single Django View, Handling multiple JSON responses after submitting multiple forms via AJAX
I am trying to submit multiple forms via AJAX calls within a single Django view. After I submit the first form, the response returned is correct. However when I submit a second form, the page refreshes with the JSON response when it should just $().replaceWith() the element as it does with the first form submission. Here is the JS: <script type="text/javascript"> $("#mark_sold").on('submit', function(event){ event.preventDefault(); $.ajax({ url: "/raw/ajax/mark_sold/", type: "POST", data: { pk: $('.pk_value').val(), csrfmiddlewaretoken: $('[name="csrfmiddlewaretoken"]').val()}, success: function(data) { $('#mark_sold').replaceWith(data) }, }) }) </script> The Django function being called: def mark_sold(request): .... return HttpResponse({'Sold': 'Sold'}) And the HTML form being generated for each object on my ListView: <form id="mark_sold" action="/raw/ajax/mark_sold/" method="POST"> {% csrf_token %} <input type="hidden" name="pk" class="pk_value" value="{{ object.pk }}"> <input type="submit" id="submitButton" name="submitButton" value="X"> </form> What is causing the page to redirect to the JSON response rather than follow the JS function? Thank you in advance for your help! -
Gulp - Error: listen EADDRINUSE :::35729?
Why do I get this error: [00:10:35] Using gulpfile /var/www/html/xxxxx/gulpfile.js [00:10:35] Starting 'sass'... [00:10:36] Finished 'sass' after 307 ms [00:10:36] Starting 'watch'... [00:10:36] Finished 'watch' after 435 ms ... Uhoh. Got error listen EADDRINUSE :::35729 ... Error: listen EADDRINUSE :::35729 at Object.exports._errnoException (util.js:1050:11) at exports._exceptionWithHostPort (util.js:1073:20) at Server.setupListenHandle [as _listen2] (net.js:1259:14) at listenInCluster (net.js:1307:12) at Server.listen (net.js:1406:7) at Server.listen (/var/www/html/xxxxx/node_modules/tiny-lr/lib/server.js:138:15) at exports (/var/www/html/xxxxx/node_modules/gulp-livereload/gulp-livereload.js:23:14) at Gulp.<anonymous> (/var/www/html/xxxxx/gulpfile.js:28:18) at module.exports (/var/www/html/xxxxx/node_modules/orchestrator/lib/runTask.js:34:7) at Gulp.Orchestrator._runTask (/var/www/html/xxxxx/node_modules/orchestrator/index.js:273:3) I don't understand it. This is my gulpfile: var gulp = require('gulp'), autoprefixer = require('gulp-autoprefixer'), livereload = require('gulp-livereload'), sass = require('gulp-sass'); var paths = { scripts: ['static/js/**/*.js'], sass: ['static/sass/**/*.scss'], sassLibs: ['static/js/libs/sass-bootstrap/lib'], cssOutput: 'static/dist/css/', templates: ['templates/**/*.*'], python: ['src/website/**/*.py'], }; gulp.task('sass', function () { return gulp.src(paths.sass) .pipe(sass({ includePaths: paths.sassLibs })) .pipe(autoprefixer("last 1 version", "> 1%", "ie 8", "ie 7")) .pipe(gulp.dest(paths.cssOutput)); }); gulp.task('watch', ['sass'], function () { var server = livereload(); var reloadPaths = [] .concat([paths.cssOutput]) .concat(paths.scripts) .concat(paths.templates) .concat(paths.python); // Recompile SASS files when they have changed. gulp.watch(paths.sass, ['sass']); // Notify livereload server when files have changed. gulp.watch(reloadPaths).on('change', function(file) { server.changed(file.path); }); }); /* * Make a complete build. */ gulp.task('default', ['sass'], function () { }); It is working fine on my dev server but not on my production server. Any … -
Django permission behaviour on referenced models
Assume I use guardian or some other object permission lib in django. I have a model e.g. XYModel, and the XYModel contains a 1-M reference to the Model Property. In this example, let's say I have CRUD Permissions, on the XYModel object, and on all of it's referenced Propertiy objects, except for one. What will happen if I sent a PUT Request, to update the XYModel object, and it's properties. Would django save all except for the one property, or would it just skip everything, because of the missing permissions on the one property reference? Thanks in advance -
How to enable creating Django Inline model admin?
I'm creating django app and I need to do next thing. I've model with many 2 many relations through content type. I user TabularInline and get following How can I add new m2m item right from this page? thanks -
Django TemplateDoesNotExist, but traceback reaches views.py
I have a begin.html file that I'm trying to access at localhost:8000/begin, but I get the DjangoTemplateDoesNotExist error when trying to access it. The only thing in that template is <h1>welcome to my app !</h1> and it's in the app/template directory. In the same app directory is my views.py file, which contains # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render # Create your views here. def begin(request): print("DEBUG STATEMENT") return render(request, "template/begin.html", {}) The return statement in begin is reached, as both the print statement and the traceback tell me, but Django can't find the template after. If it's relevant, my urls.py file is from django.conf.urls import url from django.contrib import admin from app.views import begin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^begin/$', begin, name = 'begin') ] in the project directory. -
Displaying models specific to a user in django 1.0
I created a model Song and allowed users upload songs to my website. I was wondering how to display all of the songs uploaded by a user -
django + virtualenv + gunicorn - No module named django.core.wsgi?
I have gunicorn installed inside my virtual env: $ pip install gunicorn Collecting gunicorn Using cached gunicorn-19.7.1-py2.py3-none-any.whl Installing collected packages: gunicorn Successfully installed gunicorn-19.7.1 But when I try run my app with it: $ gunicorn helloapp.wsgi [2017-05-18 22:42:36 +0000] [1963] [INFO] Starting gunicorn 19.6.0 [2017-05-18 22:42:36 +0000] [1963] [INFO] Listening at: http://127.0.0.1:8000 (1963) [2017-05-18 22:42:36 +0000] [1963] [INFO] Using worker: sync [2017-05-18 22:42:36 +0000] [1967] [INFO] Booting worker with pid: 1967 [2017-05-18 22:42:36 +0000] [1967] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 557, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 136, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 384, in import_app __import__(module) File "/var/www/html/django-project/helloapp/helloapp/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi [2017-05-18 22:42:36 +0000] [1967] [INFO] Worker exiting (pid: 1967) [2017-05-18 22:42:36 +0000] [1963] [INFO] Shutting down: Master [2017-05-18 22:42:36 +0000] [1963] [INFO] Reason: Worker failed to boot. What I have done wrong? This is my app structure: Any ideas? This is my requirments.txt: appdirs==1.4.3 Django==1.11.1 … -
in_round() function in oTree
The function someFunction tries to access the variable choice of a pervious round. When I call the function from a template file everything works out fine. If I call it from before_session_starts(), player.participant.vars['someKey'] contains None. def before_session_starts(self): if self.round_number == 3: for player in self.get_players(): player.participant.vars['someKey'] = player.someFunction() class Player(BasePlayer): choice = models.CharField(initial=None, choices=['A','B','C'], widget=widgets.RadioSelect()) def someFunction(self): return self.in_round(2).choice Why is this happening? -
Django+fcgi+Nginx hyperlinks errors
Good day! I'm pretty new to Django. My project contains several apps (catalog, parts, registration etc.) and that, how main url.py looks like: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^registration/', include('registration.urls', namespace='registration', app_name='registration')), url(r'^parts/', include('parts.urls', namespace='parts', app_name='parts')), url(r'^catalog/', include('catalog.urls', namespace='catalog', app_name='catalog')), url(r'^$', TemplateView.as_view(template_name='base.html'), name='base'),] And that how looks one of apps urls.py: `urlpatterns = [ url(r'^(?P<username>[\w ]+)?$', views.catalog, name='catalog'), url(r'^transactions/$', views.catalog_transactions, name='catalog_transactions'),` etc. etc. Everything worked fine on django testserver, but when i tried to run it with fcgi+Nginx, i've stucked with hypelink problem. When i click on one of hyperlinks on first page it somehow keeps its address and when i try to click another link it appends it to first one. For example, if my first click goes to ip_address:port/catalog/ then other hyperlink on that page transforms into ip_address:port/catalog/some_page/ instead of ip_address:port/some_page/ I use {% url %} tags for all hyperlinks in my templates, so links look like <a href="{% url catalog:some_page %}">Some_page</a> That, how looks my Nginx configuration: `server { listen 9090 default_server; server_name mtsk.tools.com; merge_slashes off; location / { fastcgi_pass 127.0.0.1:99; include fastcgi_params; } location /static/ { root /Django/Parts/; }}` Django version is 1.8 Nginx version is 1.11.10 fcgi version is 2.4.0-2 Did anyone stucked with similar … -
check a queryset for existing object
I want to check if a queryset contains an object. this is one the attribute which is pointing towards another class : profile_skills = models.ManyToManyField(Skill, through = 'ProfileSkill') I am iterating over the attributes. for key in diction: if key.startswith('profile') and key.endswith('s'): for ob in percent: if ob.field_name == key: if getattr(self, str(key)).exists(): -
Filtering "downstream" related objects in Django's ORM?
Is there a way to filter related objects in a class. I am not talking about filtering BY related objects but instead filtering the related objects themselves IN a class. Perhaps an example would better illustrate: Say I have the following model: class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', null=True) isbn = models.CharField('ISBN',max_length=13) genre = models.ManyToManyField(Genre) class Genre(models.Model): name = models.CharField(max_length=200) ... class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('Died', null=True, blank=True) I know how to do the straightforward filtering like getting all books for a specific genre: books = Books.objects.filter(genre=1) and then looping through this in the view: {% for book in books %} {{book.title}} {% endfor %} But, is there a way to filter a queryset's related objects? Let's say I have an already filtered author queryset and I ONLY want to list his books FROM a specific genre: If I do this: {% for book in author.books_set.all %} {{book.title}} {% endfor %} I get ALL of his books (as I would expect and want). But, is there a way to do something like this: {% for book in author.books_set.filter(genre=1) %} {{book.title}} {% endfor %} so that I am only … -
Django error : smtplib.SMTPDataError
>>> from django.core.mail import send_mail>>> send_mail("allo", 'here is the message', '@gmail.com', ['gauthier.jeremie.1@gmail.com'], fail_silently=False) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/jeremie/Desktop/email_test/myvenv/lib/python3.5/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/home/jeremie/Desktop/email_test/myvenv/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/jeremie/Desktop/email_test/myvenv/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/home/jeremie/Desktop/email_test/myvenv/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/usr/lib/python3.5/smtplib.py", line 883, in sendmail raise SMTPDataError(code, resp) smtplib.SMTPDataError: (421, b'4.3.0 collect: Cannot write ./dfv4IKaDvq007500 (bfcommit, uid=0, gid=133): No such file or directory') I am trying to send an email, and I obtain this error. How could I fix this issue? -
Django 1.11: Flip image horizontally before saving into a Django model
I'm doing this application where I take a user's image and then flip it horizontally using ImageOps from the Pillow library. To do so I made a model like above: from django.db import models class ImageClient(models.Model): image = models.ImageField(null=False, blank=False) I made a form using ImageField with a html form with enctype="multipart/form-data" and in my views I did the following: from django.shortcuts import render, redirect from .forms import ImageForm from .models import ImageClient from PIL import Image, ImageOps def new(request): """ Returns mirror image from client. """ if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): image = Image.open(form.cleaned_data['image']) image = ImageOps.mirror(image) form_image = ImageClient(image=image) form_image.save() return redirect('img:detail', pk=form_image.id) else: form = ImageForm() return render(request, 'img/new_egami.html', {'form':form}) .... As you see, when a check if the form is valid, I open the form's image and flip it horizontally (using ImageOps.mirror()) then I save it. But I always getting this error 'Image' object has no attribute '_committed'. I know the Image object is from Pillow, but I do not understand this error. Can someone explain and/or solve this error? -
Django admin validation not working propely after making custom model validation work
I have a Django model that uploads photos to a user's account. The upload model uses a Django auth user as a foreign key. I needed to ensure that each user could only upload 20 photos total and I wanted to do this at the model level so even the admin could not upload more. I got that working in a way but it broke my admin form validation. If I choose a related user, everything goes perfectly. It stops me from uploading more than 20 photos. But if I don't choose a user it gives me RelatedObjectDoesNotExist error. I am including my code and traceback here. Help would be appreciated. My models.py def photo_count(self): theModel = self.__class__ refModel = theModel.objects.filter(user=self.user) picCount = refModel.count() if picCount ==20: print(picCount) raise ValidationError ("You have already uploaded 20 photos. Delete some to upload more.") class StarPhotos(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) PHOTO_CATEGORY = ( ('HS', "Head Shot"), ('WP', "Western Party Wear"), ('IP', "Indian Party Wear"), ('SW', "Swim Wear"), ('CW', "Casual Wear"), ) category = models.CharField(max_length=2, choices=PHOTO_CATEGORY, default='CW') # This FileField should preferaby be changed to ImageField with pillow installed. photos = models.FileField(max_length=200, upload_to='images/',) def __str__(self): return "Images for {0}".format(self.user) def clean(self): photo_count(self) class Meta: … -
Are django modules global - ImportError: No module named django.core.management?
I am quite confused with how django works. I followed some guides and tested a sample app and got it running on my local dev machine. It works great. But when I moved this sample app to my production server, I got this error: # cd /var/www/html/helloapp # python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management So, during my setup for the sample app, I did this: $ sudo apt-get install python-django Then: $ django-admin startproject helloapp Then: $ cd /var/www/html/django-project/helloapp/ Then: $ python manage.py runserver Result: It worked! Congratulations on your first Django-powered page. So, I transferred the files helloapp/ into my production server: # cd /var/www/html/helloapp # python manage.py runserver Then there is the error: No module named django.core.management Do I have to install python-django in my production server - "globally" as one of my system software in my production server? What is django.core.management for actually? There might be many this kind of modules I need to run my app. So are these modules coming from django's "global" then? If my system broke or I removed python-django one day, all my django apps … -
In Django, are querysets a type or are they lists of objects?
Like a list or a dictionary, is a queryset a type or is it a list of objects that the database responds with? Are they syntactically anything special? How are they different from a list of objects? -
Textfield too long for docker?
I am currently updating an old website (running on Django 1.3) to the newer version (Django 1.10). My boss suggested I use Docker, because it would be easier to deploy with it, so now we're using Django + Docker + Gunicorn + Nginx (before it was just Django and Apache). We have a model called Article that keeps the content of the website. Content is a TextField. One of the Articles is a table, containing a list of shops. This article is quite long, over 65000 characters. The problem is, only the first 64416 chars are displayed if we run it inside of Docker. If I try running gunicorn directly on my laptop it's ok (entire page loads) and the same code ran from inside of the Docker container results in the truncated data. What's even more confusing, I ran manage.py shell and Article.objects.get(id=16) it returns the entire content, but Article.object.get(id=16).content gives once again only the first 64416 chars. My docker image is based on Alpine 3.3, my host os is Linux 16.10. What is the reason for this behavior? What's wrong? -
How to annotate Django view's methods?
I'd like to use Python type hints in my Django project. What's the proper way to annotate get/post methods of a simple class-based view in Django? I've searched the Django code itself but it doesn't seem to contain any type hints. -
Django Rest Framework - do not return url if imagefield doesnt exist
I have imagefield. The serializer is following class CategoryWithImagesSerializer(serializers.ModelSerializer): image_url = serializers.SerializerMethodField() def get_image_url(self, obj): return obj.image.url class Meta: model = Category fields = [ 'pk', 'name', 'image_url', ] In my model I have image described like this image = models.ImageField(verbose_name='Изображение', upload_to = 'images/', blank=True) With this setup I get crash when there is an object without image. I need a way of returning nothing instead of url if there is no image How can I do this ? -
Django CMS Project no such table: reversion_revision
I am building a relatively simple app using Django 1.9.13 and DjangoCMS, to be explicit. I get a pesky error presented below whenever I try to add a new user to the system (using Aldryn People Plugin for DjangoCMS). I also get this error when trying to add some other entities to the site. However, this error seems more Django-related than related to particular apps I am using. Hence, I am wondering if you have any suggestion on how one could fix this. Any help is appreciated. The error: no such table: reversion_revision Request Method: POST Request URL: http://localhost:8000/admin/aldryn_people/person/add/?language=en-us Django Version: 1.9.13 Exception Type: OperationalError Exception Value: no such table: reversion_revision settings.py """ Django settings for XXXXX project. Generated by 'django-admin startproject' using Django 1.9.13. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS … -
Django rest - understand cached results
I have slow queries in my Django restframework project. Many nested serializers causing slow HTTP requests (2-5 seconds) So I thought about using a cache that Django can provide with Memcache server. But I afraid I don`t really understand its behavior. What happens if the client request the same query non-stop every 1 second, and suddenly one of the objects changed? will the user get the cached results or Django will return the cached results with the specific change?