Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django download via FileResponse or HttpResponse breaks csrf
In Django I'm trying to make a view that includes these two things: a link to generate and download a file via FileResponse a form to upload a file (posts to a separate view function) If the user uses those things in that order, django returns 403 csrf error. Some things I've tried, but still get csrf error: returning HttpResponse instead of FileResponse posting to the same view function setting CSRF_USE_SESSIONS = True for session-based instead of cookie-based csrf protection I'm curious to understand why this is happening and how to properly build this view. I am aware that @csrf_exempt can be used if csrf protection is not important. -
How to pg_dump only data from a table in a PostgreSQL database and pipe it into an identical but differently-named table in another database
Goal I need to copy just the data from a table in one database into another table in another database. The table in the target database has the exact same schema except that the name of the table is different. The two databases are on the same machine. Problem I can't find a way to pipe the data from pg_dump into a differently named table in the target database. What I've tried Here's the command I would use if the tables were named the exact same: pg_dump -a -t <table_name> <source_db> | psql <target_db> But where would I be able to put the name of the target table in the target database? Background info The reason I'm doing this is because I'm building a Django web-app, and I've realized I really need to separate a bunch of the models I've created into different 'apps' within my Django project. -
npydantic.error_wrappers.ValidationError: 1 validation error for XXX field required (type=value_error.missing)
I've edited the question as going round in circles trying to fix the original error. Here's the latest: Current error pydantic.main.BaseModel.__init__\npydantic.error_wrappers.ValidationError: 1 validation error for ConversationBufferMemory2\nchat\n field required (type=value_error.missing)\n', 'args': '[]', 'kwargs': llm.py chat = Chat.objects.get(id=chat_id) memory = ConversationBufferMemory2() memory.set_chat(chat) models2.py from langchain.memory.buffer import ConversationBufferMemory class ConversationBufferMemory2(ConversationBufferMemory): """Buffer for storing conversation memory.""" chat:Chat #def __init__(self,*args, **kwargs): # super().__init__(*args, **kwargs) def set_chat(self,chat:Chat): self.chat=chat @property def buffer(self) -> Any: """String buffer of memory. Each message is separated by a newline.""" if self.return_messages: return self.chat.messages # Think this is the right return type ? https://python.langchain.com/docs/modules/memory/ else: return get_buffer_string( self.chat.messages, human_prefix=self.human_prefix, ai_prefix=self.ai_prefix, ) ValidationError: File "/code/apps/llm_module/llm.py", line 183, in get_response\n memory = ConversationBufferMemory2()\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File "/usr/local/lib/python3.11/site-packages/langchain/load/serializable.py", line 74, in __init__\n super().__init__(**kwargs)\n File "pydantic/main.py", line 341, in pydantic.main.BaseModel.__init__\npydantic.error_wrappers.ValidationError: 1 validation error for ConversationBufferMemory2\nchat\n field required (type=value_error.missing)\n', 'args': '[]', 'kwargs': -
Why my django urls don't work in production
My site works perfectly on local. But in production all links do not work, except homepage. Why homepage is so special i don't know. Browser shows 400 bad request. On the internet I found only allowed_host = [*], but I have it. Maybe I wrote something wrong in .htaccess or site.wsgi. Or are there special settings for urls in production? My hosting said that I may have errors in the code, but as I said in local it works. I use django 4.1 and python 3.8 setting.py from pathlib import Path from environs import Env env = Env() env.read_env() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'news', 'additional_information', 'photoalbum', 'methods', ] 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', ] ROOT_URLCONF = 'kinder_garden.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/a0833083/domains/mysite.ru/public_html/kinder_garden/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Can I get Django multiple admin sites, users, databases in a webapp?
I have a web app that is now working for a single business. It has users, a database, an admin site that the owner uses, and a few frontend pages through which the employees access it. I am planning to scale and the first idea was using several Django instances as subdomains (that way I just had to duplicate the code and manage routeing), but I soon realised that it would be pretty resource intensive. Is there are a way I can have multiple organizations use the webapp? All of them have the same use case so it should be less complex. I intensively use the Django users app for authentication and as a foreign key in databases so just cannot do without separate admin, users, and database for each business. The point where I encounter major issues is when trying to get different users for each of the business. Thanks a lot in advance! Edit: I just thought about another workaround, though it will take A LOT of coding. Basically making the Django admin by myself. I just need 3-4 functions out of admin: authentication, viewing models, adding users, and downloading databases in xls format. Is there a way … -
Unexpected JSTree state behavior
So I am using JSTree in my Django project and I am experiencing some unexpected behavior when retrieving the state. Before I explain what the issue is, I want to introduce how I intend to use the JSTree. So I have a menu on the left side of my main page, which always stays there. The JSTree is located in this menu and functions like an explorer, giving the user an interface to navigate through the objects displayed, just like folders in e.g. windows explorer. When the user (for instance) adds new objects (that are displayed in the JSTree), he is returned to the main page, where the JSTree is destroyed and reinitialized (thats the current implementation, I might opt to change it in the future tho). My desired behavior would be, that the JSTree keeps its state, so if the user decides to add/delete/edit an object, he does not have to open the folder structure again, to reach the point where he was before. Currently, everything expect restoring the state is working properly. Although, there is a scenario, where it behaves as expect. There are two different scenarios: 1.) When I am on the main page and refresh the … -
Django/Mysql async error “The client was disconnected by the server because of inactivity”
I’m using Django 4.2 connected to a MySQL 8.0.30 database. The server is nginx , with gunicorn (3 workers) and using WSGI. I’m running asyncio for a function I need to run asynchronously because it's used by an async API broker, but here I'm just calling directly from a view, so it's direct and short-lived: from django.db import connection import asyncio example_object = asyncio.run(make_query(name)) async def make_query(request, name): object = await ModelExample.objects.filter(name=name).afirst() return object I’m having the following error on the afirst() query execution: [4031] The client was disconnected by the server because of inactivity. See wait_timeout and interactive_timeout for configuring this behavior Initially the code works fine, the error only starts after a few hours (maybe 8h). I can temporarily fix it by restarting the (nginx) error. It’s a low traffic website so it’s very possible the function is executed only once a day. Because it requires 8hours of innactivity, it's not being easy to replicate or debug this. What I've tried: Django layer: In my understanding, Django always opens a connection, executes a query and then closes a connection. This should happen in WSGI too, but the connection getting idle suggest otherwise. So I tried: Adding close_old_connections() before … -
Sleep() not working with stacked query in mysql-connector-python
I am working on creating a security based CTF application in Django. The current exercise I am building is a blind time-based sql injection. As Django does not appear to support stacked queries through Model.raw(), I imported the mysql-connector-python which does support stacked queries using the cursor.execute(query, multi=True). However, when attempting to use sleep(X) in the stacked query, the sleep statement won't execute. The following is one example: view: query = f"select sleep(2); select 1;" mydb = mysql.connector.connect( host="localhost", user="****", password="****", database="****" ) cursor = mydb.cursor() cursor.execute(query, multi=True) return HttpResponse(f"query: {cursor}") sqli script: url = f"http://127.0.0.1:8080/books/book/?q=1" start = time.perf_counter() response = requests.get(f'{url}') end = time.perf_counter() print(response.text) print(f'response time: {end-start}') This will return the following: query: MySQLCursor: select sleep(2); select 1; response time: 0.005476321006426588 However, if dropping multi=True and running a single query, it the sleep will work just fine. view: query = f"select sleep(2);" mydb = mysql.connector.connect( host="localhost", user="****", password="****", database="****" ) cursor = mydb.cursor() cursor.execute(query) return HttpResponse(f"query: {cursor}") sqli script: url = f"http://127.0.0.1:8080/books/book/?q=1" start = time.perf_counter() response = requests.get(f'{url}') end = time.perf_counter() print(response.text) print(f'response time: {end-start}') This will return the following: query: MySQLCursor: select sleep(2); response time: 2.010241993004456 Note that I have tried using do sleep(X) and it also … -
TypeError: EmailVerificationTokenGenerator.make_token() missing 1 required positional argument: 'contact_form'
I am trying to build an email server for my website. I have a contact form and when you pass it, the server sends a verification link to email address specified in the form. Also, a response after submitting the contact form includes a unique link to re-send new verification link. On the surface my implementation looks fine, but now I am stuck on this error: TypeError at /api/contact/ EmailVerificationTokenGenerator.make_token() missing 1 required positional argument: 'contact_form'. "error screenshot views.py: from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.template.loader import render_to_string from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from rest_framework.views import APIView from rest_framework.response import Response from .serializers import ContactFormSerializer from .verification import EmailVerificationTokenGenerator from .models import ContactForm from email_server.permissions import CanResendVerificationLink from rest_framework import status from django.urls import reverse import secrets from django.shortcuts import get_object_or_404 # Base Mixin class EmailVerificationMixin: def _send_email_verification(self, contact_form): subject = 'Verify Your Email' uidb64 = urlsafe_base64_encode(force_bytes(contact_form.pk)) verification_token = EmailVerificationTokenGenerator().make_token(contact_form) verification_link = self._get_verification_link(contact_form, uidb64, verification_token) body = render_to_string( 'email_verification.html', { 'verification_link': verification_link, } ) email = EmailMessage(subject=subject, body=body, to=[contact_form.email]) email.send() def _get_verification_link(self, contact_form, uidb64, token): current_site = get_current_site(self.request) verification_url = reverse('activate', kwargs={'uidb64': uidb64, 'token': token}) verification_link = f'{self.request.scheme}://{current_site.domain}{verification_url}' return verification_link def _get_resend_verification_link(self, … -
Unable to login in custom user model
I have custom user model that works goods for registration and creating superuser. But it fails to login. I have been trying to rectify the problem but couldn't find any potential errors... Login Form is not logging in the user when I submit the form, it just says the user with that username already exists (it is kind of acting like signup page) How to resolve this issue or else i get a 'page not accessible contact owner of the site' #models.py class Organisation(models.Model): organisation_name = models.CharField(max_length = 256) contact_no = models.IntegerField() email = models.EmailField() class Meta(): unique_together = ['organisation_name','email'] def __str__(self): return self.organisation_name class MyUserManager(BaseUserManager): def create_user(self, username, organisation, email, password): if not organisation: raise ValueError("Users must have an organisation") email = self.normalize_email(email) user = self.model(username=username, email=email, organisation=organisation) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, username, email, password): user = self.model(username=username, email=self.normalize_email(email)) user.set_password(password) user.is_superuser = True user.is_staff = True user.save(using=self.db) return user class MyUser(AbstractBaseUser): username = models.CharField(max_length=256,unique=True) email = models.EmailField(max_length=256) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,null=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['email'] objects = MyUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True #forms.py class MyUserForm(forms.ModelForm): class Meta(): model = models.MyUser fields = … -
How to abort a long request in Django and stop processing?
There might be cases in my API when a single request will take more than 10 seconds, in which case I want to abort the processing and return some error. I've done some research and I know that just aborting the request to the server is not enough, and that won't be pushed to the Django server. I was wondering whether there is a way to do this? -
django formset is not working, like im expecting
I have OrderItemFormSet like class OrderForm(forms.ModelForm): class Meta: model = Order fields = ["total_cost"] class OrderItemForm(forms.ModelForm): class Meta: model = OrderItem fields = ["product", "quantity"] OrderItemFormSet = forms.inlineformset_factory( Order, OrderItem, form=OrderItemForm, extra=1, # Set the number of empty forms to display ) and view class CreateOrderView(View): template_name = "orders/create_order.html" def get(self, request): order_form = OrderForm() order_item_formset = OrderItemFormSet() return render( request, self.template_name, { "order_form": order_form, "order_item_formset": order_item_formset, }, ) def post(self, request): order_form = OrderForm(request.POST) order_item_formset = OrderItemFormSet(request.POST, prefix="order_item") if order_form.is_valid() and order_item_formset.is_valid(): order = order_form.save(commit=False) order.user = request.user # Assign the currently logged-in user order.save() order_item_formset.instance = order if ( order_item_formset.has_changed() ): # Check if there are any additional forms order_item_formset.save() # Save the additional forms # order_item_formset.save() return redirect("dashboard:dashboard") return render( request, self.template_name, { "order_form": order_form, "order_item_formset": order_item_formset, }, ) my template <form method="post" id="order-form"> {% csrf_token %} <fieldset> <legend>{% trans "Order Information" %}</legend> {{ order_form|crispy }} </fieldset> <fieldset> <legend>Order Items</legend> {{ order_item_formset.management_form }} <div id="order-items-container"> {% for form in order_item_formset %} <div class="order-item-form">{{ form|crispy }}</div> {% endfor %} <input type="hidden" name="ORDER_FORMS-TOTAL_FORMS" value="{{ order_item_formset.total_form_count }}"> </div> </fieldset> <div class="col-sm-12 d-flex justify-content-end"> <button class="btn btn-light-secondary me-1 mb-1" type="button" id="add-order-item">{% trans "Add Order Item" %}</button> <button class="btn btn-primary me-1 mb-1" … -
Django df to html show text
I am totally a new bee in Django, it's my 2nd day to learn it. I have already connected to the database and use the pandas.read_sql_query to get the df from database (I know there is ORM but since we use MSSQL, so it need more time for me to figure it out, and I really need to show sth at lease so I use pandas.read_sql_query) I have already got the df and I want it to show in the html. According to some other posts, I use the code below: view.py a_query=""" select * FROM db """ a = pandas.read_sql_query(a_query,connection) a_html = a.to_html(index=False) print(a) print(type(a)) return render(request, 'index.html',{'a_html':a_html}) the type shows: So I think it's all good. <class 'pandas.core.frame.DataFrame'> index.html I put {{a_html}} in the body part, it's the only thing I change after the original format. after I run the manage.py, it shows this in html: <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th>IT Business Service</th> <th>IT Service Instance</th> </tr> </thead> <tbody> <tr> <td> sth like that. But I want to to show the table, how should I do for it? Any help is really apprecaited! -
How to check the type of user logged in django?
I want to check the type of user logged in and return the template according to the user logged in. How can I check the type of user? This is my django model: class UserProfile(models.Model): user = models.OneToOneField(User , on_delete= models.CASCADE) class Student(models.Model): profile = models.OneToOneField(User, on_delete= models.CASCADE) rollNo = models.CharField(max_length=15) def __str__(self): return (self.rollNo) class Supervisor(models.Model): profile = models.OneToOneField(User, on_delete= models.CASCADE) teacher_ID = models.CharField(max_length=15) def __str__(self): return (self.profile) I have tried the following statements but it gives an error: def homePage(request): if not request.user.is_authenticated: return render(request , 'accounts/login.html') user = request.user is_student = Student.objects.filter(profile__user=user).exists() is_supervisor = Supervisor.objects.filter(profile__user=user).exists() return HttpResponse("Hello") Error: Unsupported lookup 'user' for OneToOneField or join on the field not permitted. -
What's the best way to automatically generate a .env-sample file from a .env file using Python or shell commands?
I've been using python-decouple to read my .env file, and it has been working great. To ensure that sensitive information is not pushed to GitHub, I've been manually creating a .env-sample file with just the variable names and pushing that to the repository instead. However, I sometimes forget to update the .env-sample file when I make changes to the .env file. It's a manual task that can be quite error-prone. I was wondering if there is an automatic way to generate the .env-sample file using Python or any other shell commands. It would be super helpful if there's a more efficient and reliable approach to keeping my sample file up to date. -
How to get username of a user by his email in django (he shold be not loged in) [closed]
my_user=User.objects.create_user(email=Email, password=Password, username=username, first_name=Last_Name) my_user.save() Here is the code for how I registered the user in Django -
Why is the my form not submitting all the fields i filled and how do i fix it?
On my real estate Django web app, I have a form which users fill to list their property or get services. The form to be filled differs depending on the type of property in question(Single or Multiple apartment properties) so I used Tailwindcss to display these forms depending on the user's choice <form class="border-3 border-red-400 p-11 block space-y-4 justify-center w-screen h-screen items-center" action="{% url 'requestservice:req_service' %}" method="POST"> <input type="radio" id="single" value="SINGLE" class="peer/single" name="property_type" checked /> <label for="single" class="peer-checked/single:text-sky-500">Single Unit</label> <input type="radio" id="multiple" value="MULTIPLE" class="peer/multiple" name="property_type" /> <label for="draft" class="peer-checked/multiple:text-sky-500">Multiple D. Unit</label> <div class="hidden peer-checked/multiple:block bg-white px-2 py-1 w-full space-y-2 md:space-y-3 rounded-xl"> <!-- <h3> M.D.U Unit Form </h3> --> <div class="block"> <p class="font-medium text-gray-950 text-sm"> Name of property: </p> <input type='text' class="w-full p-1 focus:border-1 focus:outline-yellow-300 border border-red-100 shadow-md shadow-red-100 rounded-lg " placeholder="Property name"> </div> <div class="font-medium flex space-x-5"> <p class="font-medium text-sm"> Central Server Room Avaliable: </p> <input type="radio"> </div> <div class="block "> <p class="font-medium text-sm"> Number of houses in MDU </p> <input placeholder="Number of houses" class="w-full p-1 focus:border-1 focus:outline-yellow-300 border border-red-100 shadow-md shadow-red-100 rounded-lg" type="number"> </div> </div> <div class="hidden peer-checked/single:block bg-white px-2 py-1 space-y-2 w-full rounded-xl"> <!-- <h3> Single Unit Form </h3> --> <div class="block space-y-1"> <p class="font-medium"> Name of property: … -
django how can i display multiple pictures by id inside multiple items
i have 2 classes in my models.py class Product(models.Model): ext... and class ProductImage(models.Model): product=models.ForeignKey(Product, default=None, on_delete=models.CASCADE) image=models.ImageField views.py def view_property(request, id): photo = get_object_or_404(ProductImage, id=id) product = get_object_or_404(Product, id=id) photos = ProductImage.objects.filter(product=product) context = { 'photo':photo, 'product':product, 'photos': photos } return render(request,'products/view_property.html', context) so to display multiple images in my html page i include int:id or samthing like that in the url.py url.py from django.urls import path from . import views urlpatterns = [ path( '<int:id>/' , views.view_property , name = 'view_property' ), ] Now when I want to fetch data to my view_property.html page, I get the images filtered fine by ID, so it works, but the problem is in my view_property.html page On the page I have items, each item contains the product and pictures in the slider so i want to fetch multiple products each product fetch his images filtred by id view_property.html <div class="box-container"> {% for pro in products %} <div class="box"> <div class="image-container"> {% for img in photos %} <div class="mySlides"><img src="{{img.image.url}}" alt=""></div> {% endfor %} </div> <div class="content"> <div class="location"> <p>apartments</p> </div> </div> </div> {% endfor %} </div> her i get all images of one product same thing with each items because i fetching … -
How to upload screensot if the task is completed in django rest api
Model This is the model i created this model inside the Admin app class AndroidApp(models.Model): name = models.CharField(max_length=100) link = models.URLField() category = models.CharField(max_length=100) subcategory = models.CharField(max_length=100) image = models.ImageField(upload_to='app_images/') completed = models.BooleanField(default=False) points = models.IntegerField() View class UserAppDetailedView(APIView): def get(self,request,id): try: app = AndroidApp.objects.get(id=id) except AndroidApp.DoesNotExist: return Response({'message': 'App not found.'}, status=404) serializer = AndroidAppSerializer(app) return Response(serializer.data) def put(self, request, id): try: app = AndroidApp.objects.get(id=id) except AndroidApp.DoesNotExist: return Response({'message': 'App not found.'}, status=404) if app.completed: return Response({'message': 'App already completed.'}) app.completed = True app.save() serializer = AndroidAppSerializer(app) return Response(serializer.data) def patch(self, request, id): app = AndroidApp.objects.get(id=id) if app: serializer = AndroidAppSerializer(app, data=request.data, partial=True) if serializer.is_valid(): if app.completed: screenshot = serializer.validated_data.get('screenshot', None) if screenshot: app.screenshot = screenshot app.save() return Response(serializer.data) return Response({'message': 'Please provide a screenshot image.'}, status=400) else: return Response({'message': 'App task is not completed.'}, status=400) return Response(serializer.errors, status=400) return Response({'message': 'App not found.'}, status=404) In tis code im trying to do first i check the app(task) is completed or not if the task is not completed the updated the task as true . it is working and after that i ant to upload the screen shot if the task is completed . so in my settings.py file i … -
TypeError at /saml2/ls/post/ Not a logout_response
I am trying to setup django with saml2 for sso with okta. In okta settings I have Single Logout URL: http://localhost:8000/saml2/ls/post/ SP Issuer : http://localhost:8000/saml2/metadata/ as per the documentation. In my settings.py I have the example config shown in the okta example, and have the LOGIN_REDIRECT_URL = '/home' and the 'home' path exists and works. When I login using http://localhost:8000/saml2/login/, I am correctly signed in (the saml_session cookie is created), but I am redirected to http://localhost:8000/saml2/ls/post/ and shown the error: TypeError at /saml2/ls/post/ Not a logout_response. Does anyone have any suggestions? The redirect url is not being accessed and/or the login is triggering a logout and I am not sure how to proceed! Thank you! -
Need to group the apps in the sidebar of django admin using the package jazzmin
As you can see in the image i have managed to group the apps in the landaing page of dashboard but nit in side bar. i need to group the models in the side bar too. i have used the jazzmin package as well as the admin_reorder -
New relic showing Transaction as views.function_name for pyhton services while I want to show API endpoint
I am checking transaction data for one of my APIs on Django and getting new relic Transactions as a.views:function1_name and a.views.function2_name, while I want to show API endpoints in transactions. How can I do this? -
django /admin showing react index.html page wiith when runing behind nginx
I am following this guide React-django-nginx, I am unable to access /admin it shows blank page with react's index.html page code inside it. but when access /admin by hard refreshing the page then it works correctly. all the configurations in conf file are same as this guide -
Pdf file is not displaying on frontend
I have uploaded the pdf file in django admin panel. However, when I try to open the pdf file in html file tag, it is not opening. HTML code: <a href="{{ opinion.tests }}">Your tests</a> </div> views.py: def report(request): if request.method == 'POST': try: name = request.POST['name'] phone1 = request.POST['phone'] print("name:", name, "phone", type(phone1)) analysis = Report.objects.filter(phone=phone1)[0] opinion = {'opinion': analysis} return render(request, "reports.html", opinion) except: return render(request,"not_found.html") models.py: class Report(models.Model): current_date = str(datetime.date.today()) name= models.CharField(max_length=100) email= models.EmailField(max_length=1000) phone = models.IntegerField() previous_history =models.TextField(max_length=5000) current_diagnosis= models.TextField(max_length=5000) doctor = models.CharField(max_length=100) tests = models.FileField(upload_to='ptest/', default="") def __str__(self): return self.name + " | " + "Doctor : "+ self.doctor File is displaying in admin panel. It is also uploading in the backend. The html page also displays without any error. However, when I click to open to see the file , it gives an error. I am uploading a pdf file and i am expecting the file to be displayed in html file in the frontend. -
Django edit_post view not prepopulating form fields with existing data
I'm developing a Django blog application and I have a view to edit a post. However, when I click the Edit button, the form fields do not appear prepopulated with the existing data. Here's my edit_post view code: def edit_post(request, post_id): post = get_object_or_404(Post, id=post_id) if request.method == "POST": form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return redirect("main_page") else: form = PostForm(instance=post) context_dict = { "form": form, "post": post, } return render(request, "blog/edit_post.html", context_dict) I have verified that the PostForm is correctly configured with the required fields from the Post model. I also tried using the @never_cache decorator, but it didn't resolve the issue. I'm not sure why the form fields are not prepopulated with the existing data after submitting the form. It only works when I manually reload the page. Any suggestions or insights on how to fix this issue would be greatly appreciated.