Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST related Fields Django rest Framework
new at django. What I am trying to do is POSTING a model which has a OneToOneField property. How do you POST that? Models.py Article(models.Model): name=models.CharField(max_length=50) description=models.TextField(max_length=200) Characteristic(models.Model): article=models.OneToOneField(Article,on_delete=models.CASCADE,primary_key=True) other=models.FloatField() another=models.IntegerField() Serializer.py class ArticleSerializer(serializers.ModelSerializer): class Meta: model=Article field='__all__' class CharacteristicSerializer(serializers.ModelSerializer): article=serializers.StringRelatedField() class Meta: model=Characteristic field='__all__' Views.py POST METHOD (API Based) def post(self, request,format=None): serializer=CharacteristicSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) If I try to POST with something like this: (some_url...)/characteristics/ other=4.4 another=4 post=1 I get the next error: django.db.utils.IntegrityError: (1048, "Column 'post_id' cannot be null") The idea is to receive the id of the model Article and then save the model Characteristic. Any ideas? -
How to mix RDMS DB with a Graph DB
I am developing a website using Django and PostgreSQL which would seemingly have huge amount of data as gathered in social network sites. I need to use RDMS with SQL for tabular data for less SQL complexity and also Graph DB with Cipher for large data for high query complexity. Please let me know how to use go ahead. Also please let me know whether it is feasible. -
Gunicorn + Django + Supervisor - Supervisor cannot start Gunicorn: ENOENT
**CHECKED EVERYTHING ON STACK OVERFLOW ** I have deployed Django using gunicorn and nginx. The django project is located in a virtual environment. Everything is working perfectly when I run - gunicorn mydjangoproject.wsgi -c gunicorn_config.py I am running the above command inside my Django project folder containing manage.py with the virtual environment active. However now i want to close the server terminal and want gunicorn to run automatically. For this I am using Supervisor. I have installed supervisor using apt-get and created a gunicorn.conf file in supervisor's conf.d. But when I run supervisorctl start gunicorn I am getting a fatal error- gunicorn: ERROR (abnormal termination) So checked the log file and it says- supervisor:couldn't exec root/ervirtualenvpy2/bin/gunicorn: ENOENT child process was not spawned My configuration file for supervisor's gunicorn.conf looks like this- [program:gunicorn] command = root/ervirtualenvpy2/bin/gunicorn myproject.wsgi -c root/path/to/the/gunicorn_conf.py/file directory = root/ervirtualenvpy2/path/to/myproject/ user=root autorestart=true -
Can anyone do a many to many relationship between two django models only with the foreighn key?
I have two models lets say an Album and a Song Model.I have a foreighn key field to my Song model so I can correlate multiple songs to an album (many to one relationship).If i don't change anything in my models and leave them as they are can I succeed a many to many relationship (same song to different albums and vise versa) if I change the way that my databse store my data (normalize,denormalize etc)? Thanks -
Displaying field value in template
I am trying to display a total, model field value, from a calculation done on fields in a model, on a html template. Basically calculating L X B view.py def quoting(request): if request.method == 'GET': form = CreateForm() else: form = CreateForm(request.POST) if form.is_valid(): Length = form.cleaned_data['Length'] Breadth = form.cleaned_data['Breadth'] Height = form.cleaned_data['Height'] return render(request, "quote/email.html", {'form': form}) def answer(request): return render(request, "quote/answer.html") models.py from django.db import models class ContactForm(models.Model): Length = models.IntegerField() Breadth = models.IntegerField() Height = models.IntegerField() def _get_total(self): "Returns the total" return self.Length * self.Breadth total = property(_get_total) forms.py from django import forms from .models import ContactForm class CreateForm(forms.ModelForm): class Meta: model = ContactForm fields = ['Length', 'Breadth', 'Height', 'distance', 'weight'] The template- My attempt <div class="content"> <div class="container box"> <h2> Your answer is Is: {{ form.total.value|default_if_none:"" }}</h2> </div> -
Update set of fields in django model passed in request.POST
This is my Model class class SubJobs(models.Model): id = models.AutoField(primary_key = True) subjob_name = models.CharField(max_length=32,help_text="Enter subjob name") subjobtype = models.ForeignKey(SubjobType) jobstatus = models.ForeignKey(JobStatus, default= None, null=True) rerun = models.ForeignKey(ReRun,help_text="Rerun") transfer_method = models.ForeignKey(TransferMethod,help_text="Select transfer method") priority = models.ForeignKey(Priority,help_text="Select priority") suitefiles = models.ForeignKey(SuiteFiles,help_text="Suite file",default=None,null=True) topofiles = models.ForeignKey(TopoFiles,help_text="Topo file",default=None,null=True) load_image = models.NullBooleanField(default = True,help_text="Load image") description = models.TextField(help_text="Enter description",null=True) command = models.TextField(help_text="Command",null=True) run_id = models.IntegerField(help_text="run_id",null=True) pid_of_run = models.IntegerField(help_text="pid_of_run",null=True) hold_time = models.IntegerField() created = models.DateTimeField(default=timezone.now,null=True) updated = models.DateTimeField(default=timezone.now,null=True) finished = models.DateTimeField(null=True) The user might want to update a entry and may choose to update only few fields among these. How do I write a generic update statement that would update only the fields that were passed? I tried this. def update_subjob(request): if (request.method == 'POST'): subjobs_subjobid = request.POST[('subjob_id')] post_data = request.POST if 'subjob_name' in post_data: subjobs_subjobname = request.POST[('subjob_name')] if 'subjob_type' in post_data: subjobs_subjobtype = request.POST[('subjob_type')] if 'rerun_id' in post_data: subjobs_rerun_id = request.POST[('rerun_id')] if 'priority_id' in post_data: subjobs_priority_id = request.POST[('priority_id')] if 'transfer_method' in post_data: subjobs_transfermethod = request.POST[('transfer_method')] if 'suitefile' in post_data: subjob_suitefile = request.POST[('suitefile')] if 'topofile' in post_data: subjob_topofile = request.POST[('topofile')] try: subjobinstance = SubJobs.objects.filter(id=subjobs_subjobid).update(subjob_name=subjobs_subjobname, updated=datetime.now()) except Exception as e: print("PROBLEM UPDAING SubJob!!!!") print(e.message) How do I write a generic update to update only those … -
Django REST Framework: Can't update Foreign Key with JSON POST request
I am using Django REST Framework that stores data from scanners, which are devices which send a JSON POST request to the framework whenever it detects a new scan. The models are as follows: class Location(models.Model): address = models.CharField(max_length=300) city = models.CharField(max_length=50) state = models.CharField(max_length=100) zipcode = models.IntegerField(null=True, blank=True) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField() def __str__(self): return self.address class Scanner(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True,related_name='scanner') description = models.CharField(max_length=300, null=True, blank=True) def __str__(self): return self.location.address + ": " + self.description + " (id=" + str(self.pk) + ")" class Scan(models.Model): scanner = models.ForeignKey(Scanner, on_delete=models.CASCADE, null=True, blank=True,related_name='scan') datetime = models.DateTimeField(null=True, blank=True, default=timezone.now()) def __str__(self): if self.scanner != None: return self.scanner.description + ": " + str(self.datetime) else: return "None: " + str(self.datetime) class Meta: ordering = ('datetime',) And the serializers are these: class ScanSerializer(serializers.ModelSerializer): class Meta: model = Scan fields = ('id', 'scanner', 'datetime') class ScannerSerializer(serializers.ModelSerializer): class Meta: model = Scanner fields = ('id', 'location', 'description',) class UserSerializer(serializers.ModelSerializer): scans = serializers.PrimaryKeyRelatedField(many=True, queryset=Scan.objects.all()) class Meta: model = User fields = ('id', 'username', 'scans') class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = ('id', 'address', 'city', 'state','zipcode', 'latitude', 'longitude') If I use the DRF URL to create new Scan and Scanner objects, it … -
Implementation of likes using AJAX with Django
I'v tried to use this https://github.com/yceruto/django-ajax to implement "likes" I'v followed the instructions accurately event on click outside the ajax request works fine as well the data is there, as well as ajax and jquery are enabled ajaxPost('/like', {'post_pk': 'post_pk'}, function(){ //onSuccess alert("smth"); }) at this point nothing happens, no alert window or something. in url patterns: url(r'^like/$', views.like), however nothing is printed @ajax def like(request): print('hey') What may be wrong here? And could you please as well explain what is the most prudent way to implement ajax in django? -
Is there any simple free Payment Gateway for Django?
I am building payment gateway for website, being able to receive money from users and also to send it, How is it possible? For example something like this for PayPal and Debit Card: import random from process import multiprocessing Users = [ "..." ] # PayPal: import SomePayPalApi def Receiver(): SomePayPalApi.receive_to = "somepaypalemail@email.com" while True: if SomePayPalApi.recieved: print SomePaypalApi.recieved.amount print SomePaypalApi.received.email print SomePaypalApi.Balance def Sender(): SomePayPalApi.sendto = random.choice(Users) SomePayPalApi.send() if __name__ == "__main__": p1 = Process(target=Receiver) p2 = Process(target=Sender) p1.start() p2.start() Or Debit Card: import random from process import multiprocessing Users = [ "..." ] # Debit: import SomeCardApi def Receiver(): SomeCardApi.reciever.type = SomeCardApi.type.Visa() SomeCardApi.receive_to = 4000000000 while True: if SomeCardApi.recieved: print SomePaypalApi.recieved.amount print SomePaypalApi.received.name print SomePaypalApi.Balance def Sender(): SomeCardApi.sendto.type = SomeCardApi.type.Visa() SomeCardApi.sendto = 410000000 SomeCardApi.send() if __name__ == "__main__": p1 = Process(target=Receiver) p2 = Process(target=Sender) p1.start() p2.start() How can one create such kind of sending/receiving system? I know this is really easily made and it is far more complicated but is it possible to be done? -
Object is not iterable when setting generic relation
I'm trying to set my generic relation in Model A: class A(models.Model): relation = GenericRelation('B') class B(models.Model): content_type = models.ForeignKey(ContentType, blank=True, null=True) object_id = models.PositiveIntegerField(blank=True, null=True) content = GenericForeignKey('content_type', 'object_id') Yet when I try to do: relation = B.objects.get(pk=1) model = A(relation=relation).save() I get this error: TypeError: 'B' object is not iterable -
django rest-framework-2 No module named apps
guys can you help me a bit I try to use Django REST Framework in my projet but it dosen't work... Here my Traceback : http://dpaste.com/355XG8M Thanks you ;) -
django request.POST data is empty but works with other similar form
I'm new to django and I was following a tutorial from django on how to process POST form data with a model https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view I was able to do that for a simple login, and I can print out the variables in the console. The form.is_valid() function is true and works as expected for the login view. I did the same exact thing for a registration page and I'm getting FALSE returned from the is_valid() function. I was tinkering with csrf tokens and that didn't seem to be causing the issue and thats why I didn't require them. I think it's going to be a silly problem because I'm able to get the request.POST in the login case but not the registration. Any help is appreciated. Here is my html form <div id="login" class="animate form"> <form action="/signin" autocomplete="on" method ="POST"> <!--{% csrf_token} --> <h1>Log in</h1> <p> <label for="username" class="uname" data-icon="u" > Your email or username </label> <input id="username" name="username" required="required" type="text" placeholder="myusername or mymail@mail.com"/> </p> <p> <label for="password" class="youpasswd" data-icon="p"> Your password </label> <input id="password" name="password" required="required" type="password" placeholder="eg. X8df!90EO" /> </p> <p class="keeplogin"> <input type="checkbox" name="loginkeeping" id="loginkeeping" value="loginkeeping" /> <label for="loginkeeping">Keep me logged in</label> </p> <p class="login button"> <input type="submit" … -
Django nonchanged form POST with hidden inputs
I have a django app that shows and takes username inputs. I have two input fields, <tr> <td><label for="username">User Name:</label> </td> {% if perms.commons.can_manage_iam_data and not read_only %} <td><input autocomplete="off" type="text" id="username" name="username" value="{{ iamuser.login }}" /> {% if domain %}@{{ domain }}{% endif %} </td> <input type="hidden" id="id_original_user_id" name="original_user_id" value="{{ iamuser.uuid }}"/> {% else %} <td>{{ iamuser.login }}</td> {% endif %} </tr> So there is one input field and one hidden field. When a user clicks submit, information gets POSTed. But I really want to check when user just clicks submit without actually typing the changed username. I thought form.has_changed() would catch it, but since hidden input's information always gets posted, form.has_changed() always returns true. Are there any other ways to check? -
Modelform with reverse foriegnkey
I am trying to create a ModelForm for musician Model from which it must be possible to select a number of albums for each musician.Since album is reverse foreignkey i think ModelForm doesn't saves album values to the database.Is there any possible methods to get this working please help me and thanks in advance here is my modelform: class musicianForm(forms.ModelForm): album=forms.ModelMultipleChoiceField(queryset=Musician.objects.all(), widget=forms.widgets.CheckboxSelectMultiple()) class Meta: model = Musician fields = ('album','first_name','last_name',instrument') models.py from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() admin.py class musicianAdmin(admin.ModelAdmin): form = musicianForm -
mezzanine multi tenancy, gunicorn, nginx configuration
I hope this goes here and not to server fault, since I think it's more a mezzanine/django issue. I'm trying to make use of mezzanines multi tenancy to serve different themes to each domain. I start gunicorn -b 127.0.0.1:8000 -b 127.0.0.1:8001 domain1_domain2.wsgi:application to bind 2 ports for each theme/domain. settings.py ALLOWED_HOSTS = [ 'domain1.dev', 'domain2.dev.', "127.0.0.1:8000", "127.0.0.1:8001", "*", ] HOST_THEMES = [ ('domain1.dev', 'theme1'), ('domain2.dev', 'theme2'), ('127.0.0.1:8000', 'theme1'), ('127.0.0.1:8001', 'theme2'), ] nginx server { listen 80; server_name domain1.dev; location /static { root /home/david/domain1_domain2/domain1_domain2/domain1; } location / { include proxy_params; proxy_pass http://127.0.0.1:8000; } } server { listen 80; server_name domain2.dev; location /static { root /home/david/domain1_domain2/domain1_domain2/domain2; } location / { include proxy_params; proxy_pass http://127.0.0.1:8001; } } hosts 127.0.0.1 www.domain1.dev 127.0.0.1 domain1.dev 127.0.0.1 www.domain2.dev 127.0.0.1 domain2.dev http://127.0.0.1:8000 / www.domain1.dev correctly display theme1. But http://127.0.0.1:8001 / www.domain2.dev display theme1, too, and not theme2 as expected. Can this done with mulit tenancy? What I'm doing wrong? Thanks! -
ContentType Django App Registry AppRegistryNotReady using Celery
When running celery via Django (1.9.9) why does Django App Registry have an issue with 'ContentType'? The error below suggestions the problem celery is within the 'Membership app and the import ContentType, why? Note: runserver does not produce any errors. Error: File "/Users/user/Documents/workspace/demo-api/demo/apps/pings/redis_models.py", line 12, in <module> from demo.apps.memberships.models import Membership File "/Users/user/Documents/workspace/demo-api/demo/apps/memberships/models.py", line 4, in <module> from django.contrib.contenttypes.models import ContentType File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 161, in <module> class ContentType(models.Model): File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/django/db/models/base.py", line 94, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/Users/user/Documents/workspace/demo-api/env/lib/python3.5/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Celery Task in apps/wall/tasks.py # Python imports import time import logging from datetime import datetime # Django imports from django.db.models import Q from django.conf import settings from django.utils import timezone from django.utils.dateparse import parse_datetime # Package imports from celery import Celery, task, Task, states from demo.apps.celery import app as celery_app logger = logging.getLogger(__name__) @celery_app.task(max_retries="5") def broadcast(self): try: #edited code here: if schedule: for broadcast_id in schedule: broadcast = PingBroadcast(broadcast_id) content_object = broadcast.get_content_object() Below is model.py of apps/membership/model.py: # Python core # Django imports from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.conf import settings … -
error while installing django
I am trying to learn djnago framework. I have windows machine and on that I have installed virtual machine (oracle VM VirtualBox manager) . I have python installed on that. I dont see pip installed on this VM. so i tried to install django via below:- wget https://www.djangoproject.com/download/1.10.1/tarball/ error :- Resolving www.djangoproject.com... 162.242.220.127, 2001:4802:7801:102:be76:4eff:fe20:789f Connecting to www.djangoproject.com|162.242.220.127|:443... connected. ERROR: cannot verify www.djangoproject.com's certificate, issued by /C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3': Unable to locally verify the issuer's authority. ERROR: certificate common namedjangoproject.com' doesn't match requested host name www.djangoproject.com'. To connect to www.djangoproject.com insecurely, use--no-check-certificate'. Unable to establish SSL connection so i tried below :- wget --user=username --password --no-check-certificate https://www.djangoproject.com/download/1.10.1/tarball/ but still error :- ERROR: cannot verify www.djangoproject.com's certificate, issued by `/C=US/O=Let's Encrypt/CN=Let's Encrypt Authority X3': Unable to locally verify the issuer's authority. ERROR: certificate common name djangoproject.com' doesn't match requested host namewww.djangoproject.com'. To connect to www.djangoproject.com insecurely, use `--no-check-certificate'. Unable to establish SSL connection. Can somebody help ? -
Digital Ocean Django app changes are not applied
I have a django app hosted on digital ocean on an Ubuntu machine. Every time I changed the django app code, django would automatically restart the django server so that he changes were applied. All of a sudden it stopped doing that. What could be wrong? Also I restarted the whole server using service gunicorn restart but I had no luck. -
Ember serializer customization for alternate url
I am a newbie to ember. So here is what i faced. I got backend RESTAPI written in python/Django. It provides following json response on /api/works/ [ { "id": 17, "title": "about us", "description": "some project", "owner": "admin" }, { "id": 19, "title": "test1 profit project", "description": "dev null", "owner": "test1" } ] also on detail view E.g:/api/works/17/: { "id": 17, "title": "about us", "description": "some project", "owner": "admin" } there is also /api/works/17/tasks/ for listing work tasks [ { "id": 2, "title": "secondWorkTask", "description": "task2 description", "due_date": "2016-09-26", "assign": 1, "project": "about us" }, { "id": 3, "title": "some task name", "description": "some task description", "due_date": "2016-08-27", "assign": 2, "project": "about us" } ] on the front-end side i am using ember-cli version2.7.0 + ember-django-adapter. I can get /api/works without problem. What i want to achieve is on the ember side when work detail url load, it must show all tasks. Currently i can get work detail by this url /api/works/17/ But how can i get tasks? Please help me to find a way to solve this. -
timezone vs datetime in django
What is the difference between timezone and datetime? timezone.now() returns 2016-09-26 16:20:27.211358+00:00 datetime.now() returns 2016-09-26 21:50:27.211261 Right now time in laptop clock is 21:50:27 ( 9 PM IST) In my django settings file I have following settings. USE_TZ = True TIME_ZONE = 'Asia/Calcutta' Which one should I use to store time-stamp values in my database? What if tomorrow someone in USA is using the code I am writing? What should be the correct timezone settings in django settings file? -
Re-use Wagtail Index Template for Multiple Lists
I have several product pages on my site that will have identical index and page setup but a different url path. I would like to re-use the template but filter the results to only show the child objects of that index page. For example: Currently www.../carnival - index page that displays all child objects www.../carnival/rides-games - child page of carnival www.../carnival/etc... I want to use the same index page on other sections of the site: www.../catering - index page that displays all child objects www.../catering/fun-food - child page of catering www.../catering/etc... But, when I use the same index page and visit my carnival page, I see all my catering child objects as well. Below is my code - please help me out; I know there has to be a DRY way of doing this. Thank you. standard_index_page.html {% block content %} ... {% standard_index_listing %} ... {% endblock %} standard_index_listing.html {% if pages %} {% for pages in pages %} <div class="col-xs-6 col-sm-4 col-md-3 mt20 hover-float"> <div class="team-two"> {% if pages.feed_image %} {% image pages.feed_image original as img %} <div class="team-one" data-animation="zoomIn" data-animation-delay="100" style="background: url('{{ img.url }}') no-repeat top center; background-size: cover"></div> {% endif %} <h5>{{ pages.title }}</h5> <small><a href="{% … -
Testing external URLs in Django
I'm currently having a hard time getting some of my Django tests to work. What I'm trying to do is test if a given URL (the REST API I want to consume) is up and running (returning status code 200) and later on if it's responding the expected values. However, all I get returned is a status code 404 (Page not found), even though the URL is definitely the right one. (Tried the exact string in my browser) This is the code: from django.test import TestCase class RestTest(TestCase): def test_api_test_endpoint(self): response = self.client.get("http://ip.to.my.api:8181/test/") self.assertEqual(response.status_code, 200, "Status code not equals 200") It always returns a 404 instead of a 200... Anyone knows what I do wrong here? -
Authenticating with JWT token in Django
I am beginner in Django and I am learning about JWT token from here. http://getblimp.github.io/django-rest-framework-jwt/#rest-framework-jwt-auth I have already set up in my settings.py. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.ModelSerializer', 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } If I do curl, I actually get back my token. curl -X POST -d "username=khant&password=khant" http://127.0.0.1:8000/api-token-auth/ But when I access my protected url, curl -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImtoYW50IiwidXNlcl9pZCI6OCwiZW1haWwiOiJraGFudEBnbWFpbC5jb20iLCJleHAiOjE0NzQ5MDQxNTJ9.jaZ3HwsXjx7Bk2ol5UdeE8UUlq4OEGCbnb1T8vDhO_w" http://127.0.0.1:8000/dialogue_dialoguemine/ It always say this when I access from web. Localhost is okay for me. {"detail":"Authentication credentials were not provided."} In my protected url, I just write simple api to query. May I know how to solve this? class DialogueMineView(generics.ListAPIView): permission_classes = (IsAuthenticated,) serializer_class = DialogueSerializer paginate_by = 2 def get_queryset(self): user = self.request.user return Dialogue.objects.filter(owner=user) -
Can you specify a queue and routing key in celery beat scheduler?
I have the same task that has to go to different queues depending on the conditions. I was curious if I could is specify this somehow in the celery beat scheduler either via the task or the args? CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.add(queue='priority.high' routing_key='priority.high')', 'schedule': timedelta(seconds=30), 'args': (16, 16) }, } Something like this. Or must i register the same task with different queues @app.task(queue='priority.high', routing_key='prioirity.high') def add_high_priority(x, y): pass @app.task(queue='priority.low', routing_key='priority.low') def add_low_priority(x, y): pass Then register then have 2 separate schedules for each. CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.add_low_priority', 'schedule': timedelta(seconds=30), 'args': (16, 16) }, 'add-every-90-seconds': { 'task': 'tasks.add_high_priority', 'schedule': timedelta(seconds=90), 'args': (16, 16) } } -
updating template view with error message in django
I have a Django model and form which are defined as follows: class LabelModel(models.Model): image = models.FileField(upload_to='documents/label', db_column='path', default='Some Value') The corresponding form is as follows: class DocumentForm(forms.Form): labelled_image = forms.FileField(label='Select the Label image') I have a simple validation method which checks the file extension. def validate_file_extension(value): import os from django.core.exceptions import ValidationError ext = os.path.split(value.name)[1] # [0] returns path+filename valid_extensions = ['.img'] if not ext.lower() in valid_extensions: return False return True Now, in the POST method, I do the following: if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): labelled_file = request.FILES['labelled_image'] has_errors = validate_file_extension(labelled_file) Now, if I have errors, I would like to update the render the page with an error message: So, my template rendering code looks like: <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.labelled_image.label_tag }} {{ form.labelled_image }} {{ form.labelled_image.errors }} </p> <p><input type="submit" value="Upload"/></p> </form> Now, I do not know how I can update this {{ form.labelled_image.errors }} with my own error message so that it can be displayed to the user.