Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
need a better way to validate fields in request body django depending on a specific field value
The requirement is to verify body fields in an api request depending on another field. Like: the request data has a field: action If actions is deactivate then no other field should be present in the body data however if the action is anything else we want to allow updating other fields as well such as name. currently we have a validation where we are going through the dictionary keys and comparing like below: expected_keys = ['client_updated', 'updated_by', 'actions'] if key not in expected_keys: raise ValidationError("Deactivation action does not allow {} to be updated".format(key)) Just wanted to know if there is a better way to handle via django or django rest framework, with somewhat less harcoding. -
Why create_superuser manager is not working in custom user model?
When I try to create a superuser in my app I get the next error: Traceback (most recent call last): File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 22, in <module> main() File "C:\Users\acer\Desktop\prod\DirCom\DirCom\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 88, in execute return super().execute(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 183, in handle validate_password(password2, self.UserModel(**fake_user_data)) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\base.py", line 561, in __init__ _setattr(self, field.name, rel_obj) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 338, in __set__ super().__set__(instance, value) File "C:\Users\acer\Desktop\prod\DirCom\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 235, in __set__ raise ValueError( ValueError: Cannot assign "1": "User.persona" must be a "Persona" instance. Before that createsuperuser step I have a custom script that creates the first Persona of the project, and what I'm trying is to assign the first person created with ID 1 to this superuser. My model looks like this: class Persona(models.Model): """ Clase para generar mi modelo de Persona que es el modelo previo a crear un usuario, en este modelo se guardan todos los datos personales """ DEPENDENCIES_CHOICES = ( ("1", "Rectorado - Gabinete"), ("2", "Vice Rectorado"), ("3", "Rectorado - Secretaria … -
How to Implement Conditional Filter in Django Query set
I am writing a queryset in which I am in need to check the value that exists in the table or not but here is a twist. example: if a value is: "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" which I am getting in request and like this lots of values are stored in the table. but the checking is like out of these 4 values (after split from comma we will get 4 values ) if any 3 or more than 3 gets matched with any of the records in the table then this queryset will return that complete string value from the table to which it matches. key_in_request = "12345, ABVC43F, T5T5YUH/KJUTG678, 1234567890PO-QWERT4567-OIUYT8765-POIUY7890" req_key_array = key_in_request.split(',') for getting more clarity i have a example of sql query for what i need but unable to write queryset: SQL query is here: select if((key_value is having req_key_array[0]), 1, 0) + if((key_value is having req_key_array[1]), 1, 0) as Result; here it will sum then all the 1 and 0 if conditions will be false or true, it's not a exact query but near to that. It's my first try to post question hope you will understand, if any issue please comment. -
How to test if a function gets called when another function executes in django test?
I've a method inside a manager, this method calls a function imported from different module now I'm trying to write a test that make sure the function gets called, when the manager method executes. I've tried some methods by it didn't work here is the code example. hint: I'm using pytest as testrunner from unittest import mock # Customer Manager class class ItemsManager(models.Manager): def bulk_update(self, *args, **kwargs): result = super().bulk_update(*args, **kwargs) items_bulk_updated(*args, **kwargs) return result # signals.py file def items_bulk_updated(*args, **kwargs): print("items bulk updated") # test file # Base TestCase Inherits from APITestCase class TestItems(BaseTestCase): @mock.patch("items.signals.items_bulk_updated",autospec=True) def test_bulk_update_items_triggers_signal(self, mock_function): items_qs = Items.objects.all() result = Items.objects.bulk_update(items_qs, ['item_name']) mock_function.assert_called() -
django gives me error 404 when i try to use unicode urls
there is a problem when django uses Arabic slugs . It can accepts them . But when you go for its url . It can't find a matching query in database for them . It gives me 404 . this is the urls.py and my url : re_path(r'detail/(?P<slug>[\w-]+)/$' , detail_course , name='detail_courses') and its the url that i try to enter : http://127.0.0.1:8000/course/detail/%D8%AA%D8%AD%D9%84%DB%8C%D9%84_%D8%A8%DB%8C%D8%AA_%DA%A9%D9%88%DB%8C%D9%86/ what is its problem ? -
Django Rest Framework : RetrieveUpdateAPIView
I want to add multiple data to database with RetrieveUpdateAPIView and I am not able to add that data in database. How can I update this all date in single Patch method. My view is like class CompanyDetailViewAPI(RetrieveUpdateAPIView): queryset = Companies.objects.all() serializer_class = CompanyDetailsSerializer permission_classes = [IsAuthenticated] authentication_classes = [JWTAuthentication] lookup_field = "id" and my serializer is like class KeyPersonsSerializer(serializers.ModelSerializer): class Meta: model = KeyPersons fields = [ "id", "person_name", "designation", "email", "contact_number", ] class CompanyDetailsSerializer(serializers.ModelSerializer): key_person = KeyPersonsSerializer(many=True) class Meta: model = Companies fields = [ "id", "address_line_1", "address_line_2", "city", "landmark", "state", "country", "pincode", "website", "person_name", "designation", "email", "phone", "ho_email", "ho_contact_number", "company_registration_no", "gst_no", "key_person", "company_corporate_presentation", "about_company", "company_established_date", "no_of_facilities", "no_of_employees", ] I have tried this but I cant see any result. How can I update this all date in single Patch method -
Convert datetime object to string in annotate in Python(Django)
I have a queryset like: qs = MyModel.objects.filter(name='me').values_list('activation_date') here activation_date is DateTimeField in models. How can I convert this field('activation_date') in string? I am getting error like: 'datetime object not JSON serializable' -
How to count model ForeingKeys instances per row in a template table?
I want to count how many "plans" does a "client" have per table row in my template, there's a bit of the code urls.py>>> urlpatterns = [ path('clients/', views.indexClient, name='clients'),] models.py class Plan (models.Model): name = models.CharField(max_length=100, unique=True) client = models.ForeignKey('Client', on_delete=models.RESTRICT) gp_code = models.CharField(max_length=13, primary_key=True) dispatch_conditions = models.TextField() elaboration = models.CharField(max_length=100) reviewer = models.CharField(max_length=100) def __str__(self): return self.product ------------------------------------------------------------------------------------ class Client (models.Model): name = models.CharField(max_length=100, unique=True) rif_num = models.CharField(max_length=10, primary_key=True) def __str__(self): return self.name views.py from django.db.models import Count from .models import * def indexClient(request): client_list = Client.objects.all() plans = Client.objects.annotate(num_plan = Count('plan')) template = loader.get_template('app/clients.html') context={'client_list':client_list, 'plans':plans} return HttpResponse(template.render(context, request)) template clients.html <table> <thead> <tr> <th>Client</th> <th >Plans</th> </tr> </thead> <tbody> {% for client in client_list %} <tr> <td>{{ client.name }}</td> <td>{{ plans.num_plan }}</td> </tr> {% endfor %} </tbody> </table> i tried to apply the methods said in this, this and this question but it didn't work for me or i'm applying the Count() incorrectly want the table to display just like... Client Plans Jhon 2 Mark 4 Louis 0 Vic 1 but currently the 'Plans' displays blank like this... Client Plans Jhon Mark Louis Vic -
How to access Foreign Key models attribute values into another model in Django?
I am trying to filter choices of models attribute based on its foreign key models attribute. parent_choices = [('fruits', 'fruits'), ('veggie', 'veggie')] dict_options = { 'fruits': [('apple', 'apple'), ('orange', 'orange')], 'veggie': [('carrot', 'carrot'), ('peas', 'peas')], } class Parent(models.Model): name = models.CharField(max_length=50) like_to_eat = models.CharField(max_length=20, choices=parent_choices) class Child(models.Model): name = models.CharField(max_length=50) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) given_to_eat = models.CharField(max_length=20, choices=dict_options[parent.like_to_eat]) Error Message: AttributeError: 'ForeignKey' object has no attribute 'like_to_eat' -
(-2147024891, 'Access is denied.', None, None)
I am developing a Django (v 3.2.6) application (Python 3.9.1.) which needs to write into an Excel file using pywin32.com. On the client side it works fine, but when I put in production using IIS (v 10) on a Windows 11 server, I get the error above. I have a routine that reads in a file input by the user and writes to the project directory: if request.method == 'POST': # Create a form instance and populate it with the file from the request (binding): form = Name1_uploadForm(request.POST, request.FILES) if form.is_valid(): # Create variable for uploaded file uploaded_excel_file = form.cleaned_data['excel_file'] # Write it to BASE_DIR with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination: for chunk in uploaded_excel_file.chunks(): destination.write(chunk) # Allow the write process to conclude time.sleep(12) # Close the file destination.close() # Call conversion function Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name)) # redirect to a new URL: return HttpResponseRedirect(reverse('index') ) else: form = Name1_uploadForm() This calls another function (below) that should open that same file: def Name1_extraction(uploaded_excel_file): const = win32.constants # Need to run CoInitialize to use win32com.client pythoncom.CoInitialize() # Open Name1 excel with Win32com excelFile = win32.gencache.EnsureDispatch('Excel.Application') The complete error is the following: enter image description here enter image description here enter image description here … -
I want to deploy django app on AWS EC2 using docker container with nginx, gunicorn. 502 Gateway error is happening [closed]
I make a docker container for Django-app. I tested it on my local host, and everything is working fine. I want to implement it on the AWS Linux server(EC2). Docker-compose-up is running successfully, but a 502 gateway error happens. Last time i had the same issue, but there was no docker container and i find out the problem was in nginix config. I added user "mylinuxname"; and it was working. Now i don't know how to update that config file, because i'm using container and when i add user "mylinuxusername" it is not working. output : "it is not place where u can use user settings". Anyone can help me or give me any references.enter image description hereenter image description here[enter image description here](https://i.stack.imgur.com/6S9ow.png) -
(Django) Why my login only work for db table:auth_user can't work another table:myapp_user?
Sorry bad English! I have a login function in my project like: from django.contrib.auth.forms import AuthenticationForm from django.contrib import auth from django.http import HttpResponseRedirect from django.shortcuts import render def log_in(request): form = AuthenticationForm(request.POST) if request.method == "POST": form = AuthenticationForm(data=request.POST) username = request.POST.get('username') password = request.POST.get('password') user = auth.authenticate(request,username=username,password=password) if user is not None and user.is_active: auth.login(request,user) return HttpResponseRedirect('/index') context = { 'form': form, } return render(request, 'login.html', context) This function can work for any accounts that save in database table:auth_user,but can't work for my define class User: from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class User(AbstractBaseUser): username = models.CharField(unique=True,max_length=20,default="") email = models.EmailField() date_of_birth = models.DateField() date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = AccountManager() USERNAME_FIELD = 'username' #類似主鍵的功用 REQUIRED_FIELDS = ['email','username'] #必填 def __str__(self): return self.email def is_staff(self): return self.is_admin def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin If I use register page to create a new account data,it will save in table:function_user("function" is my app name),and if my login table:auth_user accounts it will jump to /index,this right,but when I login new register account,it not do anything , I really sure the username and password is already created in table:function_user. … -
Django slice variable in template
I am trying to cut a slice a list of images to split them over a few pages of a pdf I am generating. But im not sure what the syntax I need to use is. (or if there is a better way). {% for page in image_pages %} // range loop for number of pages (passed from view) <p style="page-break-before: always"></p> // new page break for each page <div class="img-wrapper"> {% for image in project_images|slice:"0:12" %} <div class="img-box" style="margin: 5px"> <img class="report-img" src="{{ base_url }}{{ image.path.url }}" /> </div> {% endfor %} </div> {% endfor %} What i want to do is adjust this line {% for image in project_images|slice:"0:12" %} To something like (to print 12 images from total image list sent) {% for image in project_images|slice:"page*12:page*12+12" %} -
Continuous deployment of django react project
I have a react app with django backend. Every time when I need to deploy the app I have to follow following steps - Git pull new django code Copy react build from local to aws Collect static files using python manage.py collectstatic I have to automate this process using bare minimum dependencies. What can be done in such case? Thanks in Advance. -
How to use AdminEmailHandler class to send mails to admins with celery task in django?
I'm trying to send a mails to admins with celery by overriding the current AdminEmailHandler class of django from django.utils.log import AdminEmailHandler from celery import shared_task class CeleryAdminEmailHanadler(AdminEmailHandler): @shared_task(bind=True) def celery_send(self,subject, message, *args, **kwargs): super().send_mail(subject, message, *args, **kwargs) def send_mail(self, subject, message, *args, **kwargs): self.celery_send.delay(subject, message, *args, **kwargs) whenever celery_send function run the super().send_mail function getting this error Error('super(type, obj): obj must be an instance or subtype of type') Traceback (most recent call last): File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "D:\cmms\env\lib\site-packages\celery\app\trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "D:\cmms\core\utils\log.py", line 7, in celery_send super().send_mail(subject, message, *args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type I'm using this for logging purposes to send mail to admins on critical errors in the website with celery. -
How to get value by index in jinja2 list?
I am using plotly to make multiple graphs and django framework to present the graph to user. I am storing all the graphs in list, example: all_graphs=[graph1, graph2] I need to show only one graph at a time according to value selected in dropdown in HTML. I am using javascript and jinja2 element for the same. Below is my javascript code: ` function graphshow(s){ var id=Number(s[s.selectedIndex].id); var graph1 = {{ all_graphs.0 | safe}}; Plotly.plot('id_of_div_to_show_graph', graph1, {}); } ` The above code works perfectly but when i replace 0 in line 2 with 'id' which is the index value of graph to be shown the code doesn't work. The value stored in 'id' is correct i've already checked. -
Django using URL parameters in template
I need to redirect to another page with same url parameters so I don't understand how to use url parameters in current template to redirect. dborg.html: {% extends './frame.html' %} {% block content %} <a href="{% url 'create_user' {{orgtype}} {{deg}} %}">Создать нового пользователя</a> {% csrf_token %} {{form}} {% for i in o %} <p><a href='{% url "view_user" i.id %}'>{{i.fld}}</a></p> {% endfor %} {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path('', views.main, name='main'), path('view_org/<str:orgtype>/<str:deg>', views.view_org_db, name='view_org'), path('token/<str:orgtype>/<str:deg>', views.get_token, name='token'), path('token/<str:orgtype>', views.get_token, name='token'), path('create/<str:orgtype>/<str:deg>', views.create_user, name='create_user'), path('search/', views.search_user, name='search_user'), path('report/', views.view_report, name='view_report'), path('view/<int:id>', views.view_user, name='view_user') ] -
How do I get a cloned Django project running?
When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully I tried python 'python3 -m pip install -U setuptools' but that didn't work. -
Django issue saving data to database
username is saving but information such as first_name, email and etc are not. `from django.contrib.auth.models import User from django.contrib.auth.password_validation import validate_password from rest_framework import serializers class RegisterSerializer(serializers.ModelSerializer): email = serializers.CharField(required=True) first_name = serializers.CharField(max_length=50, required=True) last_name = serializers.CharField(max_length=50, required=True) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) is_admin = serializers.BooleanField(default=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'password2', 'is_admin') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user` i have searched online for hours, but have not managed to make much progress. if someone could elaborate on my issue and explain what I have done wrong that would be greatly appreciated -
Django - write Python code in an elegant way
I have a situation as shown below: in models.py: class singer(models.Model): name = models.CharField() nickName = models.CharField() numSongs= models.IntegerField() class writer(models.Model): name = models.CharField() numBooks = models.IntegerField() class weeklyTimeSinger(models.Model): singerID = models.ForeignKey(singer, on_delete = models.CASCADE, related_name = 'hook1') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() class weeklyTimeWriter(models.Model): writerID = models.ForeignKey(writer, on_delete = models.CASCADE, related_name = 'hook2') dayWeek = models.IntegerField() startHour = models.TimeField() stopHour = models.TimeField() in view.py: class Filters(APIView): def queryFilter(self, querySet, request, singerOtWriter): param1 = int(request.GET.get('param1', 0)) param2 = int(request.GET.get('param2', 0)) if singerOtWriter == "singer": querySet = querySet.filter(weeklyTimeSinger_dayWeek=param1) querySet = querySet.filter(weeklyTimeSinger_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet else if singerOtWriter == "writer": querySet = querySet.filter(weeklyTimeWriter_dayWeek=param1) querySet = querySet.filter(weeklyTimeWriter_startHour__lt=param2) querySet = querySet.update(..... ....a lot of operation on querySet, the same of the case singer return querySet class Artist(Filters): def get(self, request): querySetSinger = singer.objects.all().annotate(numWorks= F('numSongs')) querySetSinger = self.queryFilter(querySetSinger , request, "singer") querySetSinger = querySetSinger.values('name', 'numWorks') querySetWriter = writer.objects.all().annotate(numWorks= F('numBooks')) querySetWriter = self.queryFilter(querySetWriter , request, "writer") querySetWriter = querySetWriter.values('name', 'numWorks') values = querySetSinger.union(querySetWriter) serialized = ArtistSerializers(values, many = True) return Response(serialized.data) In queryFilter function I have 2 different flows depending on singerOtWriter parameter. The 2 flows are long and identical execpt for "weeklyTimeWriter" or "weeklyTimeSinger" tables … -
Django complexity of one-to-one field reverse lookup
Reverse lookup of foreign key fields takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
Duplicate object with django-hitcount
I want to duplicate my current object with its values. So, I need to copy all of its old values to the new object. Duplication of all old values I implemented well, but I can't make hits (views) that are created with django-hitcount. I tried to do different options, but it doesn't work. Could you please give me advice on how to build it? models.py class Blog(models.Model, HitCountMixin): slug = models.SlugField() name = models.CharField() author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, blank=True, ) content = models.TextField(blank=True, null=True) bookmarkscount = models.IntegerField(null=True, blank=True, default=0) downloadscount = models.IntegerField(null=True, blank=True, default=0) hit_count_generic = GenericRelation( HitCount, object_id_field="object_pk", related_query_name="hit_count_generic_relation", ) hitcount.models.py from datetime import timedelta from django.db import models from django.conf import settings from django.db.models import F from django.utils import timezone from django.dispatch import receiver from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext_lazy as _ from etc.toolbox import get_model_class_from_string AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') from .managers import HitCountManager, HitManager from .settings import MODEL_HITCOUNT from .signals import delete_hit_count @receiver(delete_hit_count) def delete_hit_count_handler(sender, instance, save_hitcount=False, **kwargs): """ Custom callback for the Hit.delete() method. Hit.delete(): removes the hit from the associated HitCount object. Hit.delete(save_hitcount=True): preserves the hit for the associated HitCount object. """ if not save_hitcount: instance.hitcount.decrease() … -
Missing 'path' argument in get() call
I am trying to test my views in Django, and when I run this i get the error from django.test import TestCase, Client from django.urls import reverse from foodsystem_app.models import discount,menu import json class TestViews(TestCase): def test_login_GET(self): client = Client response = client.get(reverse('login')) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response,'foodsystem/login.html') response = client.get(reverse('login')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Client.get() missing 1 required positional argument: 'path' ---------------------------------------------------------------------- Ran 4 tests in 0.005s FAILED (errors=1) I'm not sure what I am supposed to pass as the path name. This is the code for what I am testing def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("main:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) -
Getting (2006, 'MySQL server has gone away error) in kafka consumer in my django application
I recently written a kafka consumer in my django project which is running in the background and there's a mysql query which reads inside the consumer and the process is very light as I don't have that much of data. But I'm getting (2006, 'MySQL server has gone away) and I'm not getting why exactly it's happening and what's the solution for this? Any leads or solution for this would be highly appreciated. The below is my code:- `def job_listener(): listener = KafkaConsumer(topic, group_id=group_id, bootstrap_servers=settings.KAFKA_BOOTSTRAP_SERVERS, auto_offset_reset=settings.KAFKA_AUTO_OFFSET_RESET, enable_auto_commit=settings.KAFKA_ENABLE_AUTO_COMMIT) for message in listener: try: data = json.loads(message.value) logger.info("Data Received {}".format(data)) except Exception as e: data = None logger.error("Failed to parse the message with exception {}".format(e)) if data is not None: try: Job.objects.get(pk=data['id'] except ObjectDoesNotExist: logger.error("Keyword doesn't exist with data {}".format(data)) listener.commit({TopicPartition(topic, message.partition): OffsetAndMetadata(message.offset+1, '')}) except Exception as e: logger.error( "Failed to read data {} with exception {}".format(data, e)) listener.seek(TopicPartition(topic, message.partition), message.offset)` -
how to pass a context variable from a variable inside of an if statement?
Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement? View if request.method == "POST": if request.user.is_authenticated: customer = request.user.customer check_order = OrderItem.objects.filter(order__customer=customer) if check_order: if form.is_valid(): #does logic else: messages.error(request, f"Failed") else: return redirect() context = {"check_order": check_order}