Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How I can count the video views in django by ip for Anonymous users
I created a view to get the Anonymous users IP, I want when this user what the video then register this ip has watched the video,I know it's now efficient because might the user use diffrent network, This my model of the user by ip: class UsersByIP(models.Model): ip_user = models.GenericIPAddressField() def __str__(self): return self.ip_user This model to make relationship between the vdeo and the number of viewrs by ip class Video(models.Model): viewers_by_ip = models.ManyToManyField(UsersByIP, default='192.168.0.1', blank=True) I created this view to register the ip as view but I got this error: Field 'id' expected a number but got '127.0.0.1' and I couldn't solv it. The view: num_views_by_ip = Video.objects.annotate( num_views_ip=Count('viewers_by_ip'), ).order_by('-viewers_by_ip') data = get_object_or_404(num_views_by_ip, pk=pk) ip_user = UsersByIP(ip_user=request.META.get('REMOTE_ADDR')) if not request.user.is_authenticated: __, created = Video.viewers_by_ip.through.objects.get_or_create( video=data, usersbyip=request.META.get('REMOTE_ADDR') ) if created: data.num_views_by += 1 I would like to get any suggestions to solve this view or make a new view (logic) -
Django is sending error mails to admins but they don't reach Sentry
We have a site in production where Sentry is enabled but strangely some of the errors are not being reported to Sentry but are only being sent as emails to the admins set in the settings. Which logger settings we need to change so that only Sentry is used and no direct emails are sent? Our project is based on the cookiecutter-django code base. This is our current logger settings: General logger settings: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "root": {"level": "INFO", "handlers": ["console"]}, } and the Sentry config: SENTRY_DSN = env("SENTRY_DSN") SENTRY_LOG_LEVEL = env.int("DJANGO_SENTRY_LOG_LEVEL", logging.INFO) sentry_logging = LoggingIntegration( level=SENTRY_LOG_LEVEL, # Capture info and above as breadcrumbs event_level=logging.WARNING, # Send errors as events ) sentry_sdk.init( dsn=SENTRY_DSN, integrations=[sentry_logging, DjangoIntegration(), CeleryIntegration()], ) -
How can I filter questions that are answered/unanswered?
In attempting to replicate the unanswered QuerySet functionality of Stack Overflow, I'm left stuck how this would be done at the table level? How would I go about implementing a QuerySet where it returns all unanswered questions when the Question model doesn't have any foreign key reference to Answer on the table itself? It's only when an individual question has been queried that reverse relationship of answers can be accessed. class QuestionStatusQuerySet(models.QuerySet): def unanswered(self): pass def newest(self): pass class Question(models.Model): title = models.CharField(unique=True, max_length=50) body = models.TextField() dated = models.DateField(default=date.today) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="questions" ) tags = models.ManyToManyField(Tag, related_name='questions') objects = models.Manager() dateranges = DateRangeQuerySet.as_manager() status = QuestionStatusQuerySet.as_manager() class Meta: ordering = ['-dated'] default_manager_name = "objects" def __str__(self): return self.title class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="answers" ) response = models.TextField() dated = models.DateField(auto_now_add=True) likes = models.IntegerField(default=0) user_account = models.ForeignKey( 'users.UserAccount', on_delete=models.SET_NULL, null=True, blank=True, related_name="answers" ) class Meta: ordering = ['-likes'] -
Django's 'python manage.py runserver' does not create a local website I can access
I am trying to follow this online class, and I am stuck on the part where I access a local website made by django. The tutorial that I follow is this one by freecodecamp, and I get stuck by the 11min mark where I try to access the output site http://127.0.0.1:8000/ . I am following this tutorial on the browser version of Jupyter Notebook. Tutorial: https://www.freecodecamp.org/news/create-an-e-commerce-site-with-django-and-vue/ The 'python manage.py runserver' line runs, and I get the following output: System check identified no issues (0 silenced). April 16, 2021 - 03:37:04 Django version 3.2, using settings 'djacket_django.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. When I copy and paste the server address into the browser, I just get the following error saying that I wasn't able to connect to the site: Unable to connect Firefox can’t establish a connection to the server at 127.0.0.1:8000. The only resource I really found that addressed this issue was the following post, but when I went through my netstat list, there were no IPs listing :8000, so I don't think that I am using up that address already. Post: Django manage.py runserver is not working -
I got the msg can't fork because you own this repository while share code to another git account multiple developers on same project
I got the message cannot fork because you own this repository I am trying to send the code on this repo to another account when I tried to share my code to another git account 'while working with multiple developers on same project" and I am new to git hub -
how to compare two lists in different functions in Python?
I am making a Django web Application and i am facing a problem in comparing two different lists in different functions def marks(correct): list1=[] l1=correct def score(and): list2=[] l2=ans how can I compare l1 and l2? -
Django serializer JSON file in database
I have model to load JSON file in my PostgreSQL database.When I migrate,getting some error message. This URL is my JSON field: https://jsoneditoronline.org/#left=cloud.aabe0ab0f87349deada424286dc5c737 First, I create model to load JSON file. from django.db import models WEEKDAYS = [ (1, ("Monday")), (2, ("Tuesday")), (3, ("Wednesday")), (4, ("Thursday")), (5, ("Friday")), (6, ("Saturday")), (7, ("Sunday")), ] class BookStore(models.Model): cash_balance = models.FloatField(null=False) store_name = models.CharField(max_length=100, null =False) opening_hours = models.ManyToManyField('OpeningHours') class Book(models.Model): books = models.ForeignKey(BookStore, on_delete=models.CASCADE) book_name = models.CharField(max_length=100, null=False) price = models.FloatField(null=False) class OpeningHours(models.Model): week_day = models.CharField(max_length=20, choices=WEEKDAYS) start_min = models.TimeField() end_min = models.TimeField() Then, I create 0002_load_json.py to loaddata jsondata.json in migrations directory import os from django.db import migrations from django.core.management import call_command from django.core import serializers book_store_json_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../data')) book_store_filename = 'book_store_data.json' def load_book_store(apps, schema_editor): book_store_file = os.path.join(book_store_json_dir, book_store_filename) call_command('loaddata', book_store_file) # book_store = open(book_store_file, 'rb') # objects = serializers.deserialize('json', book_store, ignorenonexistent=True) # for obj in objects: # obj.save() # book_store.close() # def unload_book_store(apps, schema_editor): book_store_model = apps.get_model("bookstore_api", "model") book_store_model.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('bookstore_api', '0001_initial'), ] operations = [ migrations.RunPython(load_book_store, reverse_code=unload_book_store), ] When I execute manage.py migrate myapps, I get some error message. django.core.serializers.base.DeserializationError: Problem installing fixture -
How to request get name value from <input name={{}}> in django view
I have code blew as: In djang view, how to get input value. if name is not variable, I can get value by request.POST.get("aaa"),but now, I dont know how to do it, pls help, thanks. {% for resu01 in Testpapers %} {{resu01.id}} {{resu01.subject}} {{resu01.duration}} {{resu01.passscore}} {{resu01.examendtime}} {{resu01.subject_id}} start {% endfor %} -
How to make charts using django
Hi I am new to web development and django. I am currently creating a clock in clock out system in a web app. Is there a way to get the clock in clock out information and turn it into a graph or chart? -
CSS file not reloading on change with nginx-gunicorn-django
Firstly I've tried most of the solutions suggested in Stack and from Google. None of the below solutions work when DEBUG MODE is off. sudo systemctl daemon-reload , sudo systemctl restart gunicorn to make sure its not a gunicorn issue Turned off all caching from nginx. Made sure this was the case with curl -I "https://swjungle.shop/2static/CACHE/css/output.9291a1ea98ad.css" returns Cache-Control: no-cache Checked Nginx config again. If debug=True the static files are still not reloaded until collectstatic. But after collectstatic it works. .staticfiles is my STATIC_ROOT location /2static { alias /home/.staticfiles; } sudo systemctl restart nginx also does not reload caching My browser caching is off and I did a hard reload , Ctrl + F5. Deleted all cookie. None of it works... Struggling to find a solution. -
Django is returning JsonResponse, can see the desired JSON response in browser Network tab, but unable to access on the FE
Not quite sure what I'm doing wrong here. I have a method in utils.py that returns the dictionary: import boto3 import base64 # Create a Rekognition client def detect_faces(photo): ... return { 'comment': comment, 'rekognition_response': response, 'url': url, } Which sent back to the views.py: from django.shortcuts import render from django.http import JsonResponse, HttpResponse from . import utils def index(request): return render(request, 'index.html') def submit(request): response = utils.detect_faces(request.body) return JsonResponse(response) I can see the response I'm expecting in the Network tab of the browser: But then on FE, I'm not seeing it in the res: const submitScreenshot = async () => { const picture = document.getElementById('webcam-picture-submit').src; const res = await fetch('/submit/', { method: 'POST', headers: { 'X-CSRFToken': csrftoken }, body: picture.replace('data:image/png;base64,','') }) console.log(res); console.log('Submitted.'); }; I get the sense this is something super basic I'm missing, what is it? -
How to query ManyToMany field using current user in django?
In my django app I have a Message Model with a sender (User) and some receivers (also Users). I want to display in a ListView, all messages that have the current logged user as one of its receivers (the current user must be in the receivers ManyToMany) How to I do that? Here is my code: class MessageModel(models.Model): MESSAGE_TYPE_CHOICES = ( ('draft', 'borrador'), ('new', 'nuevo'), ('red', 'leido'), ('deleted', 'borrado'), ) subject = models.CharField(verbose_name="Asunto",max_length=50) sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='+', verbose_name='destinatario', editable=False, null=True, blank=True) receivers = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name="destinatarios") received_date = models.DateTimeField(verbose_name="Fecha" ,auto_now_add=True) state = models.CharField( verbose_name="Estado", max_length=50,blank=False, null=False, choices=MESSAGE_TYPE_CHOICES, default="new") message_body = models.TextField(verbose_name="Mensaje") @property def get_receivers(self): return self.receivers.all() class Meta: verbose_name = "Mensaje" verbose_name_plural = "Mensajes" def __str__(self): return self.subject class MailboxListView(LoginRequiredMixin, ListView): model = MessageModel template_name = 'mailapp/inbox.html' context_object_name = 'messages' def get_queryset(self): # here i want to get only the messages in wich the current user is a receiver query_result = MessageModel.objects.all().order_by('received_date') return query_result -
no confirm send when user update his email but it saved new email without confirm - django
i create change email in user profile and when user change email to new one no confirm send to his new email but it saved new email without confirm , what is the problem here views.py : # Edit Profile View @method_decorator(login_required, name='dispatch') class EmailChange(UpdateView): model = User form_class = EmailChangeForm success_url = reverse_lazy('home') template_name = 'user/commons/EmailChange.html' def get_object(self, queryset=None): def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your site email ' message = render_to_string('user/emails/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete change email.')) return redirect('login') return self.request.user tokens.py : from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class AccountActivationTokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.profile.email_confirmed) ) account_activation_token = AccountActivationTokenGenerator() -
Django File Upload Button working but files storing in Project File(VSCode)
I'm trying to make a file upload system in django. My file upload button is working but files storing in project file. Also, i'm using MongoDB and my uploaded files displaying there too. Is this a database issue or is there something wrong about the views.py, models.py? So this is my code, view.py def link1(request): if request.method == "POST": uf=UploadFileForm(request.POST,request.FILES) if uf.is_valid(): uf = FileUpload(file = request.FILES['file']) uf.user = request.user uf.save() else: uf=UploadFileForm() return render (request,'blog/links/Link1.html',{'uf': uf}) models.py from djongo import models from django.contrib.auth.models import User class FileUpload(models.Model): file = models.FileField() user = models.ForeignKey(User, on_delete = models.CASCADE) forms.py from django import forms from .models import FileUpload class UploadFileForm(forms.ModelForm): class Meta: model= FileUpload fields = ['file'] -
Django ListView works but DetailView not displaying Model Data
I am helping my daughter with her computing Project for school. It is a simple generic forum type application. She has a ListView for a model which works fine: {% extends 'users/main.html' %} <!-- Here is where our content will begin --> {% block content %} <h1>This is posts.html!</h1> <br/> {% for obj in object_list %} <h2>{{ obj.topic }}</h2> {{ obj.date_posted }} <br/> {{ obj.content }} <br/> Author: {{ obj.author }} <br/><br/> {% endfor %} {% endblock %} She then added a DetailView which is simply the same code with the loop removed: {% extends 'users/main.html' %} <!-- Here is where our content will begin --> {% block content %} <h1>This is posts.html!</h1> <br/> {{ obj.id }} <h2>{{ obj.topic }}</h2> {{ obj.date_posted }} <br/> {{ obj.content }} <br/> Author: {{ obj.author }} <br/><br/> {% endblock %} This is then called with a '....post/1/' (post id = 1 does exist (checked via DB Browser and in the ListView) and the path and naming of the template is correct. Frustratingly, this displays the page but not the details inside the django temp language brackets (object.topic etc)! When I look at the page source for the section dealing with the detail, I get: … -
django orm filter and exclude by related date field
models.py class Model(models.Model): ... class RelatedModel(models.Model): date = models.DateField() I want to filter objects realted by a DateField by month and year. first I do Model.objects.all() and I see 3 instances second I filter like this: Model.objects.filter(related_model__date__month=6, related_model__date__year=2021) the result is just 1 instance out of 3 third and last, I filter like this Model.objects.exclude(related_model__date__month=6, related_model__date__year=2021) and the result is empty, I was so sure that the result will be the opposite to the second query, like 2 out of 3 instances. any explanation? thanks. -
Django admin inline change fields on new record
Background I'm customizing the admin pages for an inventory system with a lot of ManyToMany relationships and other complex data. I want to display these relationships using Inlines, but I don't like the default drop-down field that Django uses for ManyToMany relationships in an Inline so I customized the field set. My custom fields are relatively simple, an ID field that links to the related record, readonly text fields with data from the related record since the Inline can't get fields from the related record by default; that sort of thing. Problem The issue is that in order to use custom fields in these inlines, I've had to make them all read-only. Normally that's fine, because of the linked ID field, but it's impossible to add a new record via the button on the Inline because I can't enter any of the necessary information. My IDs aren't even auto-incremented since this data needs to sync up with another Database, so the new row doesn't link to a newly created record. Basically, what I want to do is have a different set of writable fields on newly added rows so that required fields, like the ID, can be filled. Issues I've … -
Erro 500 / in handle / in handle_request / required 'SEND' - Django ASGI + Gunicorn + Nginx
I have a serious problem that made me lose a couple of hours and nothing solves. Below the installed modules: Package Version ---------------------------- --------- asgiref 3.3.4 attrs 20.3.0 autobahn 21.3.1 Automat 20.2.0 certifi 2020.12.5 cffi 1.14.5 channels 3.0.3 chardet 4.0.0 constantly 15.1.0 cryptography 3.4.7 daphne 3.0.2 Django 3.1.7 django-appconf 1.0.4 django-bootstrap-modal-forms 2.1.0 django-compressor 2.4 django-crispy-forms 1.11.2 django-drf-filepond 0.3.0 django-extensions 3.1.2 django-filter 2.4.0 django-mathfilters 1.0.0 django-model-utils 4.1.1 django-pandas 0.6.4 django-redis 4.12.1 django-stdimage 5.3.0 django-storages 1.11.1 django-widget-tweaks 1.4.8 djangorestframework 3.12.4 geographiclib 1.50 geopy 2.1.0 gunicorn 20.1.0 hyperlink 21.0.0 idna 2.10 importlib-metadata 3.10.1 incremental 21.3.0 Markdown 3.3.4 numpy 1.20.2 pandas 1.2.4 Pillow 8.2.0 pip 21.0.1 psycopg2 2.8.6 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 PyHamcrest 2.0.2 pyOpenSSL 20.0.1 python-dateutil 2.8.1 pytz 2021.1 rcssmin 1.0.6 redis 3.5.3 requests 2.25.1 rjsmin 1.1.0 service-identity 18.1.0 setuptools 54.1.2 shortuuid 1.0.1 six 1.15.0 sqlparse 0.4.1 Twisted 21.2.0 txaio 21.2.1 typing-extensions 3.7.4.3 urllib3 1.26.4 uvloop 0.15.2 wheel 0.36.2 zipp 3.4.1 zope.interface 5.4.0 When running the server on 'python3 manage.py runserver' or 'python3 manage.py runserver 0.0.0.0:8000', everything is perfect! However, when running the system with gunicorn + nginx, I have the following error output: gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Thu 2021-04-15 … -
Problem in the integration of django and react
I have a problem integrating my template with django. I have set up the webpack w and babel correctly and I ran the run dev webpack but I don't get any result in the server. [enter image description here][1] Index.html ``` Diet {% load static %} <link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}" /> <script src="{% static "frontend/main.js" %}"></script> </body> </html>``` this is my index.js ``` import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import { BrowserRouter } from 'react-router-dom'; import reportWebVitals from './reportWebVitals'; // Css import '../node_modules/animate.css/animate.css'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import '../node_modules/slick-carousel/slick/slick.css'; import '../node_modules/slick-carousel/slick/slick-theme.css'; import '../node_modules/magnific-popup/dist/magnific-popup.css'; import '../node_modules/react-select2-wrapper/css/select2.css'; import '../node_modules/leaflet/dist/leaflet.css'; import './assets/fonts/flaticon/flaticon.css'; import './assets/fonts/font-awesome/css/all.min.css'; import './assets/css/style.css'; ReactDOM.render( <BrowserRouter> <App /> </BrowserRouter>, document.getElementById('app') );``` [1]: https://i.stack.imgur.com/UDFik.png -
django.db.utils.DatabaseError with Django and Djongo
I keep running into the django.db.utils.DatabaseError error with trying to migrate the database changes in a Django project. Terminal Output: Running migrations: Not implemented alter command for SQL ALTER TABLE "project_name_user" ALTER COLUMN "age" TYPE double Applying project_name.0002_auto_20210415_1452...Traceback (most recent call last): File "...\.venv\lib\site-packages\djongo\cursor.py", line 51, in execute self.result = Query( File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 783, in __init__ self._query = self.parse() File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 875, in parse raise e File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 856, in parse return handler(self, statement) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__ super().__init__(*args) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__ super().__init__(*args) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__ self.parse() File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse self._alter(statement) File "...\.venv\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter raise SQLDecodeError(f'Unknown token: {tok}') djongo.exceptions.SQLDecodeError: Keyword: Unknown token: TYPE Sub SQL: None FAILED SQL: ('ALTER TABLE "project_name_user" ALTER COLUMN "age" TYPE double',) Params: ([],) Version: 1.3.4 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "...\.venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "...\.venv\lib\site-packages\djongo\cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: Traceback (most recent call … -
Django user uploadind files without forms, button doesn't work
I'm trying to make a file upload page in my web site but I want to make this page without forms. I wrote my models.py and views.py files. When I click on "Choose File" button it doesn't gives error but it doesn't work either. So, I'm this is my codes, views.py def link1(request): if request.method == "POST": if request.POST.get('submit') == 'Upload': file_info = request.POST, request.FILES['file_info'] if not file_info.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') return redirect('/mainpage') file_info = FileUpload(file = request.FILES['file_info']) file_info.user = request.user file_info.save() return render (request,'blog/links/Link1.html') models.py from djongo import models from django.contrib.auth.models import User class FileUpload(models.Model): file = models.FileField() user = models.ForeignKey(User, on_delete = models.CASCADE) -
UnboundLocalError when submitting form in Django App
I am trying to submit a form but receiving an error: UnboundLocalError at /create/ local variable 'spr' referenced before assignment Below is the section of my views.py file that is highlighted in the error, specifically: return HttpResponseRedirect("/%i" %spr.id) def create(response): if response.method == "POST": form = CreateNewSprint(response.POST) if form.is_valid(): n = form.cleaned_data["name"] spr = Sprint(name=n) spr.save() response.user.sprint.add(spr) return HttpResponseRedirect("/%i" %spr.id) else: form = CreateNewSprint() return render(response, "main/create.html", {"form": form}) I am unsure of why this is happening, any pointers in the right direction would be greatly appreciated. If any other code/information is needed please let me know. -
Reduce Intial Server Response Time On Django Nginx
I have deployed a django 3.1 peoject on nginx 1.18 and gunicorn. I'm trying reduce website server response time (TTFB). The trouble i'm facing right now is that the webpage first renders all the data then display the webpage. Please refer the screenshot. Image 1 Image 2 -
Django, i can't put function form inside generic.UpdateView
I am making a app for one kindergarten in my city. I have kids model and payment model. For updating kid I am using class based view generic UpdateView and for creating a payment i am using form and function view. I have not problems with payment form when I am using a different template but when I try to put it on the same template, payment form is not showing up and it's not working. Is it possible to have payment form on same template as UpdateView class ? I am using UpdateView class as profile page and I would like to have payment form on the same page. Please help. Thanks models: class Kids(models.Model): name = models.CharField(max_length=100, blank=True, null=True) city_birthday = models.CharField(max_length=100, blank=True, null=True) custom_id = models.CharField(max_length=100 ,blank=True, null=True) gender = models.CharField(max_length=100, choices=gender_choices, null=True, blank=True) address = models.CharField(max_length=250, null=True, blank=True) contact_phone = models.CharField(max_length=100, blank=True, null=True) family_size = models.IntegerField(null=True, blank=True) living_with = models.CharField(max_length=100, choices=living_choices, null=True, blank=True) number_of_preschool_kids_in_family = models.IntegerField(null=True, blank=True) kid_already_been_in_kindergarten = models.CharField(max_length=100, choices=preschool_choices, null=True, blank=True ,default=False) father_name = models.CharField(max_length=100, blank=True, null=True) father_education_level = models.CharField(max_length=200, blank=True, null=True) father_company = models.CharField(max_length=200, blank=True, null=True) mother_name = models.CharField(max_length=100, blank=True, null=True) mother_education_level = models.CharField(max_length=200, blank=True, null=True) mother_company = models.CharField(max_length=200, blank=True, null=True) parent_notes = … -
Can't get a combination of if and elif to work in django
I have two variables, date1 and date2, both DateField. Here's what I'm trying to write: if date1 and date2 have values, display "Datation évaluée entre date1 et date2". if date1 have value but not date2, display "Datation évaluée vers date1". if date2 have value but not date1, display "Datation évaluée vers date2". if neither date1 nor date2 have values, don't display anything. Here is my code: {% if 'date1' and 'date2' %} Datation évaluée entre {{ object.date1 }} et {{ object.date2 }}. {% elif not 'date1' %} Datation évaluée vers {{ object.date2 }}. {% elif not 'date2' %} Datation évaluée vers {{ object.date1 }}. {% elif not 'date1' or 'date2' %} Datation inconnue. The first condition appears indeed, but not the others. When there's a value only on one side, I get "Datation évaluée entre value1 et None.", and when there are no values, I get "Datation évaluée entre None et None." Any ideas what's wrong in the code? Thanks for your help.