Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django refuses to cascade on delete
Django 1.9 with PostgreSQL. I have a model that looks like this: class MyCrossModel(models.Model): one_thing = models.ForeignKey('OneThing', on_delete=models.CASCADE) other_thing = models.ForeignKey('OtherThing', on_delete=models.CASCADE) When I go to delete one of these in the database, it cascade-deletes the one_thing, but does not cascade_delete the other_thing. Scouring the Django docs but cannot find any mention of this behavior. -
EmailField allows but get SMTPRecipientsRefused exception
I am sending an email on my django application. the recipient address is an 'EmailField' Here how I defined it on forms. recipient_email = EmailField( required=True, label="E-mail address", max_length=254, widget=forms.EmailInput(attrs={'size':'80'}) ) As a test case I tried an email address with exactly 254 characters. 7yvghdfsvy7dfvy7y7y7y7y7vy7vy7vyyvyy7v7dyvysdfuivhjkvcbherhe77fuihrubhvfhbervfhfhvuirdhfuier89f84ewr4wur4wurewuiehifhesfshjfbsdvsdvcbsdhvgcsvcsdhvcbsdvbsdhvbuisdvghuisdvh4e7h7f478fgy4f4yuwgf4yuwgf4whu4wfbferhjbfeshjbfshjbfhuewrfhb4wy84ygf@emtwwavds.co.jp I know this is not a valid email address but EmailField allows it. but while sending this email, i have got 'SMTPRecipientsRefused' exception. the exception value says too long (255 bytes max) If i delete a one character of the address, it is working fine with 253 characters. My problem is how this 254 characters got [too long (255 bytes max)] error? even though I have handled it by catching SMTPException, can anyone suggest me a better way to validate the email address, thus I can display better error message. Django version : 1.11.3 Python version : 3.6.3 -
request.META.get('CSRF_COOKIE')
I'm getting the "csrf token missing or incorrect" error in my django app. I have the csrf token in my template: <form action="/hello/compare_lname" method="post" enctype="multipart/form-data>{% csrf_token %} I use request in render() in my view.py: render(request, 'delta.html',{'delta_dict': delta_dict}) I put a print statement in _compare_salted_tokens in middleware.csrf print(request_csrf_token, csrf_token). request_csrf_token is changing. csrf_token doesn't change, even if I restart the server. csrf_token comes from: csrf_token = request.META.get('CSRF_COOKIE') Do I need to reset request.META.get('CSRF_COOKIE') somehow? -
getting debug/verbose from django "python manage.py makemigrate"
following this guide: https://cloud.google.com/python/django/appengine Im trying to run python manage.py makemigrations in the virtualenv however no output comes out, it seems as if it freezes immediately. Is there a debug or verbose command i can use to see what it gets stuck on? python manage.py migrate does the same -
Django query does not group
I want to group the number of messages by recipient user -> {'User 1': 5};{'User 2': 7}... My model: class Mensaje(models.Model): remitente = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Remitente') destinatario = models.ForeignKey('Usuario', on_delete=models.CASCADE, related_name='Destinatario') mensaje = models.TextField(validators=[MaxLengthValidator(1000)]) leido = models.BooleanField(default=False) fechaEnvio = models.DateTimeField(auto_now_add=True) My query: mensajes = Mensaje.objects.filter(destinatario=request.user).values('pk', 'remitente__username').annotate(num_msg=Count('pk')).order_by('-fechaEnvio') Result: {'pk': 28, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 27, 'remitente__username': 'Paco', 'num_msg': 1}, {'pk': 26, 'remitente__username': 'jota', 'num_msg': 1}, {'pk': 25, 'remitente__username': 'jota', 'num_msg': 1}... As you can see, the query returns all the messages without group by user. Another question: Why does not work mensajes = request.user.mensaje_set.all()? -
Django won't set a specific cookie, but will set others
response = redirect("/") response.set_cookie('id_token1', 'woohoo') response.set_cookie('id_token', 'woohoo') response.set_cookie('test', 'woohoo') return response When I inspect the cookies on the next page, id_token1 and test are both set but id_token is not. I have: turned off DEBUG mode SESSION_COOKIE_SECURE set to off checked that the cookie isn't being deleted or cleared in any other part of the code -
Create custom lookup in Django similar to startswith
I need to create a custom field lookup in Django that is similar to startswith. The built in startswith lookup works like this: id__startswith='abc' So if the ID field is 'abc1' then it would match. However I need create a 'contained from start' (cfs) lookup that looks this: id__cfs='abc12' So if the ID field is 'abc' then it would match. Basically __startswith but the other way around. This is my code so far but I am getting an error: class Test(Lookup): lookup_name = 'test' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = rhs_params + lhs_params return "%s LIKE %s%%" % (rhs, lhs), params Field.register_lookup(Test) test_parts = Items.objects.filter( id__test='12345' ) print('test_parts', test_parts) This is the error I am getting: Traceback (most recent call last): File "/Users/juanjosegutierrez/projects/powerTools/projects/tests/unit/tasks/test_match_parts.py", line 83, in test_part_ids_param print('test_parts', test_parts) File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/models/query.py", line 138, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 840, in execute_sql cursor.execute(sql, params) File "/Users/juanjosegutierrez/.virtualenvs/powertools/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) IndexError: tuple index out of range This is … -
Celery 4.1.0 and Django 2.0.2 app tasks not discovered
I have found this question and tried all recommendations as well as the accepted answer. Still no luck. Here is my mysite/taskapp/celery.py: import os from celery import Celery from django.apps import AppConfig from django.conf import settings if not settings.configured: # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover app = Celery('mysite') class CeleryConfig(AppConfig): name = 'mysite.taskapp' verbose_name = 'Celery Config' def ready(self): app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) # pragma: no cover Here is my mysite's __init__.py: from mysite.taskapp.celery import app as celery_app __all__ = ['celery_app'] Here is an example mysite/myapp/tasks.py: from celery import shared_task @shared_task def mytask(): print('Do something') When running the celery worker with celery -A mysite worker -l info here is the output: celery@tim-office v4.1.0 (latentcall) Darwin-16.7.0-x86_64-i386-64bit 2018-02-27 21:38:55 [config] .> app: mysite:0x1058e0fd0 .> transport: amqp://guest:**@localhost:5672// .> results: disabled:// .> concurrency: 4 (prefork) .> task events: OFF (enable -E to monitor tasks in this worker) [queues] .> celery exchange=celery(direct) key=celery [tasks] . mysite.taskapp.celery.debug_task Note that the mysite/myapp/tasks.py tasks are not found. I've been spinning my wheels for a full day trying all kinds of things from adding the app to CELERY_IMPORTS in the settings file: CELERY_IMPORTS = … -
Editing , posting and deleting appointments (Django)
I wrote a login page that is supposued to take appointments. Everything works except when it comes to making new post and editing them.here is the html page that is giving me trouble. `!DOCTYPE html> <html> <head> <a href="/logout">Logout</a> <title>What's Up</title> <h1>Hello </h1> <p>Here are your appointments for today</p> </head> <body> <form action="/create"> {% csrf_token %} <table> <thead> <tr> <th>Task</th> <th>Time</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <tr> <td>Jojos Bizaree Adventure</td> <td>11:00PM</td> <td>Done</td> <td><a href="/edit">Edit</a> <a href="/delete">Delete</a></td> </tr> </tbody> </table> </form> <p>Your other appointments</p> <table> <thead> <tr> <th>Task</th> <th>Date</th> <th>Time</th> </tr> </thead> <tbody> {%for appt in appts%} <td>Task:{{appts.task}}</td> <td>Date:{{appts.date}}</td> <td>Time:{{appts.time}}</td> <td><p><a href="/edit">Edit</a></p> <td><a href="/delete">Delete</a></td> {% endfor %} </tbody> </table> <form action="/update" method="POST"> {% csrf_token %} <p>Add Appointment:</p> <button type="submit" value="addappoint">Add</button> </form> </body> </html>' I want to be able to add information from this page to the table enter code here<!DOCTYPE html> <html> <head> <title>Update Appointment</title> <a href="appointments.html">Dashboard</a> ||<a href="/logout">Logout</a> </head> <body> <form action="/create" method="POST"> {% csrf_token %} <p>Task: <input type="text"></p> <p>Status: <input type="radio">Done<br> <input type="radio">Pending<br> <input type="radio">Missed<br> </p> <p>Date: <input type="date"></p> <p>Time:<input type="time"></p> <button type="submit" value="newappoint">Update</button> </form> </body> </html> and edit the data in question with this page `<!DOCTPYPE html> <html> <head> <h1>Edit Appointment</h1> <a href="/success">Dashboard</a> ||<a href="/logout">Logout</a> </head> <body> <form … -
Login/Logout a user using Django
I am currently working on a project with Django. I am trying to implement the ability of login and logout a user from the application using only python scripts in order to send post request from the client to the server. I am trying to logout a user from my application but it does not seems to work. In my login function this is the method used to login a user: login_user = authenticate(username=user.customer_username, password=user.customer_password) if login_user is not None: if login_user.is_active: request.session.set_expiry(86400) login(request, login_user) print(request.user.is_active) The result of the print is True here which means that the login method is correct if I am not wrong. When I try to logout the user, using this method: # Loging out the user print(request.user.is_active) logout(request) It does not logout the user and the result of the print is False here, which means that the user is not logged in. If anyone have any idea, how to solve this, it would be very helpful. Thanks. -
How forms work in django
I am sure this is a silly question but I am trying to understand how forms work in django and I am confused about the action attribute in the template and the httpresponseredirect in views.py I have the following template: <form action="/play_outcomes/output/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> And the following view: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] return HttpResponseRedirect('/thanks/') else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) And finally in forms.py class get_data(forms.Form): get_down = forms.IntegerField(label = "Enter a down") get_ytg = forms.IntegerField(label = "Enter yards to go") get_yfog = forms.IntegerField(label = "Enter yards from own goal") When I go to play_outcomes/getinput my form comes up. When I press 'submit' it directs shows the play_outcomes/output page, presumably because that is what is specified by the <form action variable. Anyway, my question is what is the purpose of the return HttpResponseRedirect('/thanks/') after it has checked form.is_valid(). This is TRUE so it must execute this code. But this return seems redundant. Please can someone enlighten me on what the return in the views.py is doing -
Using related_name twice
Suppose I have 3 models which are subsequent 1 to many relations, A (1 to many) B (1 to many) C class ModelA(models.Model): class ModelB(models.Model): model_a = models.ForeignKey('ModelA', related_name='re_model_b') class ModelC(models.Model): model_b = models.ForeignKey('ModelA', related_name='re_model_c') Starting from a ModelA instance I can use model_a.re_model_b to obtain the ModelB related objects. But from there I don't know how to get to ModelC. I tried model_a.re_model_b.re_model_c and model_a.re_model_b__re_model_c neither of which seems to do the trick. -
django not reconizing default objects manager for model
I am running my django server and I am getting a 500 code with the error AttributeError: type object 'EventPurpose' has no attribute 'objects' the model however was created correctly and other models with the same implementation are working fine. Here is the full code from model creation to use. model creation class EventPurpose(models.Model): purpose = models.CharField(max_length=200) view class GetAllSettingsObjects(APIView): def get(self, request, format=None): eventpurposequeryset = EventPurpose.objects.all() and that is were I get the error: The error in full line 24, in get eventpurposequeryset = EventPurpose.objects.all() AttributeError: type object 'EventPurpose' has no attribute 'objects' [27/Feb/2018 20:57:55] "GET /<super cool url object that I dont want to share with you>/ HTTP/1.1" 500 16404 please help. Hugs and kisses -
Remove choice from ModelForm Select widget
In my model I have multiple choices like: class Choice_Test(models.Model): TESTS = (('1', 'A'),('2', 'B'),) option = models.CharField(choices=TESTS, max_length=1) and it's form: class Choice_TestCreateForm(forms.ModelForm): class Meta: model = Choice_Test fields=['option'] widgets={'option': forms.Select()} in the template: <label id="options">Options</label> {{ form_options.option }} How can I remove from the select the 'A' value? I've tried this but it didn't work for me. -
Django - change Dictsort using a Javascript onclick listener?
Is it possible to change what dictsort is sorting by using Javascript? Here is my sort code: {% for product in products|dictsortreversed:'price' %} ....stuff happening here {% endfor %} What I want is for when a user clicks on a sort option for the dictsortreversed:'price' to become dictsort:'price'. Is this possible at all? Or should I try and find a different way to do this? -
django TemplateDoesNotExist exception but template exists
I am trying to render a template in django. I get this error when i connect to the site: django.template.loaders.filesystem.Loader: path-to-azerty/templates/base.html (Source does not exist) Here's my project directory structure: azerty/ __init__.py ├── settings.py ├── templates │ └── base.html ├── urls.py ├── views.py └── wsgi.py Here's my code: // ulrs.py from django.contrib import admin from django.urls import path from azerty import views urlpatterns = [ path('', views.index), path('admin/', admin.site.urls), ] // settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] //views.py from django.shortcuts import render def welcome(request): return render(request, 'base.html')` -
Difference between args=[topic.id] and args=[topic_id] when using the return HttpResponseRedirect(reverse) in Django
I'm following a tutorial from to build a simple blog app with Django. I have noticed that in the new_entry() view, we need to pass topic_id in agrs when using the reverse function: def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': #No data submitted, create a blank form form = EntryForm() else: #POST data submitted; process data form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) However, when creating the edit_entry() view (that allows users to edit existing entries), we need to pass topic.id def edit_entry(request, entry_id): """Edit an existing entry""" entry = Entry.objects.get(id=entry_id) topic = entry.topic if request.method != 'POST': #Initial request, render the form with current entry form = EntryForm(instance=entry) else: #Submit changes, process data form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id])) context = {'topic':topic, 'entry':entry, 'form':form} return render(request,'learning_logs/edit_entry.html', context) Initially I thought this was a mistake so I used args=[topic_id] in both reverse functions and it worked fine Later, I decided I wanted to add a title to each entry so I made some minor changes to models.py, … -
Django ListView split display in categories in template
I don't really know how to phrase my question, but what I'm trying to do is add a title between items to split them into obvious categories on my template. I would like to do this: {# set variable "current_category" to an empty value first #} {% for item in items %} {% if item.category == current_category %} {{ current_category = item.category }} {# <-- How to do that? #} <h1>{{ item.category }}</h1> {% endfor %} <p>{{ item.name }}</p> {% endfor %} Then end up with: <h1>Cat 1</h1> <p>item</p> <p>item</p> ... <h1>Cat 2</h1> <p>item</p> .. I saw on similar answers that there are things called custom filters and simple tags but it seems really complicated for something very simple. Is this really the only way to do that? NOTE: I already ordered the items by category of course -
How to use Django Rest pandas to make "A bar Chart interactive with Slider"
I want to make a Bar chart that changes according to the slider(not range slider).I have a pandas python code.How I can integrate this python (pandas)code using https://pypi.python.org/pypi/rest-pandas">Django Rest Pandas so that I can make an interactive bar chart with the slider. Also, I want to Know if there any tutorial for Django rest pandas which will help me to understand the Concept Comprehensively.I have searched on google but could not find the good tutorial . -
Django: Display contents of txt file on the website
I have this in my views.py def read_file(request): f = open('path/text.txt', 'r') file_contents = f.read() print (file_contents) f.close() return render(request, "index.html", context) I am not seeing anything on the website (text.txt file has information). I am not seeing any print output in nohup. No errors -
Geodjango and hierarchical locations
In a few weeks I want to start building a "datawarehouse" based on django. The database should be filled with data which can be connected to a location. For example population which is connected to country or city, or the anual rainfall or temperature. The parameters are not yet defined and will change over time but they will in general have a quantity, timeperiod (for example anual) and unit (so in the example: population of country X in year Y). My idea was to have a selfreferencing table in the database named locations in which there would be continents, countries, regions and cities. An example: ID | parent_id | name 1 | null | Europe 2 | 1 | France 3 | 2 | Paris I would than have a table which would connect data to a location like such: ID | location_id | parameter_id | from_date | to_date | quantity 1 | 3 | 1 | 01-01-2000 | 31-01-2001 | 3000000 parameters: ID | name | unit 1 | population | people Technically I also want to couple locations to coordinates or polygons such that I can show them on a map. Is something like this possible in (Geo)Django? … -
Django WSGI: A server error occurred. How to use wsgi in webapp
I am new to Django, and trying to create a web app use Django and wsgi to generate a server. But I got some error and misunderstanding about Django. Here is the code of my wsgi.py : from django.shortcuts import render import urllib import urllib2 from urllib2 import urlopen import json from wsgiref.simple_server import make_server from django.http import HttpResponse def map(request): return render(request,'WebPage1.html') def searchMap(request): address =request.POST['city'] return render(request,'WebPage1.html',{'Address':address}) def routers(): urlpatterns = ( ('/map',map), ('/searchMap',searchMap) ) return urlpatterns def application(environ, start_response): print(environ['PATH_INFO']) path=environ['PATH_INFO'] status = '200 OK' response_headers = [('Content-Type', 'text/plain')] urlpatterns = routers() func = None for item in urlpatterns: if item[0] == path: func = item[1] break if func: return func(environ) else: return ["Hello World".encode("utf-8")] httpd = make_server('', 8080, application) print('Serving HTTP on port 8080...') httpd.serve_forever() And my html: <!DOCTYPE html> <html> <head> <title>Simple Map</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> #map { height: 100%; } html, body { height: 100%; margin: 0; padding: 0; } #floating-panel { position: absolute; top: 10px; left: 25%; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; text-align: center; font-family: 'Roboto','sans-serif'; line-height: 30px; padding-left: 10px; } </style> </head> <body> <div id="map"></div> <div id="floating-panel"> <form method="POST" action="/searchMap/"> {% csrf_token %} <input … -
Django model outside of django
I have a non django project for which i would like to use the django models for data access layer. Added the models lib in requirements.txt django-model-utils==3.1.1 And code set it up like below: from django.conf import settings from django.db import models settings.configure( DATABASE_ENGINE='django.db.backends.mysql', DATABASE_NAME='***', DATABASE_USER='***', DATABASE_PASSWORD='***', DATABASE_HOST='***', DATABASE_PORT='***') class Bus(models.Model): class Meta: db_table = 'my_custom_bus' bus_name = models.CharField(max_length=20) bus_description = models.CharField(max_length=100) But when i run the above code, i am getting the following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Am i missing some setting here? -
Missing Environment Vars in docker python:3 with docker-compose
Though my configuration looks good, my python:3 image does not seem to have the expected DJANGO_SECRET_KEY set, at least at the point that the Dockerfile attempts to run migrations $ docker-compose config services: api: build: context: /Users/ben/Projects/falcon/falcon-backend dockerfile: Dockerfile depends_on: - db - redis environment: DJANGO_SECRET_KEY: 'some-secret-that-works-elsewhere' $ $ docker-compose up --build api [...] Step 6/7 : RUN echo `$DJANGO_SECRET_KEY` ---> Running in fbfb569c0191 [...] django.core.exceptions.ImproperlyConfigured: Set the DJANGO_SECRET_KEY env variable ERROR: Service 'api' failed to build: The command '/bin/sh -c python manage.py migrate' returned a non-zero code: 1 however, the final line, CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice does start up as desired, with the necessary env vars set. # Dockerfile -- api FROM python:3 RUN pip3 -q install -r requirements.txt RUN echo `$DJANGO_SECRET_KEY` RUN python manage.py migrate --settings=falcon.settings.dev-microservice # <-- why does this not work CMD python manage.py runserver 0.0.0.0:8001 --settings=falcon.settings.dev-microservice Why does the penultimate line of the Dockerfile fail due to an unset environment variable while the final one works as expected? -
Django - forms for mapping table children?
my models are as below, im using mapping tables as a subnet may belong to more than one device and a subnet may belong to more than one site. The tables work great, now my issue is how can I use model forms to create and edit devices? for example... select site create a device form under site show all subnets related to device in form (get the data from sitessubnets mapping table and display as options) add new record to devicedata model add new record(s) to devicesubnets model based on selection(s) in form can anyone point me in the right direction, do I need to use some sort of ModelForm inheritance? or nested forms with custom fields to obtain the sites revenant subnets? class DeviceData(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site device belongs to", on_delete=models.PROTECT) hostname = models.CharField(max_length=200) template = models.ForeignKey(ConfigTemplates, on_delete=models.PROTECT) ... class Subnets(models.Model): subnet = models.GenericIPAddressField(protocol='IPv4', \ verbose_name="Subnet", blank=True, null=True) subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True) peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True) class Meta: verbose_name = "Subnets" verbose_name_plural = "Subnets" def __str__(self): return self.subnet class DeviceSubnets(models.Model): device = models.ForeignKey(DeviceData, on_delete=models.CASCADE) subnet = models.ForeignKey(Subnets, on_delete=models.CASCADE) class Meta: verbose_name = "Device Subnets" verbose_name_plural = "Device Subnets" …