Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images are not displayed with Django in Ubuntu while works well in Windows 10
I have built a gallery website with Django in Win10 and everything works well. However when I want to deploy it in Ubuntu 18.04, all images are not displayed. I think the problem is about the image paths: Source code for images: <img src="{% static img_path %}"> I use for loop for img_path so one img_path can be "home/xinliy/IAI/semlog_web/web/website/static/1.png" Generated html code for this image: <img src="/home/xinliy/IAI/semlog_web/web/website/static/1.png"> hyperlink for this image: 127.0.0.1:8000/home/xinliy/IAI/semlog_web/web/website/static/1.png And the django fail to load this image. I tried to change the hyperlink to be "File:///home/xinliy/IAI/semlog_web/web/website/static/1.png" Then I can see the image in the browser. However all html generated from Django would have a hyperlink with the prefix of "127.0.0.1:8000/" in default and I can never show a single image. I also create a single html file with src="/home/xinliy/IAI/semlog_web/web/website/static/1.png" and it works.But in Django I cannot get away from that prefix. In Win10 images can display but in Ubuntu it cannot. I need help! -
How to delete data from user profile in django
I am trying to remove dns-records that are associated to the user profile via ForeignKey but I am unable to achieve that. How can I delete it? When I try deleting from the shell DnsRecord.objects.filter(profile=self.id).delete() its working OK but when I run the same queryset in the model it is not deleting. def save(self, *args, **kwargs): try: DnsRecord.objects.filter(profile=self.id).delete() except DnsRecord.DoesNotExist: pass super(Profile, self).save(*args, **kwargs) And the Model looks like this class DnsRecord(models.Model): profile = models.ForeignKey(Profile, related_name='dns_records', on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) value = models.CharField(max_length=255, blank=False) objects = DnsRecordManager() class Meta: unique_together = ['profile', 'name', 'value'] def __str__(self): return f'{self.name} {self.value}' -
Variable return types of DecimalField
I have a model thats something like this: class Item(models.Model): value = models.DecimalField(default=0.0, decimal_places=4, max_digits=20) Now suppose that I have two items: a = Item() a.value = 1.20 b = Item() b.value = 2 When I access the model values I get: a.value = 1.2 <float> b.value = 2 <int> Why DecimalField does that? Can't I get the values always as python Decimal? -
How to change model attribute from template?
I am trying to add a user to a ManytoManyField when a button is clicked in the template. The idea is that I want users to mark a memo as read by clicking a button. First I tried to use a ModelManager method to accomplish this but the problem is that I need to pass the request.user arg; therefore that doesn't work. Next I tried a template tag but it didn't seem to work as I couldn't seem to call it in the template. Also, this seems like it is just wrong because I am writing a function in the ModelManager then another function to call that function in the template tag. @register.simple_tag def user_read_memo(user): Memo.mark_as_read(user) I tried to just add a custom view method to call from the template when the user presses a button but this doesn't seem to work either.. And now I am thinking that if I want to add a function then it needs to not be in a view but rather on the Model level. Therefore it seems that a template tag is necessary. Either this or I need to create a new view but that doesn't seem right because I would need to … -
How to add extra category field in django.views.generic
I have class in views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content',] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I want to add object to fields, but when I'm trying to add like this: fields = ['title', 'content', 'category'] the debugger send an error log like this -> FieldError at /post/new/ Unknown field(s) (category) specified for Post I need an extra column to add category field when creating post in my django blog. Here is blog_category.html {% extends 'blog/base.html' %} {% block content %} <h1 class='mb-3'>Category: {{ category | title }}</h1> {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" alt=""> <div class="media-body"> <div class="article-metadata"> <a class="mr-2 author_title" href="{% url 'user-posts' post.author.username %}">@{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"N d, Y" }}</small> <div> <small class="text-muted"> Categories:&nbsp; {% for category in post.categories.all %} <a href="{% url 'blog_category' category.name %}"> {{ category.name }} </a>&nbsp; {% endfor %} </small> </div> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content|slice:200 }}...</p> </div> </article> {% endfor %} {% endblock content %} The main goal is: create category field in views.py -> after pressing "Post" this field should push the content to the … -
Celery Incorrect Padding Base64
I'm having an issue with my worker and I don't know what to do. I have: @periodic_task(run_every=crontab(hour='*', minute='*', day_of_week="*")) def print_hello(): print('hello world') It works and it prints: hell world the first a handful of times and then I get this: [2019-11-05 12:28:57,824: CRITICAL/MainProcess] Unrecoverable error: Error('Incorrect padding') Traceback (most recent call last):... File "/home/xxxxxxxxx/xxxxxxxxx/project/lib64/python3.7/base64.py", line 87, in b64decode return binascii.a2b_base64(s) I'm using Django with Celery. I saw this SO answer. But I'm not trying to send messages to SQS. Plus, this works in another app I've been using so I don't think I need to decode and encode a simple string. Help would be appreciated. -
How to display an image from django models?
I am currently learning to make a blog website using Django.On my index page I want that there should be thumbnails present for the blogs in list form with the image which I asked them to upload while creating the post. I grabbed all the posts from my Post model but I don't know how to grab the image. Here is my index page: <div class="container-fluid row" > {%for post in post_list%} <div class="col-sm-6 col-md-4 bor"> <div class="thumbnail"> <img src="{{...}}" class="img-thumbnail" alt="..."> <div class="caption"> <h3>{{post.title}}</h3> <p>Published on: {{post.published_date}}</p> <p><a href="{%url 'post_detail' pk=post.pk%}" class="btn btn-primary" role="button">Read</a> <a href="#" class="btn btn-default" role="button">Button</a></p> </div> I read several answers related to Model.objects.all thing but I can't really understand what and how to do? I am new to Django. Can anyone help me please?? -
How to change pk field on existing database with data?
I have a user model which has an AutoField as the pk field. Now I want to change pk to uuid as I need to use it on my API. The biggest problem is that project is already running and there some 3-rd party apps which have relation with User model. For example it's DRF Token model. I tried to write some migrations to replace tables and keep my data safe. here is User model: class User(PermissionsMixin, AbstractBaseUser): email = models.EmailField(_("email address"), max_length=64, unique=True) first_name = models.CharField(_("first name"), max_length=30, blank=True) last_name = models.CharField(_("last name"), max_length=50, blank=True) Here are my steps: 1) I created the first migration by adding uuid = models.UUIDField(default=uuid4, editable=False) 2) Then I created empty migrations and filled new uuids from uuid import uuid4 from django.db import migrations def fill_ids(apps, schema_editor): user_model = apps.get_model("users", "User") for user in user_model.objects.all(): user.uuid = uuid4() user.save() class Migration(migrations.Migration): dependencies = [ ('users', '0002_user_uuid'), ] operations = [ migrations.RunPython(fill_ids) ] 3) Before this step everything works good. Then I tried to fill my related models with new ids from django.db import migrations, models from django.conf import settings def change_model_fks(apps, schema_editor): log_model = apps.get_model('admin', 'logentry') token_model = apps.get_model('authtoken', 'token') user_model = apps.get_model('users', "user") … -
How to implement a ManyToMany form with a through model and record multiple relations at once
I have a simple Order and Product models. They have a M2M relationship, so that a Product can be in several Orders and an Order can have several Products. I need a form for the users to gather the following information: List of products to be ordered and units of each one of those products. Date of creation of the Order User who made the order Etc As far as I understand, I need a through model to record the units for each product and I'm okay with that, but I have no idea on how to implement it in the Forms.py and Views.py and neither in the html. How can I show a "units" field next to each of the "product" MultipleChoice field? I already tried the "add form" for the through model in the admin site, but it only let me add relations one by one. After googling I managed to get a form like that, but then again, it's not what I'm looking form. In a magical scenario I would have several form fields with TextWidgets with django-autocomplete to search in them for products (one field per category of product, making it easier to find stuff) and … -
Unable to implement dependent dropdowns
been trying to implement dependent dropdown in my forms but I have been unable to get it right since I don't know much about jquery, but I think I'm doing something wrong if someone could help me out would really appreciate it the problem is upon selecting the fl no field, park_bay does not get updated screenshot followed the post written by Vitor Freitas which can be found here link models.py of app called postlog: from django.db import models class flight(models.Model): fl_no =models.CharField(max_length=6,primary_key=True) inbound= models.CharField(max_length=15,blank=True) dest= models.CharField(max_length=15,blank=True) park_bay= models.CharField(max_length=3) airline= models.CharField(max_length=15) dep_time= models.TimeField() arr_time= models.TimeField() def __str__(self): return self.fl_no the below provided table is in a different app models.py of an app called status: from django.db import models from postlog.models import flight # Create your models here. class FlightStatus(models.Model): Yes = 1 No = 2 CLEANING_CHOICES = ( (Yes, 'Yes'), (No,'No'), ) fl_no= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='fli_no') park_bay= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='parki_bay') catering= models.CharField(max_length=9) fuel= models.IntegerField() pas_cnt= models.IntegerField() dest= models.ForeignKey(flight,on_delete=models.CASCADE,related_name='desti') dep_time=models.ForeignKey(flight,on_delete=models.CASCADE,related_name='dept_time') Cleaning = models.PositiveSmallIntegerField(choices=CLEANING_CHOICES) def __str__(self): return self.fl_no views.py in status app: from django.shortcuts import render,redirect from django.views.generic.base import TemplateView from status.forms import StatusForm from status.models import FlightStatus from postlog.models import flight from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy # Create your views … -
Best way for allowing %d.%m.%Y-formated strings to be passed a model's DateField?
I have been trying to understand the effects of the DATE_INPUT_FORMATS settings and the way Django processes these datfields but whatever I find is either not understanable to me (being relatively new to DJango) or seems to relate to Forms, which doesn't seem to be applicable here. My user model has a birthday field: class LocalUser(AbstractUser): birthday = models.DateField(blank=True, null=True) and I want to create users from a csv. I upload the csv and process its contents: class InputFileForm(forms.Form): file = forms.FileField() def process_file(self): file = io.TextIOWrapper(self.cleaned_data['file'].file, encoding='utf-8-sig') reader = csv.DictReader(file, delimiter=";") l = LocalUser(**dict(line)) l.save() The csv contains dates in e. g. "01.01.1999" format. It works when I reformat dates e. g. via line["birthday"] = datetime.strptime(line["birthday"], '%d.%m.%Y') but I am sure there must be a nicer solution, one where I don't have to modify code wherever a birthday is passed to the user model as string. In the settingy.py file I added: #USE_L10N = False from django.conf.global_settings import DATE_INPUT_FORMATS DATE_INPUT_FORMATS += ('%d.%m.%Y',) but that doesn't help. The error message I get is: ValidationError at /import_export/import_data ["'11.02.1993' value has an invalid date format. It must be in YYYY-MM-DD format."] Do you have any recommendations on how to solve this? -
my ci/cd pipeline on azure builds but the staging app doesnt work
My cicd pipeline on azure will build successfully but when I get to staging it turns out it breaks in the backend. My backend is in django is there either 1. A way to make the entire piepline fail if the backend has an exit code of 1 2. Write a unit test to see if python manage.py works -
How to implement JQuery confirm dialog popup
I have a form with a submit button ant I want to add a confirm modal dialog using JQuery example without success when I use django template I currently used the JS confirm() (see below) but I would like to customize the dialog box I have understand that I should use a JQuery Dialog so I try to implement this solution this is my template: {% extends 'layouts/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block extrahead %} <!--<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />--> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(document).ready(function() { $("#randomize").click(function(event){ var response = confirm("Do you confirm randomization"); if (response == false) { event.preventDefault() } }); }); </script> {% endblock %} {% block title %}Index | Intense TBM{% endblock %} {% block content %} <div class='container'> <h1>Randomization form</h1> </br> <div class="row"> <div class="col-sm"> <strong>Patient code: </strong>{{ preincluded.pat_num }} </div> <div class="col-sm"> <strong>Age: </strong>{{ preincluded.age }} </div> <div class="col-sm"> <strong>Sex: </strong> {% if preincluded.pat_sex == 1 %} Male {% else %} Female {% endif %} </div> </br></br> </div> <form method="POST" class="post-form"> {% csrf_token %} {{ form |crispy }} <!--<button id="randomize" type="submit" class="btn btn-primary" onclick="confirm('Do you confirm randomization?')">Randomize</button>--> <button id="randomize" type="submit" class="btn btn-primary">Randomize</button> … -
Wrote some code for a model.PositiveIntegerField but changed it to Float and it wont register
I am currently working with Django and I just added a models.PositiveIntegerField and then migrated but decided I wanted to change it to models.FloatField. After making that change I went into django admin dashboard and was checking out an entry that I made which had 0 set as quantity at first but after I migrated the new changes it is now 0.0 Now the problem is that if I try to save a number, say 5.0, it would require me to enter a whole number. Even if I try to save the page with 0.0 it would summon an error. Should I reverse my migration? -
Target WSGI Script Cannot be loaded as a Python Module: No module named 'pytz'
This error seems fairly simple to solve right? I tried doing pip3 install pytz. But it still seems to think it's not there. Any ideas? For context I'm following this guide https://mindchasers.com/dev/apache-install And here is my error.log: [Tue Nov 05 16:36:26.413502 2019] [wsgi:error] [pid 23202:tid 140594089387776] mod_wsgi (pid=23202): Target WSGI script '/build/CommsApp/CommsApp/wsgi.py' cannot be loaded as Python module. [Tue Nov 05 16:36:26.413537 2019] [wsgi:error] [pid 23202:tid 140594089387776] mod_wsgi (pid=23202): Exception occurred processing WSGI script '/build/CommsApp/CommsApp/wsgi.py'. [Tue Nov 05 16:36:26.413732 2019] [wsgi:error] [pid 23202:tid 140594089387776] Traceback (most recent call last): [Tue Nov 05 16:36:26.413800 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/CommsApp/CommsApp/wsgi.py", line 12, in <module> [Tue Nov 05 16:36:26.413805 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.wsgi import get_wsgi_application [Tue Nov 05 16:36:26.413811 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/wsgi.py", line 2, in <module> [Tue Nov 05 16:36:26.413815 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.handlers.wsgi import WSGIHandler [Tue Nov 05 16:36:26.413820 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/handlers/wsgi.py", line 8, in <module> [Tue Nov 05 16:36:26.413824 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.core.handlers import base [Tue Nov 05 16:36:26.413830 2019] [wsgi:error] [pid 23202:tid 140594089387776] File "/build/django/django/core/handlers/base.py", line 8, in <module> [Tue Nov 05 16:36:26.413833 2019] [wsgi:error] [pid 23202:tid 140594089387776] from django.urls import … -
select2 multi select box only takes in the last selected value into the array
I recently tried using select2 multi-select box in my django app, the select2 box displayed properly and I can select multiple options like it should, but there is just a problem when the selected values taken into the array, this is my code : html page <head> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" /> <script src="{% static 'js/vendor/jquery-3.4.1.min.js' %}"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script> <script> $(document).ready(function() { $('.recipientMultiSelect').select2({ placeholder: "Choose Recipient Numbers / Groups", tags: true }); }); </script> </head> <body> <form action="{% url 'broadcast_single' %}" method="POST"> {% csrf_token %} <div class="col-md-4"> <div class="form-group"> <label for="broadcast_name" class="col-form-label"> Broadcast Name: </label> <input type="text" name="broadcast_name" class="form-control" required> </div> </div> <div class="col-md-4"> <div class="form-group"> <label for="recipients[]" class="col-form-label"> Recipient List: </label> <select class="recipientMultiSelect form-control" name="recipients[]" multiple="multiple" required> <option value="aaaaaa">aaaaaa</option> <option value="bbbbbb">bbbbbb</option> <option value="cccccc">cccccc</option> </select> </div> </div> </br> </br> </br> </br> <div class="col-xs-8 col-md-8"> <div class="form-group"> <label for="broadcast-content" class="col-form-label"> SMS Content: </label> <textarea name="broadcast_content" rows="15" cols="85" maxlength="160" class="form-control"> </textarea> </div> </div> <div class="col-xs-8 col-md-8"> <div class="form-group"> <button class="btn btn-primary btn-block mt-4" type="submit">Send Broadcast</button> </div> </div> </form> </body> lets assume that all 3 options are selected and passed into the array recipients[] views.py def broadcastSingle(request): if request.method == 'POST': bcName = request.POST['broadcast_name'] bcRecArray = request.POST['recipients[]'] bcContent = request.POST['broadcast_content'] print('PRINT : ',len(bcRecArray)) print(', … -
How to make DRF pass query parameters to the actions
I am using filtering in the django rest framework using django-filters. Due to the nature of some @actions I have on my viewset, I need the filter parameters to be passed to these actions. Is there any way to pass the query parameters of the current listview of a viewset to these actions? -
Converting a C++/Python desktop application to web app
I have a desktop application that's essentially a glorified Monte Carlo simulation. The simulation is written in C++ (<10,000 lines of code) and the GUI, which calls the .exe is written in python (don't ask, I had (bad) reasons). I'm looking to convert this to a web application on Azure, which I know is going to be a less than trivial task, but I'm hoping to get advice on how to best do this. From how I see this, I have three options, modifying the C++ code and somehow converting this to a web app, rewriting entirely in the .NET framework using C#, or rewriting entirely with Django/Python. Regardless of what I do, I'll have a ton to learn, and I'll need to completely rewrite the front end. Modifying the C++ code seemed like the best option at first. However, after doing some research, I'm thinking my modifications will be heavy, and C++ really isn't an ideal fit for web apps to begin with. I'm worried that between the likely heavy modifications and the finagling I'll have to do with C++, that will greatly outweigh me getting to reuse a good amount of code. The next option would be to … -
Django Runserver Crashes without Message
I've been working a project for months using Python3 & Django, never had issues regarding starting django but yesterday I formatted my Mac, I have the project in Github so today I clone the project and had bunch of issues with Psycopg2 and Pillow but eventually fixed it. The problem now is that, when on the terminal I put python manage.py runserver, django simply crashes without any message and I don't know how to find the problem or view any logs regarding the crash, this is all I get: (backend) ➜ src git:(master) ✗ python manage.py runserver 3Watching for file changes with StatReloader Performing system checks... After that it simply crashes and nothing else happens. Any ideas on how to debug this problem? I've tried cloning it again and building it but same results. -
Read file in Django Management Command
I'm trying to read credentials for the Google Sheets API using gspread. I wrote the following code: class Command(BaseCommand): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def handle(self, *args, **kwargs): scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name('/static/json/spreadsheets.json', scope) gc = gspread.authorize(credentials) wks = gc.open("Where is the money Lebowski?").sheet1 self.stdout.write(self.style.SUCCESS('Succesfully ran "sheets" command')) Reading the file returns the following error: FileNotFoundError: [Errno 2] No such file or directory: 'static/json/spreadsheets.json' I tried multiple paths like: '~/static/json/spreadsheets.json' '/json/spreadsheets.json' 'spreadsheets.json' But none seem to work. Could anybody help me out here? -
Why doesn't Django Rest Framwork show the posted latitude?
I've got a Django code base which uses Django Rest Framework (DRF) for an API which serves the contents of the DB to the frontend. I now also want users to be able to post new content through this API. I got the API to accept POSTs, but I've got trouble with a gis Pointfield. In one of my models I've got the following field: from django.contrib.gis.db import models as gis_models class Device(models.Model): geometry = gis_models.PointField(name='geometry', null=True, blank=True) # And some other fields I let people post the geometry in two separate fields (latitude and longitude) which I then want to write to the geometry field. I've got a DeviceSerializer which looks like this: class DeviceSerializer(HALSerializer): types = TypeSerializer(many=True) longitude = serializers.SerializerMethodField() latitude = serializers.SerializerMethodField() organisation = serializers.SerializerMethodField() class Meta: model = Device fields = ( '_links', 'id', 'types', 'longitude', 'latitude', 'organisation' ) def get_organisation(self, obj): if obj.owner: return obj.owner.organisation return 'Unknown' def get_longitude(self, obj): if obj.geometrie: return obj.geometrie.x def get_latitude(self, obj): if obj.geometrie: return obj.geometrie.y def create(self, validated_data): print(validated_data) # IN HERE I DON'T RECEIVE THE POSTED LATITUDE AND LONGITUDE types_data = validated_data.pop('types') device = Device.objects.create(**validated_data) for type_data in types_data: Type.objects.create(device=device, **type_data) if 'longitude' in validated_data and 'latitude' in … -
why i have ValueError Django
I have this ValueError views.py def category_post(request, category): posts = get_object_or_404(Post, category=category) return render(request, 'blog/category.html', {'posts': posts}) or def category_post(request, category): posts = Post.objects.filter(category=category) return render(request, 'blog/category.html', {'posts': posts}) or def category_post(request, category): posts = Post.objects.get(category=category) return render(request, 'blog/category.html', {'posts': posts}) I have this error: invalid literal for int() with base 10: 'business' where i made wrong? -
Create boolean twin field automatically for Django model fields
I have models with many fields. For a large amount of those fields (let's say around 20) but not all of them I would like to automatically create a twin BooleanField each. Some requirements: The fields are of different type (e.g. CharField, DateField, ...) In the future there will be new fields added, which is why I want to create this generic solution such that I'll only have to add the main field and mark it for adding a twin Ideally I would like to be able to use the same ORM syntax for filtering and such as if I had manually defined the boolean twin Most of the times just the fields themselves are needed, only very rarely the boolean twin Given the following model from django.db.models import model class MyModel(models.Model): ignore_field = models.Charfield(max_length=10) my_field = models.Charfield(max_length=30) I would like to automatically add the field: is_fixed_my_field = models.BooleanField(default=False) What I have considered: 1. composite-fields The problem I see with that approach is that I will need to define such a composite field for every field type manually and I am also not sure if I can pass kwargs. Also, I don't think I can keep the default syntax for … -
Problems saving Django ORM object with a many to one relationship
I have this model: class Answer(models.Model): order = models.IntegerField() question_key = models.IntegerField() answer_index = models.IntegerField() user_session = models.ForeignKey( UserSession, on_delete=models.CASCADE, related_name="answers" ) user_session cannot be None and I'd love to keep it that way. This is how I'm trying to save an Answer object: answer = Answer( question_key=question_key, answer_index=answer_index, user_session=user_session, order=answer_order, ) answer.save() But I get the error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'user_session'. My research suggests that I need to save the Answer object prior to adding the user_session to it. However, I can't do that if I would like to preserve the not null constraint on the Answer model. Is there a better way to solve this or should I just allow Answer.user_session to be nullable? -
Django - Form not displaying in HTML when receiving an error
In my Django project, I display a form when a user sends a GET request. Here's the code for this: form = SignUpForm() if request.method == 'POST': .... else: return render(request, 'users/signup.html', {'form': form}) HTML FOR THIS: <form method="POST" class="signupform"> {% csrf_token %} {% for field in form %} <div class="fields">{{ field }}</div> {{ field.errors }} <br> {% endfor %} <input class="submitButton" type="submit" value="Sign Up"> </form> If the user sends a post request, I set form = SignUpForm(request.POST) and check if a user with the same username as someone else exists. When this happens, I want to render the whole page again, including the form fields, with an error message displayed. Here's my current code for this: try: user = User.objects.get(username=form.cleaned_data['username']) return render(request, 'users/signup.html', {'error': 'Username field has already been taken', 'form':form}) except User.DoesNotExist: ... HTML: {% if error %} <form method="POST" class="signupform"> {% csrf_token %} {% for field in form %} <div class="fields">{{ field }}</div> {{ field.errors }} <br> {% endfor %} <input class="submitButton" type="submit" value="Sign Up"> </form> {{ error }} {% endif %} However when this error occurs, The error message does show but none of the form fields are displayed on the screen. They disappear. Does anybody …