Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Twilio REST Exception HTTP 429 error: Unable to create record: Too many requests
I have created an app in Django. Using Twilio Verify API (free trial) for OTP. Problem:- It's working fine but when a user try to get the OTP multiple times, Twilio creates an exception "HTTP 429 error: Unable to create record: Too many requests". After this I was not able to use this for the whole day even for different mobile number or device. How to bypass this issue and precisely what is the reason behind this issue? -
get() returned more than one Model -- it returned 4! - but only 1 Model in db
In a Django view, I'm getting a MultipleObjectsReturned error using a get_or_create. Many questions have been asked about this, but those people seem to be using this construct wrongly. I think that I'm using it correctly, but please correct me if I'm wrong. I have the following model: class MyModel(models.Model): field1 = models.ForeignKey('app.OtherModel', on_delete=models.SET_NULL, null=True) field2 = models.CharField(max_length=50, blank=True, null=True) field3 = models.JSONField() field4 = models.JSONField() updated = models.DateTimeField(_('Date updated'), auto_now=True) created = models.DateTimeField(_('Date created'), default=timezone.now) ... class Meta: ordering = ('-created',) constraints = [ models.UniqueConstraint(fields=['field1', 'field2'], name='unique_model'), ] And this code in my view: o, created = MyModel.objects.get_or_create(field1=value1, field2='value2', defaults={'field3': '...', 'field4': '...'}) So the get is performed on the two fields that are in the UniqueConstraint, the other fields are listed in the defaults part (in case the create is required). The MultipleObjectsReturned is thrown on that last line, when Django performs the get part of the get_or_create, but only in some rare cases - most of the time this construct works well. The view is actually a handler for AWS's SNS event messages for SES, handling delivery delays, bounces and complaints. In theory it should not happen that this view is called exactly twice, causing a race-condition. … -
django csrf_token verification with python requests module
I want to send post request using python requests module. Since, I use Django for backend server. So, I need verify csrf_token for post method. I know that i have option to stop csrf_token verification using Django built in decorators. But, i don't want to do that for cross site protection. My Django Sample Code: from django.http import HttpResponse from django.middleware.csrf import get_token def pv(v, s): print(f"----------Value of {s}-------") print(f"Type= {type(v)}") print() print(v) print() def index(request): pv(request.COOKIES,"HttpRequest.COOKIES") pv(request.headers,"HttpRequest.headers") token = get_token(request) # I think, Here have some worng. But What? return HttpResponse("Hello World") index() is work for both get and post reequest. Though i don't use redirect() for post method in sample code. Here is my get and post request code using python requests module: import requests import time def pv(obj, s): print(f"-----Value of {s} --------") print(type(obj)) print(obj) print() url = "http://192.168.0.102:8000/home/" data = {"a":"5", "b":4} d = requests.get(url) time.sleep(2) requests.post(url, cookies=d.cookies, data=data) # For Test pv(d.headers, "d.headers") pv(d.cookies['csrftoken'], "d.cookies") get request work properly and return me csrf_token.when i use this toke with post method. Django server give me Forbidden (CSRF token missing or incorrect.): /home/ error and post request doesn't work properly. How can i verify csrf_token? -
Django Model Use Text Choices From Another Model
In my Django model, I want to use the text choices from another model, but I don't want to use it as a foreign key, because I want the whole list of weekdays before any Day object exists. If I use it as a foreign key, I will need to create Day object first. Can anyone help to solve this? class Day(models.Model): class Weekdays(models.TextChoices): MONDAY = "Monday" TUESDAY = "Tuesday" WEDNESDAY = "Wednesday" THURSDAY = "Thursday" FRIDAY = "Friday" SATURDAY = "Saturday" SUNDAY = "Sunday" store = models.ForeignKey(Store, on_delete=models.DO_NOTHING) weekday = models.CharField(max_length=9, choices=Weekdays.choices) class School(models.Model): weekday = ??? -
Django - Altering list view based on link that is pressed
I have a navbar above my products on my fake e commerce website that I am building. I render this view through list view. In this navbar I have a search area that works fine, and want to add the ability to filter the results based on what is pressed. For example, I have styles: realism, portrait, etc in the navbar. When I click on realism I want the results to change to all realism paintings that are in the DB. My question is what would be the best way to accomplish this? Could I alter the original list view? Or would I just need to create an entirely new view based on the specific queries I need? Any help is greatly appreciated! Also attached will be a picture to show you what I mean in case my explanation wasn't the best. view: class AllProductView(ListView): template_name = 'my_site/all_products.html' model = Product ordering=['id'] paginate_by = 9 context_object_name = 'products' -
Django / Docker, manage a million images and many large files
The project I am working on relies on many static files. I am looking for guidance on how to deal with the situation. First I will explain the situation, then I will ask my questions. The Situation The files that need management: Roughly 1.5 million .bmp images, about 100 GB Roughly 100 .h5 files, 250 MB each, about 25 GB bmp files The images are part of an image library, the user can filter trough them based on multiple different kinds of meta data. The meta data is spread out over multiple Models such as: Printer, PaperType, and Source. In development the images sit in the static folder of the Django project, this works fine for now. h5 files Each app has its own set of .h5 files. They are used to inspect user generated images. Results of this inspection are stored in the database, the image itself is stored on disc. Moving to production Now that you know a bit about the problem it is time to ask my questions. Please note that I have never pushed a Django project to production before. I am also new to Docker. Docker The project needs to be deployed on multiple machines, … -
Django inline AdminSite with intermediate model that has relationship
I'm having the following Django models (irrelevant fields were removed): class View(models.Model): pass class PropertyVersion(models.Model): pass class EntityVersion(models.Model): properties = models.ManyToManyField(PropertyVersion, through='EntityVersionProperties') class EntityVersionProperties(models.Model): entity_version = models.ForeignKey(EntityVersion, on_delete=models.CASCADE) property_version = models.ForeignKey(PropertyVersion, on_delete=models.CASCADE) views = models.ManyToManyField(View, blank=True) The funny thing is that the intermediate model EntityVersionProperties has a relation to View. If I display the intermediate model in an own admin site, everything is fine and I can choose to not provide a value for views, following the blank=True definition. AdminSite for that has no explicit config: @admin.register(EntityVersionProperties) class EntityVersionPropertiesAdmin(admin.ModelAdmin): pass The thing is that I now want to display the EntityVersionProperties as admin inline of EntityVersion. It is displayed correctly, but I cannot save the EntityVersion as this marks every EntityVersionProperties where no element for View/EntityVersionProperties.views is selected with This field is required.. Why does that happen? How does it validate the inline elements actually? Admin site for EntityVersionProperties: class EntityVersionPropertiesInline(admin.TabularInline): model = EntityVersionProperties @admin.register(EntityVersion) class EntityVersionAdmin(admin.ModelAdmin): inlines = [EntityVersionPropertiesInline] Using Django 3.2.4 with SQLite. -
Django TemplateDoesNotExist when generating URL
I want to have my URL to change based on the results displayed. For example, I want the URL to be .../profile_detail/1, but it always returns: NoReverseMatch at /search/ Reverse for 'profile_detail' with arguments '(UUID('f3ef1f95-f374-4ac4-b1aa-b5db5fd76af7'),)' not found. 1 pattern(s) tried: ['profile_detail/(?P<profile_id>[0-9]+)/$'] views.py def profile_detail(request, profile_id): user = get_object_or_404(CustomUser, pk=profile_id) return render(request, 'network/profile_detail.html', {'user': user}) models.py class CustomUser(AbstractUser): username = None uniqueID = models.UUIDField(max_length=20, default=uuid.uuid4) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_("first name"), max_length=100) last_name = models.CharField(_("last name"), max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [first_name, last_name] objects = CustomUserManager() def __str__(self): return self.email class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") date_of_birth = models.DateField(blank=True, null=True) image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) def save(self, *args, **kwargs): # Opening the uploaded image try: im = Image.open(self.image) output = BytesIO() # Resize/modify the image and convert to RGB from RGBA im = im.convert('RGB') im = im.resize((300, 300)) # after modifications, save it to the output im.save(output, format='JPEG', quality=90) output.seek(0) # change the imagefield value to be the newly modified image value self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None) except: pass super(Profile, self).save() urls.py from django.urls import path from . import views from .views import SearchResultsView urlpatterns = [ path('feed', views.home, name="home"), path('', views.landing, … -
How to serialize incoming string array?
While working on a pet project, I ran into a problem. I have a post request with foreward data: { "name": "Name", "description": "Description", "questions": [ { "question": "question", "multiple": true, "variants": [ { "variant": "cloudy" }, { "variant": "cold" } ], "answer": ["cloudy","cold"] } ] } After saving the data to the database, when receiving this data, the answer field looks like this "answer": [ "[", "'", "c", "l", "o", "u", "d", "y", "'", ",", " ", "'", "c", "o", "l", "d", "'", "]" ], Why is this happening and how can I fix it? I have the following setup in Django REST Framework: models.py class Quiz(models.Model): name = models.CharField(max_length=250) description = models.TextField() date_created = models.DateTimeField(auto_now=True, db_index=True) class Question(models.Model): quiz = models.ForeignKey(Quiz, related_name='questions', on_delete=models.CASCADE) question = models.CharField(max_length=250) multiple = models.BooleanField(default=False) answer = models.CharField(max_length=30, default='') class Variant(models.Model): question = models.ForeignKey(Question, related_name='variants', on_delete=models.CASCADE, db_index=True) variant = models.CharField(max_length=30) serializers.py class VariantSerializer(serializers.ModelSerializer): class Meta: model = Variant fields = ['id', 'variant'] class QuestionSerializer(serializers.ModelSerializer): variants = VariantSerializer(many=True) answer = serializers.ListSerializer(child=serializers.CharField()) class Meta: model = Question fields = ['id', 'question', 'variants', 'answer', 'multiple'] class QuizSerializer(serializers.ModelSerializer): questions = QuestionSerializer(many=True) class Meta: model = Quiz fields = ['id', 'name', 'description', 'questions'] def create(self, validated_data): questions_data = validated_data.pop('questions') … -
Python: How to join an operator?
I'm currently developing a Django application with i18n support. This works by providing a field for each language for a given field. Example model: class Article(models.Model): title_en = models.CharField() title_de = models.CharField() title_fr = models.CharField() # etc... (under the hood this is automatically done using django-translated-fields) I would now like to filter for Articles with a given title. The title should be checked in every available language. (so in this case title_en, title_de and title_fr). If there was only one title, I could query like this: Article.objects.filter(title=my_title) I don't want to use this: Article.objects.filter(Q(title_en=my_title) | Q(title_de=my_title) | Q(title_fr=my_title)) since the fields are created dynamically and the available languages could change. My question I need to somehow join classes using the __or__ operator. I came up with this: Article.objects.filter(*[ Q(**{ f"name_{code}": my_name }) for code in available_languages ]) but the joining is missing. Is there any method to do this? Or is there a better method available to filter for the names? -
how to make thunk HTTP POST request to Django rest api
I'm pretty new to this, so I will show you the error first and then display my thought process. I am attempting to use a thunk (Http request in redux) to make a post request to my personal rest api in django. (so it can run cURL commands and use a authorization code to gain an access token and get user data from an API) when I make this request, the network returns a 201 status to stay it worked, while my console logs the dispatch as rejected, and gives the error, "message: "Unexpected end of JSON input". In this message, payload is undefined, and my payload is living in meta under arg. After much reserach, it looks like I either need to JSON.strigify something on my front end, OR that django is receiving a null object and not knowing what to do with it. I believe it is the latter, and not sure how to proceed. Here is my code: FRONTEND: slice.py import {createAsyncThunk} from '@reduxjs/toolkit' export const postRequest= createAsyncThunk('slice/postRequest', async postData => { const response= await client.post('url', {slice:postData}) return response.slice } ) component.py import {useDispatch} from 'react-redux' import {postRequest} from './slice' const Component = () => { const … -
Django DetailView - display boolean from models as checkboxes
There's a number of snippets to display booleans in Django Forms as checkboxes (i.e. specifying Checkbox as a widget). For instance (assuming a boolean field defined in the model for bar): class FooForm(forms.ModelForm): class Meta: model = Foo fields = ['bar'] widgets = { 'bar' : CheckboxInput(attrs={'class': 'required checkbox form-control'}), } However I also need to display a (disabled) checkbox in DetailView (client says so). But I can't figure out an elegant way to do this, since I don't have a form meta for details view... My current thinking is something like this (bootstrap checkbox): <div class="form-check"> <label class="form-check-label"> <input type="checkbox" {% if foo.bar %}checked{% endif %} disabled>Bar </label> <\div> Any way to accomplish this in a fashion closer to the Form's widgets? -
I am getting ERROR: AttributeError at /customer/5/ type object 'Customer' has no attribute 'orderitem_set'
Please help me I stuck at this problem. When Click on the view button I want to show all the orders from that user as shown in the image below, but when i click on it I am getting this error instead of order details for that customer. The models file contains models.py class Customer(models.Model): user = models.OneToOneField( User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length= 200, null = True) email = models.CharField(max_length=100) def __str__(self): return self.name class Order(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=True) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.customer) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey( Product, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=False) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product.name @property def get_total(self): total = self.product.price * self.quantity return total The views.py file contains Views.py … -
Django filter by field on a relationship
How can I replicate this query with Django's ORM? SELECT * FROM commit INNER JOIN object on commit.object_id = object.id WHERE commit.created_at = object.created_at; My models: class Object(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) created_at = models.DateTimeField(default=timezone.now) class Commit(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) object = models.ForeignKey(Object, null=True, blank=True, related_name="commits") created_at = models.DateTimeField(default=timezone.now) -
Django Model field to populate another field
I'm back again, I've been on this for more than 48 hours, still couldn't find a response to this. I have this model. The Position table has Site Engineer, Site Manager, HVAC Engineer, etc Engineers have only one position each, and I want the manager field to be populated only if the Engineer created has a position Site Manager. If an Engineer is created, the manager field will be a dropdown list of Engineers who have the Site Manager position. from django.db import models class Position(models.Model): name = models.CharField(max_length=100, default='Site Engineer') def __str__(self): return self.name class Engineers(models.Model): region = ( ('SS', 'South-South'), ('SW', 'South-West'), ('SE', 'South-East'), ('NE', 'North-East'), ('NW', 'North-West'), ('NC', 'North-Central'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20, default='Leave Blank', unique=True) phone = models.CharField(max_length=11) position = models.ForeignKey(Position, on_delete=models.DO_NOTHING) workarea = models.CharField(max_length=20, choices=region) manager = models.CharField(verbose_name='Site Manager', max_length=80, default=None) def save(self, *args, **kwargs): self.username = self.firstname +'.'+self.lastname self.manager = self.firstname +' '+self.lastname super(Engineers, self).save(*args, **kwargs) def __str__(self): return self.firstname + ' ' + self.lastname This code only fills the manager field with the name of the Engineers, even if they are not Site Managers. Please help -
Django REST API set allowed hosts for individual endpoints
I would like to have different values for ALLOWED_HOSTS for different Django REST API endpoints. Is this possible? Here are more details: I have a setup consisting of a Django REST API backend, a React frontend, a Postgresdb and nginx, each running in a docker container, managed by docker compose. I am exposing Django API endpoints that are accessed by the frontend from the user's browser, so I am adding the domain of the frontend to allowed hosts. However, I have one specific API endpoint that should only accept requests from the frontend docker container but never accept requests from outside. It should only be used for communication between the frontend and the backend container. So in this case i would have to restrict allowed hosts to the ip of the docker container. Both settings are possible and working, but I can only choose one of both in the global Django settings. My question is: Is it possible to set allowed hosts for an individual endpoint/url? -
How to serve form to multiple Django views
I have a Django form in a modal which needs to be included in many pages across my website. I've read and re-red all similar issues on StackO and been through the documentation but still have questions as to the best way to achieve this. So: I want to put a subscribe modal on many pages. I want a single view to handle the form submission. The form has pre-filled fields so I need to put some things into the context of the view, which sounds like a middleware thing, but I'm not sure. I've created a class-based view which serves the form to some of the urls like the first two listed here ('about' and 'faq'): urls.py url(r'^about/$', views.SubscribeFormView.as_view(template_name='about.html'), name='about'), path('faq/', views.SubscribeFormView.as_view(template_name='faq.html'), name='faq') views.py class SubscribeFormView(View): form_class = forms.SubscribeForm template_name = 'modals/subscribe-modal.html' 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) form_error = False if form.is_valid(): ... return redirect('{}?{}'.format( reverse('site_subscribe', args=[site.id]), urlencode({ 'duration': request.POST.get('duration', ''), }) )) else: form_error = True context = { 'form': form, 'form_error': form_error } ... return render(request, self.template_name, context) However I run into a problem with how to get this view to … -
Django: Certain users get random 404 error
I'm facing a strange issue that I can't handle on my own. In normal cases when users click on a link, then they are directed to a page where they can edit their hook baits (objects). However, certain users get 404 errors, but I don't know why because the page is rendered for most users. html where the link is <div class="row justify-content-center mx-2" > <div class="col-12 p-0"> <ul class="list-group text-center custom-borders m-2 p-0"> {% if own_hookbaits.count == 0 %} <a href="{% url 'user_profile:hookbaits' request.user.fisherman.fisherman_id %}" class="list-group-item" >No hook baits yet</a> {% else %} {% for hookbait in own_hookbaits %} <a href="{% url 'user_profile:hookbaits' request.user.fisherman.fisherman_id %}" class="list-group-item">{{ hookbait.name }}</a> {% endfor %} {% endif %} </ul> </div> views.py class HookBaitUpdateView(UpdateView): model = HookBait template_name = "user_profile/hookbaits.html" form_class = HookBaitForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = HookBaitFormset(queryset=HookBait.objects.filter(fisherman=self.request.user.fisherman)) return context def post(self, request, *args, **kwargs): formset = HookBaitFormset(request.POST) if formset.is_valid(): return self.form_valid(formset) else: return self.form_invalid(formset) def form_valid(self, formset): instances = formset.save(commit=False) for instance in instances: instance.fisherman = self.request.user.fisherman instance.save() return super().form_valid(formset) def form_invalid(self, formset): return HttpResponse("Invalid") def get_success_url(self): return reverse('user_profile:profile', args=(self.kwargs['pk'],)) urls.py app_name = "user_profile" urlpatterns = [ path("profile/<int:pk>/", views.ProfileView.as_view(), name="profile"), path("profile/<int:pk>/hookbaits/", views.HookBaitUpdateView.as_view(), name="hookbaits"), ] rendered html <div class="row justify-content-center … -
ERROR: null value in column "fname" of relation "app_form" violates not-null constraint
select * from PUBLIC.app_form COPY PUBLIC.app_form(pincode, district) FROM 'C:\Users\HP\Desktop\pincode2.csv' DELIMITER ',' CSV HEADER; ERROR: null value in column "fname" of relation "app_form" violates not-null constraint DETAIL: Failing row contains (6, null, null, Wayanad, 673575). CONTEXT: COPY app_form, line 2: "673575,Wayanad" SQL state: 23502 -
Django,Docker - Cannot use ImageField because Pillow is not installed
I`m trying deploy the Django project for productions.I use Postgres, Nginx and Gunicorn. In a Docker container I have installed package Pillow==8.3.1 (I also tried version 8.3.0). In Dockerfile I have dependencies: RUN apk update \ && apk add postgresql-dev gcc python3-dev musl-dev jpeg-dev zlib-dev libjpeg RUN pip install --upgrade pip COPY . . COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt when I execute the migrate command: docker-compose exec web python3 manage.py migrate Shows me errors: SystemCheckError: System check identified some issues: ERRORS: poszukiwania.Rzeczy.image_obverse: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". poszukiwania.Rzeczy.image_reverse: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". Any suggestions on how to fix this? -
Is there a way to do more coding/refresh screen after a return FileResponse in django?
I've created a pdf successfully, code roughly: .......blah blah ..... c.setFont('Arial', 55) c.drawString(140, 160, '30 DAYS') c.setFont('Arial', 38) c.drawString(110, 260, 'Terms of Payment') c.showPage() c.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') messages.success(request, f'Thank you file in download folder!') return HttpResponseRedirect(request.META.get('HTTP_REFERER')) i would like to include the message and reload after the fileresponse is there a way of doing this? as the last two lines of code are ignored -
How to fix "exit status 1 " error when deploying on digital ocean
I'm trying to deploy a django website on digital ocean. I was able to clone my project from GitHub to droplet on digital ocean. This web project I cloned has requirements.txt file. When I ran the command pip install -r requirements.txt in other to install all the packages in my project, the packages installed halfway and threw back an error message ERROR: Command errored out with exit status 1 as found in the the attached photograph. Also, I used MySQL locally but I want to use postgrel on live server. Why am I getting the error message? I can't find where I made any mistake. -
Django admin - property options based on a related parent model
I have a parent and a child class. The relation between them is many-to-one like this: class Parent(AccessmanagerMixin, models.Model): name = models.CharField(max_length=150) def __str__(self) -> str: return self.name class Child(AccessmanagerMixin, models.Model): name = models.CharField(max_length=150) parent_group = models.ForeignKey(Parent, on_delete=models.CASCADE, null=True ) def __str__(self) -> str: return self.name they both have a many-to-many relation with User class,named read_users (its a custom security on object level). class AccessmanagerMixin(models.Model): read_users = models.ManyToManyField(User, related_name='read_users') class Meta: abstract = True For example in the admin I would like to use the users from Parent read_users as an option for selecting the read_users for the Child entity? How can I do this in a best way? Can I override the read_users property in the Child admin.ModelAdmin. -
how to create auto slugfield in ddjango restframework in django like
class AddCategory(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name', 'slug', 'icon'] lookup_field = 'slug' -
Django: Cant Update/save form
Just a small question in relation to updating my form. I have 2 main pages, the dashboard and auditform pages. Everything works when i click on any item on the home page it directs me to the form page, and all the required information relating to the clicked item populates. The issue is when im trying to Save/Update the file. I believe the issue has to do with the views.py when trying to save, as after i click submit it doesnt redirect me to the home page. Here are the relevant files: urls.py: urlpatterns = [ path('Home/', views.homePage, name='Home'), path('AuditForm/<str:pk>/', views.auditFormPage, name='AuditForm'), path('register/', views.registerPage, name='Register'), path('Login/', views.loginPage, name='Login'), ] urlpatterns += staticfiles_urlpatterns() views.py: def auditFormPage(request, pk): data= datas.objects.get(Task_ID=pk) form = auditForm(instance=data) context = {'data': data} if request.method == 'POST': form = auditForm(request.POST , instance=data) if form.is_valid(): form.save() return redirect('Home') return render(request,"main/auditform.html", context) HTML Webpage: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>QS Tool Demo 1</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <!-- Lightbox --> <link href="path/to/lightbox.css" rel="stylesheet" /> <!-- Stylesheets --> …