Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django facebook data deletion callback
Does someone have an working example of facebook data deletion callback? I was searching for it for quite a long time, but still didn't find any, only on php and node.js, so if someone have a working example or link to git repository i wil be greatfull. -
Django: Pass form.cleaned_data to the view that handles the page to where user is being redirected with HttpResponseRedirect
I have the following situation and would appreciate your help very much. Making use of the Post/Redirect/Get design pattern, I have created a form with Django Forms. This then redirects to a page with HttpResponseRedirect. I have created a view for that page and that part works fine. I would like to use the form data (form.cleaned_data) on the redirected page to dynamically insert the (form.cleaned_data) values to a sql script and show the results using a template. Everything works smoothly but I just don't succeed in passing the form data. What works: Form (and the view with that form). Sql functionality works, without dynamically added form data, so it is a static sql for now. templating works fine redirect works fine. As you can see, all works fine but I can't make it dynamic. How to capture the cleaned form data and pass / forward it to the page (view) that loads with HttpResponseRedirect, (which is a page that loads using the GET method)? Thank you very much in advance. Kindest regards, PieThon -
Django Rest Framework - Optimize Serializer with nested objects and @property on related Model
Let me explain briefly the context with some code. Two related Models. One of them has a really expensive @property field: # models.py class MyModel(models.Model): [... fields ...] class RelatedModel(models.Model): [... fields ...] related_field = models.ForeignKey(MyModel, ...) @property def expensive_query_field(self): return OtherModel.objects.filter( Q(some_field__some_relation__id=self.some_field_id) | Q(some_other_field__some_other_relation__id=self.some_other_field_id) | [...] ).distinct().order_by('-id') On the serializer side those are mirrored: # serializers.py class RelatedModelSerializer(serializers.ModelSerializer): [... fields ...] expensive_query_field_objects = OtherModelSerializer(many=True) class MyModelSerializer(serializers.ModelSerializer): [... fields ...] related_field_objects = RelatedModelSerializer(many=True) Everything works fine BUT it's really inefficient, since the @property is a python-land thinghy and it's also querying off an unrelated Model I can't really prefetch_related or select_related to reduce the number of queries. Thus, when serializing an instance of MyModel, I end up with N expensive queries (with N equal to the number of RelatedModel connected to MyModel). I'm looking for optimization ideas to avoid the N+1 queries. I've tried, in MyModelSerializer.to_representation(), to manually pre-fetch all expensive queries in one go for all RelatedModel and then unpack the data directly into Queryset._result_cache but don't want to go so low-level as it makes code more fragile and I'm not even sure it might work :( -
Downloading a file in downloads directory - flask, python
I have a flask app in which it has a button to download an HTML report. The download button when hit creates an xlsx file. It worked fine until that app was running on my local server because the python code found my Downloads directory no matter what os it is using python's os module. Now the app is deployed on a remote server, in this case, how do you let the system know the client's download directory path where this xlsx file can then be created? Or any other pointers for a better solution if I'm missing something? -
DateTimeField not showing previous date and time when editing
I want previously set dates and times to be displayed before they are edited. The previously set name and description of my event are being displayed as it should. Here's a part of my code: Forms: class EventForm(forms.ModelForm): name = forms.CharField(label='Event name', widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(label='Description', required=False, widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 4, 'cols': 15})) date_hour_start = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={'type': 'datetime-local', 'class': 'form-control col-md-4'})) date_hour_end = forms.DateTimeField(input_formats=['%d/%m/%Y %H:%M'], widget=forms.DateTimeInput(attrs={'type': 'datetime-local', 'class': 'form-control col-md-4'})) Views: def event_update_view(request, event_id): event = get_object_or_404(Event, event_id=event_id) event.date_hour_start = datetime.datetime.strftime(event.date_hour_start, '%d/%m/%Y %H:%M:%S') event.date_hour_end = datetime.datetime.strftime(event.date_hour_end, '%d/%m/%Y %H:%M:%S') if request.method == 'POST': form = EventForm(request.POST, instance=event) if form.is_valid(): event = form.save() event.save() return redirect(reverse('list_events')) return redirect(reverse('list_events')) HTML (just a part): <div class="col-md-12"> <p style="margin-bottom: .5rem">Date and Time (Start) <span style="color:red">*</span></p> {{ form.date_hour_start }} </div> <div class="col-md-12"> <p style="margin-bottom: .5rem">Date and Time (End)<span style="color:red">*</span></p> {{ form.date_hour_end }} </div> Why isn't it working? Here's how it's showing. (It's aaaa because it's in Portuguese but it's the year) -
I'm getting this error using axios in my react app
I need to connect my backend and frontend, for that i'm using axios and i'm following this tutorial: https://www.digitalocean.com/community/tutorials/como-crear-una-aplicacion-web-moderna-para-gestionar-la-informacion-de-clientes-con-django-y-react-on-ubuntu-18-04-es but i'm getting this error and i dont know why My Error My backend My frontend1 My frontend2 It's my first time using react , django, and axios so i need help! -
Update or edit a specific field of my form from Django?
I am learning django and I am trying to edit / update a specific field of my model from my ListView, I mean I want to update only my field status, how can I do this? Models.py from django.db import models class RequestContract(models.Model): PENDIENT = "Pendiente" APPROVED = 'Aprobado' REJECTED = 'Rechazado' CANCELLED = 'Cancelado' STATUS = ( (PENDIENT, 'Pendiente'), (APPROVED, 'Aprobado'), (REJECTED, 'Rechazado'), (CANCELLED, 'Cancelado'), ) objective = models.TextField( verbose_name='Objeto', blank=False ) request_date = models.DateTimeField( verbose_name='Fecha de solicitud', null=True, blank=False ) status = models.CharField( verbose_name='Estado', max_length=30, choices=STATUS, default='Pendiente' ) def __str__(self): return self.objective forms.py from django import forms from .models import RequestContract class RequestContractForm(forms.ModelForm): class Meta: model = RequestContract fields = ('__all__') views.py In my listview I am rendering the form using the get_context_data method (I don't know if it is the best way for what I want to do), I think it is a good idea to use the patch method, because I only want to partially update my model, but idk how to use it class RequestContractList(ListView): model = RequestContract template_name = "contratacion/contratacion_list.html" paginate_by=5 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['action_new_url'] = '/requestscontracts_create/' context['form'] = RequestContractForm() return context def patch(self): pass And finally this is my template,I … -
ipfshttpclient.exceptions.StatusError: HTTPError: 405 Client Error: Method Not Allowed for url: http+ip4://127.0.0.1:5001/api/v0/version?
How can I connect IPFS with my Django project? This error is thrown after installing ipfs for django and making changes in settings.py settings.py IPFS_GATEWAY_API_URL= 'http://localhost:8080/ipfs/', IPFS_STORAGE_API_URL= 'http://localhost:5001/api/v0/', IPFS_GATEWAY_API_URL= 'https://ipfs.io/ipfs/', DEFAULT_FILE_STORAGE = 'ipfs_storage.InterPlanetaryFileSystemStorage' IPFS_STORAGE_API_URL = 'http://localhost:5001/api/v0/' IPFS_STORAGE_GATEWAY_URL = 'http://localhost:8080/ipfs/' -
Django Sum of Avg's
I have the existing SQL query and struggling to get the same result from Django SELECT cast(sum(avg)/count(avg) as decimal(13,12)) as a FROM ( SELECT cast(sum(HG)/count(Things) as decimal(13,12)) as avg FROM mydb.mytbl WHERE `stuff` = 'AU' group by Things ) I have managed the count(avg) easy enough and can get the SUM or AVG of all it, but don't know how to get the sum of all the individual avg's -
Django Queryset filter
My code looks like below Extracting the tag-id from the Car class tags = [UUID('1b2990eb-f625-4458-8878-1ab199e3e72b'), UUID('6e663259-9bf0-4e2d-8bf6-11be14218036')] When I try the below codes : Car.objects.filter(uuid__in=tags).values_list('id',flat=True)[0] -> Output 11 Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all()[0] -> Output :11 Car.objects.filter(uuid__in=tags).values_list('id',flat=True).all() -> Output : <QuerySet [11,12]> I want the output in the format of [11,12] -
Passing values from views.py to select tag in html template
I wrote a code that calculates the difference between two stations and the fees required by taking values from the user through the two variables "x" and "y" then calculates stations difference and the fees. I want to know how to pass the values in this code from a function in views.py to select tags in the html template and submit to execute the code. This is the function in views.py def postcalc(request): firstLine = ["Helwan","Ain Helwan","Helwan University","Wadi Hof","Hadayeq Helwan","El- Maasara","Tora El-Asmant","Kozzika","Tora El-Balad","Sakanat El-Maadi", "Maadi","Hadayek El-Maadi","Dar El-Salam","El-Zahraa'", "Mar Girgis","El-Malek El-Saleh","Al-Sayeda Zeinab","Saad Zaghloul", "Sadat","Nasser","Orabi","Al-Shohadaa","Ghamra","El-Demerdash", "Manshiet El-Sadr","Kobri El-Qobba","Hammamat El-Qobba","Saray El-Qobba", "Hadayeq El-Zaitoun","Helmeyet El-Zaitoun","El-Matareyya","Ain Shams", "Ezbet El-Nakhl","El-Marg","New El-Marg"] secondLine = ["El-Mounib","Sakiat Mekky","Omm El-Masryeen","Giza","Faisal", "Cairo University","El Bohoth","Dokki","Opera","Sadat","Mohamed Naguib", "Attaba","Al-Shohadaa","Masarra","Rod El-Farag","St. Teresa","Khalafawy", "Mezallat","Kolleyyet El-Zeraa","Shubra El-Kheima"] thirdLine = ["Adly Mansour","El Haykestep","Omar Ibn El-Khattab","Qobaa","Hesham Barakat", "El-Nozha","Nadi El-Shams","Alf Maskan","Heliopolis Square","Haroun","Al-Ahram", "Koleyet El-Banat","Stadium","Fair Zone","Abbassiya","Abdou Pasha","El-Geish", "Bab El-Shaaria","Attaba"] # Entering Gate check = 0 while(check==0): check = 1 try: x = input("Enter the Source station: ") if x in firstLine: currentStation = firstLine.index(x) currentLine = 1 elif x in secondLine: currentStation = secondLine.index(x) currentLine = 2 elif x in thirdLine: currentStation = thirdLine.index(x) currentLine = 3 except: check=0 msg = "Enter the station again" return render (request, "calc.html", {"msg":msg}) # … -
How to access attributes of the 'User' model extended by another model referenced by a OnetoOneField in admin.py
In model.py, I have a class extending the User model class Tutor(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) In admin.py, I tried to access user.id with 'user_id', which works class TutorAdmin(admin.ModelAdmin): list_display = ('user_id', 'contact_number') However, when I try to access other attributes of 'user' such as username, email with this format class TutorAdmin(admin.ModelAdmin): list_display = ('user_id', 'user_username', 'contact_number') This occurs What is the format to access attributes such as user.username or user.email? -
Error inserting data into Django database field with a OneToOnefield
I've asked this question before and tried to Google it but I've had no luck, so I have simplified my question. I have two very simple models: one holds some shift numbers and the other holds some data related to the sale of gift cards during a shift. In this case, we have an employee who worked shift "1234" and sold $200.45 and $43.67 worth of gift card from each of two terminals. The models are below: class Data_Shifts(models.Model): shift_id = models.CharField(max_length=25, primary_key=True, db_column="shift_id", verbose_name="Shift ID") def __str__(self): return str(self.shift_id) class Data_GiftCards(models.Model): shift_id = models.OneToOneField('Data_Shifts', on_delete=models.CASCADE, primary_key=True, db_column="shift_id", verbose_name="Shift ID") net_sales_terminal_1 = models.DecimalField(max_digits=8, decimal_places=2, default=0) net_sales_terminal_2 = models.DecimalField(max_digits=8, decimal_places=2, default=0) def __str__(self): return str(self.shift_id) I then try to insert some test data into the table using the following command: Data_GiftCards.objects.create(shift_id="1234", net_sales_terminal_1="200.45", net_sales_terminal_2="43.67") Upon submitting the web form, I get the following error: Cannot assign "'1234'": "Data_GiftCards.shift_id" must be a "Data_Shifts" instance. I am boggled by this. I have a workaround that bypasses django and inserts directly into the table successfully, but this is dirty and I'd prefer to use the proper Pythonic Django way. What am I doing wrong here? Many thanks in advance. -
How can I access the outer loop context value in inner loop section in Django Template
In my case, I want to access the context value which is present in the outer for loop and use(print) that value in the inner for loop section. There are two context values one for the outer loop and the other one is for the inner loop. here is my template logic. when the condition becomes false it did not print the values that belong to the outer-loop context variable(else part of if statement not working). <div class="panel-group" id="accordion"> {% for x in queryset %} <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}"> Question </a> </h3> </div> <div id="collapse{{ forloop.counter }}" class="panel-collapse collapse"> <div class="panel-body"> <!-- <input type="button" onclick="updateques();" value="Edit!!"><br> --> <br><br> <div> <form action="tobeupdated" method="POST" enctype="multipart/form-data" > {% csrf_token %} {{x.question.id}} <input type="hidden" id="quesid" name="quesid" value="{{x.question.id}}"> <label>Q- <input type="text" id="ques" name="ques" value="{{x.question.question}}" readonly></label><br><br> <img src="{{x.question.image}}" alt="" srcset="" width="700"><br><br> {% for q2 in queryset2 %} {% if q2.option_id == x.option_id %} <label>A- <input type="text" id="op1" name="op1" value="{{x.option.option1}}" readonly><br><br> <img src="{{q2.option1_img}}" alt="" srcset="" width="400"><br><br> <label>B- <input type="text" id="op2" name="op2" value="{{x.option.option2}}" readonly><br><br> <img src="{{q2.option2_img}}" alt="" srcset="" width="400"><br><br> <label>C- <input type="text" id="op3" name="op3" value="{{x.option.option3}}" readonly><br><br> <img src="{{q2.option3_img}}" alt="" srcset="" width="400"><br><br> <label>D- <input type="text" id="op4" name="op4" value="{{x.option.option4}}" readonly><br><br> <img … -
Django : unique=True constraint does not get removed using django migrations
I have a model as : class order(models.Model): serial = models.CharField(max_length=20,unique=True) I've migrated this model using django migrations (PostgreSql). Now I wish to remove the unique constraint. class order(models.Model): serial = models.CharField(max_length=20) On running makemigrations, only an AlterField migration is created : migrations.AlterField( model_name='order', name='serial', field=models.CharField(max_length=20), ), On migrating this, the unique constraint is not removed. (it's visible in pgAdmin). After this, I tried removing the constraint manually. The unique constraint name as in pgAdmin is 'order_serial_key'. In the migrations file, I added : migrations.RemoveConstraint( model_name='order', name='order_serial_key' ) On migrating, it shows ValueError: No constraint named order_serial_key on model order How can I remove this constraint using migrations ? -
Superuser can't access Django Admin Panel. It shows "You don’t have permission to view or edit anything."
I've created a custom User model in Django==3.2.3 Here is my model.py file class MyUserManager(BaseUserManager): """ A custom Manager to deal with emails as unique identifer """ def _create_user(self, email, password, **extra_fields): """ Creates and saves a user with a given email and password""" if not email: raise ValueError("The Email must be set!") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self._create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=60, unique=True, verbose_name='Email') first_name = models.CharField(max_length=30, verbose_name='First Name') last_name = models.CharField(max_length=30, verbose_name='Last Name') is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('first_name', 'last_name') objects = MyUserManager() def __str__(self): return self.email def get_short_name(self): return self.first_name def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin class Meta: verbose_name_plural = "Users" Here is my admin.py file class MyUserAdmin(UserAdmin): form = UserchangeForm add_form = UserCreationForm list_display = ('email', 'first_name', 'last_name', 'is_admin') list_filter = ('is_admin',) fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': (('first_name', 'last_name'))}), ('Permissions', {'fields': ('is_admin',)}), ) add_fieldsets = … -
No parameter on drf_yasj on using swagger_auto_schema
Code Swagger Page name = openapi.Parameter('Product Name', in_=openapi.IN_BODY, description='Enter Product Name', type=openapi.TYPE_STRING) # cat = openapi.Parameter('Product Category', in_=openapi.IN_BODY, description='Enter Product Category', # type=openapi.TYPE_STRING) @api_view(['POST']) @swagger_auto_schema(manual_parameters=[name]) No parameter option in swagger window -
how to install templates in django? I connected the template to the views file and in the settings file. then i used render to display the template
I connected the template to the views file and in the settings file. then i used render to display the template ** def index(request): return render(request, 'pages/pages.html') ** and in the settings file i setted it through os library os.path.join(BASE_DIR, 'templates') but i'm still getting an error "template does not exist" while i'm very sure i typed the right path and imported the views file in the urls file and everything is fine just that template doesn't load. anyone knows what could be the problem? [1]: https://i.stack.imgur.com/Wdu2g.png -
How to add value to a many-to-many field in Django
Suppose I have a relation as down below: class Student(models.Model): firstname lastname ... class Teacher(models.Model): firstname lastname email ... class Meeting(models.Model): student = models.ManyToManyField(Student) teacher = models.ManyToManyField(Teacher) How should I add/set a value to field 'student' or 'teacher'. I tried to assign an object from related models to them but got an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use student.set() instead. -
How do I overwrite the variable from cleaned_data
I wanted to know how I can save a photo that will contain a watermark. Currently grabs a photo from the form and creates a watermark on it, but saves it separately. More precisely, I would like the photo I send in the form to be processed and saved. if request.method == 'POST': form_w = ImageForm(request.POST, request.FILES) if form_w.is_valid(): form = form_w.save(commit=False) cd = form_w.cleaned_data['img'] im = Image.open(cd) width, height = im.size draw = ImageDraw.Draw(im) text = "TEST WATERMARK" font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) im.save('Luki/media/upload_p/{}'.format(cd)) form.save() return redirect('Luki:gallery') else: form = ImageForm() return render(request, 'Luki/upload_img.html', { 'form': form, }) -
Django admin panel not showing related foreign key correctly - Postgresql
I'm new to Django. I've defined 2 tables and have set a foreign key. So I want to link the column note from table Comment to the column id from table Note. As I'm using PostgreSQL, when I check the psql shell, the name of the column note will be displayed as note_id. So for using in template, if I use something like comment.note, it prints the "quick_note" of the note table, which I don't want that. I want to get the "id" of the related post to the current comment, not the quick_note of the related post. But if I use something like comments.note_id, it shows the id of the related post, which is what I expect to get. Also in the admin panel, I see a field of note: that shows related quick_note not id. How can I fix it that admin panel show the related id? So here I want the id of related post to be shown in front of note:. This is my model.py: class Note(models.Model): title = models.CharField(max_length=100) quick_note = models.CharField(max_length=500) pub_date = models.DateTimeField('date published') author = models.CharField(max_length=100) class Comment(models.Model): text = models.CharField(max_length=200) note = models.ForeignKey(Note, on_delete=models.CASCADE) pub_date = models.DateTimeField('date published') -
Run Celery Task For Past Timestamps
My app was running celery tasks on daily basis. It faced an outage due to some server issues. This made a blank windows in between the tasks. Can somebody let me know if running celery tasks for past timestamps is possible to fill up those gaps? -
The comment form is displayed incorrectly
I am making comments on django on this video https://www.youtube.com/watch?v=bmFkND-scpY when the author in the middle of the video showed what he had done, he showed this (this is how it should be) enter image description here but for some reason it turned out like this enter image description here class Comment in models.py class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255, default="Some String") body = models.TextField(max_length=255, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s' % (self.post.title, self.name) forms.py from django.forms import ModelForm from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['name', 'body'] def detail in views.py def detail(request, slug): post = Post.objects.get(slug=slug) form = CommentForm() context = { 'post': post, 'form': form } return render(request, 'myblog/templates/post_detail.html', context) post_detail.py {% extends 'base.html' %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> <p><a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a></p> <p><a href="{% url 'post_delete' post.pk %}">+ Delete Blog Post</a></p> <img src="{{ post.header_image.url|default_if_none:'#' }}"> {{ post.body|urlize }} {% for comm in post.commentpost_set.all%} {{ comm.user }} <br> {{ comm.text }} <br><br> {% endfor %} <article class="content"> <br><hr> <h2>Add a comment</h2> <form method="post" action="."> {% csrf_token %} {{ … -
Extending django User Model (Unable to add extra fields)
Here is the code files. admin -> init__.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from usermanagement.models import UserProfile scrumboard_models = [models.Board, models.Setting, models.CheckList, models.CheckListItem, models.Comments, models.Subscribers, models.Lists, models.Label, models.Card, models.Attachment, models.Team] admin.site.register(scrumboard_models) class UserProfileAdmin(UserAdmin): list_display = ( 'id', 'first_name', 'username', 'email', 'is_active', 'dob' ) admin.site.register(UserProfile, UserProfileAdmin) **Settings.py** """ Django settings for app project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent import datetime JWT_AUTH = { 'JWT_ALLOW_REFRESH': True, 'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=3600), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'v!t5abxm^t@tyj=z5gp!*_%qy=$q-d6g!4zx(!r3_nn)7h^ee7' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'scrumboard', 'admin_app', 'whitenoise.runserver_nostatic', 'corsheaders', 'usermanagement', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': … -
How to compare IntegerChoice values in Django Templates
I intend to compare the value of an IntegerChoice inside Django Template : class SomeModel(models.Model): class Answer(models.IntegerChoices): NO = 0, _('No') YES = 1, _('Yes') __empty__ = _('(Unknown)') answer = models.IntegerField(choices=Answer.choices) SomeModel.objects.create(answer=0) somemodel = SomeModel.objects.filter(answer=0) Inside template : {% if somemodel.answer == SomeModel.Answer.YES %} ... {% else %} <h1>{{ SomeModel.get_answer_display() }}</<h1> {% endif %} Yet, this does not get inside the true if case, and also does not like "()" at the end of "SomeModel.get_answer_display" with the following message : Could not parse the remainder: '()' from 'SomeModel.get_answer_display()' How can I make the filter work as expected?