Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can solve this problem to apply that for loop for every line of that csv file?
When i try this for loop to add data with a csv file it just adds the data of last line in csv file. from django.db import models # Create your models here. class product(models.Model): Number=models.CharField( max_length=40 ) name=models.CharField(max_length=40 ) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) p=product() f = open('b.csv', 'r') for line in f: line = line.split(',') p.Number=line[0] p.name=line[1] p.image=line[2] p.description=line[3] p.price=line[4] p.buy=line[5] p.save() f.close() csv file: Number,name,image,description,price,buy 1,a,1,1,1,1 2,bb,2,2,2,2 3,aa,3,3,3,3 4,bd,4,4,4,4 5,d,5,5,5,5 6,e,6,6,6,6 there is just one product with the data of last line of csv file: How can solve this problem to apply that for loop for every line of that csv file? -
OperationalError at /admin/ no such table: User
Here I have creates user model and inherited AbstractUser to the user model. but No such table showing here, I did migrations also but it is not showing. Please tell me what to do: Error: OperationalError at /admin/ no such table: User Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 3.2.13 Exception Type: OperationalError Exception Value: no such table: User Exception Location: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\Manoj\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.5 Python Path: ['E:\\Project\\S3_project', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Manoj\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Manoj\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin'] Server time: Sat, 23 Apr 2022 09:10:23 +0000 models.py: class User(AbstractUser): address = models.TextField(max_length=500,null=False) contact_number = models.PositiveIntegerField(null=False) ut=(('Admin','Admin'),('Operator','Operator'),('Ticket generator User','Ticket generator User'),('Inspector','Inspector'),('User 80','User 80'),('Final Inspection','Final Inspection'),('Maintenance','Maintenance'),('Ticket admin','Ticket admin')) user_type = models.CharField(max_length=100,null=False,choices=ut) class Meta: db_table = "User" forms.py: class UserForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','address','contact_number','user_type','username','password'] widgets = {'first_name': forms.TextInput(attrs={ 'class': 'form-control'}), 'last_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'address': forms.Textarea(attrs={ 'class': 'form-control' }), 'contact_number': forms.NumberInput(attrs={ 'class': 'form-control' }), 'user_type': forms.Select(attrs={ 'class': 'form-control' }), 'username': forms.TextInput(attrs={ 'class': 'form-control' }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control' }) } settings.py: AUTH_USER_MODEL = 'Master.User' admin.py: admin.site.register(User) -
Is there anyway to compare two fields in two models and store a field in the first model in Django?
class Register(models.Model): prollno=models.CharField(max_length=8) full_name=models.CharField(max_length=100) drollno=models.CharField(max_length=9) email=models.EmailField() gender=models.CharField(max_length=7,default="Male") programme=models.CharField(max_length=100) course=models.CharField(max_length=100) yearofstudy=models.CharField(max_length=5) phone=models.BigIntegerField() city=models.TextField() pincode=models.IntegerField() address=models.TextField() isblacklisted=models.BooleanField(default=False) class Blacklist(models.Model): prollno=models.ForeignKey(Register) full_name=models.CharField(max_length=100) email=models.EmailField(max_length=55) phone=models.BigIntegerField() I have two models Register and Blacklist and I have to compare the prollno of Register and Blacklist and if the values stored in both prollno are same, then I have to save the field isblacklisted of Register Model to True. -
Filter queryset of django inline formset based on attribute of through model
I have a basic restaurant inventory tracking app that allows the user to create ingredients, menus, and items on the menus. For each item on a given menu, the user can list the required ingredients for that item along with a quantity required per ingredient for that item. Menu items have a many-to-many relationship with ingredients, and are connected via an "IngredientQuantity" through table. Here are my models: class Ingredient(models.Model): GRAM = 'Grams' OUNCE = 'Ounces' PIECE = 'Pieces' UNIT_CHOICES = [ ('Grams', 'Grams'), ('Ounces', 'Ounces'), ('Pieces', 'Pieces') ] user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) unitType = models.CharField(max_length=200, choices=UNIT_CHOICES, verbose_name='Unit') unitCost = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Unit Cost') inventoryQuantity = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Quantity') def __str__(self): return self.name + ' (' + self.unitType + ')' def totalCost(self): result = self.inventoryQuantity * self.unitCost return "{:.0f}".format(result) class Menu(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) timeCreated = models.DateTimeField(auto_now_add=True) timeUpdated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.name) class MenuItem(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) name = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2) ingredients = models.ManyToManyField(Ingredient, through='IngredientQuantity') menu = models.ForeignKey(Menu, on_delete=models.CASCADE, null=True) def __str__(self): return self.name def itemCost(self): relevantIngredients = IngredientQuantity.objects.filter(menuItem=self) cost = 0 for ingredient in relevantIngredients: cost += (ingredient.ingredient.unitCost * ingredient.ingredientQuantity) … -
How to change the status code that is recieved in the response in case of specific exceptions in Django rest framework
I am adding some details to my Django model from a react frontend. Everything is working fine and the API request is made with Axios. The data that is being submitted is an OneToOne Field with the user and hence submitting more than once raises an Integrity error of Unique Constraint. But the response I receive back has a status of 200. This triggers a notification in my frontend that says details submitted every time the button is pressed. However. that is not being submitted the second time because of the Integrity Error. My question is if I handle the Integrity Error exception separately how can I send a different status rather than 200 as shown below config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …} data: {message: 'UNIQUE constraint failed: teacher_teacherdetail.user_id'} headers: {content-length: '39', content-type: 'application/json'} request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" Currently I am handling the exception as below try: # some code except IntegrityError as e: message = { "error": str(e) } return Response(message) except Exception as e: message = { "message": "exception", "error": str(e) } return Response(message) -
How to synchronize Django database migration on VPS and inside django container?
I have a task to set up work with migrations. In this photo I am on the VPS and when I try to see apps migrations, there is only one migration file(0001_initial.py) in every app. And for example if I change something in models.py and run 'makemigrations & migrate' commands, the new migration file won't appear here on the VPS, it will only appear inside the django container And the question here is how can I set up migrations so that when I run docker-compose -f docker-compose.dev.yml exec web_dev python manage.py makemigrations docker-compose -f docker-compose.dev.yml exec web_dev python manage.py migrate commands from the VPS, migration files appear here in the VPS and not only inside the django container? -
Django with DRF APIs slows down after few weeks or months
I have Django with DRF sight and it has couple of APIs based on DRF with GenericAPI view and API view. The APIs is used to calculate XML vs XML and JSON vs JSON differences. Two objects are passed as body to these APIs and the API returns the no of differences and exact nodes at which the differences are found. It also respond with nodes which are added or removed. The sight and APIs work just fine when my environment is just up and running for few weeks say 2 weeks. I have recently observed that after a month or 3 weeks same APIs takes much more time to calculate the differences with same set of data. Usually it is very fast for example If we have large JSON object then 1k differences per second is processed. If we have pretty small JSON or XML object like 5 to 10 keys (very basic) the main library function which calculates the difference tales just about few milliseconds. So overall API time is like 200 ms. Now the issue that I have is after lets say 3 weeks or a month same very basic JSON object comparison (with just 5-10 keys) … -
What can i do to add a.csv data to my fields in django?
In this code i have a for loop that wants to add a.csv data to my django fields but when i run the server there is no data in fields of product model. from django.db import models # Create your models here. class product(models.Model): Number=models.CharField( max_length=40 ) name=models.CharField(max_length=40 ) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) p=product() f = open('a.csv', 'r') for line in f: line = line.split(',') p.Number=line[0] p.name=line[1] p.image=line[2] p.description=line[3] p.price=line[4] p.buy=line[5] p.save csv: Number,name,image,description,price,buy What can i do to add that csv data to my fields? -
Django Internationalization gettext() Not Creating message files from JavaScript source code
I am working with django internationalization. I did all setup its working fine in templates and .py files. I tried to create a translation text in .js file I setup that like This documentaion. After the setup I used the gettext() in my js file is not showing the error in console. Then I use the command to create messages file django.po using this command django-admin makemessages -d djangojs -l ta and the translation text not added in django.po file. urls.py urlpatterns = i18n_patterns( ..., path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), prefix_default_language=False ) js file console.log(gettext('Javascrit gettext')) //Print the text in console it was working. -
Folium - Django: How to make a folium marker a link to another page
I'm generating a map using Folium with Django like so: views.py def viz(request): dg_map= folium.Map(location=[50.38175,6.2787], tiles= 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png?api_key=<MY_API_KEY>', attr= '&copy; <a href="https://stadiamaps.com/">Stadia Maps</a>, &copy; <a href="https://openmaptiles.org/">OpenMapTiles</a> &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors', zoom_start=10) map_details = fetch_data("SELECT id, firstname, lat, long FROM map_details") #helper func to query the DB for item in map_details: location = [item[2], item[3]] popup = f"{item[1]}'s Garden" marker = folium.Marker( location = location, popup = popup, icon=folium.Icon(color='darkgreen', icon="heart", prefix='fa')) marker.add_to(dg_map); m = dg_map._repr_html_() context = {'map': m} return render(request, 'accounts/viz.html', context) This is working as expected. However, I'd like each marker to redirect towards another page on-click. To make matters worse, I'd need to use the id that's querried in the SELECT statement and include it in the destination link, because the urlpattern of the destination pages is this: urls.py path('garden/<str:id>/', views.garden, name="garden"). What I found out so far: I found several suggestions on how to add an href to the pop-up (e.g. here) but this is not what I want as it requires the user to click twice. Some ideas on how to add custom js to Folium's output are mentioned here, but I think it's not implemented yet. I also found instructions on how this can be done … -
How to serialize object field in django rest framework
I have Profile model, which is auth model. And I have Blog model. I want to serialize model as it will give me {author: {user_name:.., photo: photo_path}, blog_title:some_title, ..}. Shortly, I want use author field as inner serialiser. I have already ProfileSerialiser and BlogSerializer. Here's my BlogList serializer: class BlogListSerializer(serializers.ModelSerializer): author = MiniProfileSerializer() class Meta: model = Blog fields = ['title', 'content', 'like_count', 'author'] read_only_fields = ['views', 'author', 'like_count'] And MiniProfileSerializer: class MiniProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['user_name', 'image'] and view: class BlogListAPIView(generics.ListCreateAPIView): serializer_class = BlogListSerializer queryset = Blog.published.all() permission_classes = [permissions.IsAuthenticatedOrReadOnly] -
Can't change background color of django form field
I'm trying to change background colors of django form field using attrs of form.widget like below. forms.py class MyForm(forms.Form): a_filed = forms.EmailField( widget=forms.EmailInput( attrs={'class':'black-input'})) It produces an html element in a template with classname 'black-input' as expected. html <input type="email" name="email" class="black-input" id="id_email"> Elements with the name 'black-input' should show up with black background as I set {background-color:black} in my css. main.css .black-input{ padding: 5px; background-color: rgba(1, 4, 9, .7); color: rgba(177, 177, 177, .8); border: none; border-radius: 8px; } But css doesn't change anything about background color. The weird part is that css changes other attributes of the element (border, border-radius, padding). -
How do i do user = request.user in views.py just because i have foreign key in my model
How do i update user field in views.py just because i have a view to edit and delete posts associated with the user. I also have a view that fetch products with user == request.user and show in the profile page. Almost my site is dependent on post creation.Please let me know how can I update that user foreign key while saving the form( ex:- product.user = request.user ) My Models.py ```class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=150) details = models.TextField(default="...") ....``` My Forms.py ```class AddUserPacksForm(forms.ModelForm): user = forms.ModelChoiceField(label="", queryset=User.objects.all(), widget=forms.HiddenInput(), required=False) title = forms.CharField(label='Title', widget=forms.TextInput( attrs={'class': 'form-control'})) details = forms.CharField(label='Description', widget=forms.Textarea( attrs={'class': 'form-control'})) image = forms.FileField(label='Thumbnail', widget=forms.FileInput( attrs={'class': 'form-control'})) sp = forms.IntegerField(label='Selling Price', widget=forms.NumberInput( attrs={'class': 'form-control'})) dp = forms.IntegerField(label='Discounted Price', widget=forms.NumberInput( attrs={'class': 'form-control'})) buy_link = forms.CharField( label='Buy Link ( i.e Instagram Link, Shorten Urls, Your Own Website Link Where Users can Buy This Pack, etc )', widget=forms.TextInput(attrs={'class': 'form-control'})) category = forms.ChoiceField(label='Category', choices=CHOICES, widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Product fields = ['title', 'details', 'image', 'sp', 'dp', 'buy_link', 'category']``` My Views.py ```def AddUserPacks(request): if request.method == "POST": userform = AddUserPacksForm(request.POST, request.FILES) if userform.is_valid(): userpacks = userform.save(commit=False) userform.user = request.user.get_profile() userpacks.save() messages.success(request, f'Successfully Uploaded the post') return redirect('home') … -
How To give optional parameter in DRF
Hi Everyone i am created one api, where i will city_id as parameter but i need id parameter for this api, means view data based on city_id or based on id, please help me out. serializers.py class CarNumberSerializer(serializers.ModelSerializer): model=CarModelNameSerializer() company=CarCompanySerializer() class Meta: model = Car fields = ['id','car_number','model','company'] views.py class CarNumberViewset(viewsets.ModelViewSet): queryset=Car.objects.all() serializer_class= CarNumberSerializer def retrieve(self, request, *args, **kwargs): params= kwargs params_list=params['pk'] car=Car.objects.filter(city=params_list) serializer=CarNumberSerializer(car,many=True) return Response(serializer.data) urls.py routers.register(r'gms/car_list',CarNumberViewset) -
Upload file to Django in Requests.POST
Trying to upload a text file (of molecules) to ADMETlab 2.0 and download the corresponding CSV output, from within python. Tried the following code: import requests fyle = 'infile.sdf' Headers = {"Referer" : "https://admetmesh.scbdd.com/service/screening/index", "User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"} with open(fyle, 'rb') as f: r = requests.post('https://admetmesh.scbdd.com/service/screening/cal', files={fyle: f}, headers=Headers) print(r.text) Which led to this error: ValueError: invalid literal for int() with base 16: b I tried this fix and now, no error is raised but nothing except a blank new line is printed. Where am I going wrong? -
How to add default data to django model
I have a web app with the following model class Records(models.Model): alias = models.CharField(max_length=17, unique=True) status = models.BooleanField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.alias def list_data(self): return [self.alias, self.status, self.created_at, self.updated_at] I want some default data to be populated into this model on creation. I went through the documentation and this StackOverflow question for doing the same. I first ran this command to create a migrations file (0001_initial.py) python manage.py makemigrations --empty main_app I then edited the migrations file as follows 0001_initial.py # Generated by Django 4.0.3 on 2022-04-23 05:57 from django.db import migrations def add_initial_data(apps, schema_editor): Records = apps.get_model('main_app', 'Records') for record in Records.objects.all(): record.alias = f'ACCORD1' record.status = True record.save() for i in range(2,6): record.alias = f'ACCORD{i}' record.status = False record.save() class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunPython(add_initial_data) ] When I run the migrations with the following command python manage.py migrate I get the following error LookupError: No installed app with label 'main_app'. I tried adding the dependency to the migrations file as follows dependencies = [ ('main_app', '0001_initial') ] But this gives me the following error django.db.migrations.exceptions.CircularDependencyError: main_app.0001_initial I am not sure what I am doing wrong. -
Why data passed from frontend using ajax shows NonType in view function in Django
I have created a form in html which take some value from user on clicking submit button a JavaScript function is called which passes data using ajax to Django server. But instead of getting data in view function it shows NoneType error on backend. My html form:- <div class="cropDetail"> <form method="post"> {% csrf_token %} <div class="form__group"> <label htmlFor="name" class="form__label"> Nitrogen </label> <input type="number" id="nitrogen" name="nitrogen" class="form__input" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Potassium </label> <input type="number" id="potassium" class="form__input" name="potassium" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Phosphorus </label> <input type="number" id="phosphorus" class="form__input" name="phosphorus" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> PH </label> <input type="number" id="ph" class="form__input" name="ph" required /> <p className="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> Rainfall </label> <input type="number" id="rainfall" class="form__input" name="rainfall" required /> <p class="error"></p> </div> <div class="form__group"> <label htmlFor="name" class="form__label"> City </label> <input type="text" id="city" class="form__input" name="city" required /> <p class="error"></p> </div> <div class="form__actions"> <button onclick="passdata()">Submit</button> </div> </form> </div> My JavaScript function:- const nitro = document.getElementById("nitrogen"); const potass = document.getElementById("potassium"); const phos = document.getElementById("phosphorus"); const phi = document.getElementById("ph"); const rain = document.getElementById("rainfall"); const cityi = document.getElementById("city"); function passdata(event) { event.preventDefault(); const usernitrogen = nitro.value; const userpotassium … -
Chrome Incognito Mode 2GB download net::ERR_FAILED
Maybe you could share your piece of advise on the following trouble: Chrome Incognito Mode doesn't let download big files (2 Gb) with net::ERR_FAILED 200 error in console: The same download of the same file works fine without Incognito; the same same request with the same headers also work fine when loading a file via Curl; and other browsers' incognito mode also works fine. I wonder maybe there is some kind of a memory limit for file download using Chrome in Incognito mode? And what memory does Chrome use for downloading files in Incognito mode? Thank you! -
CSS doesn't work as expected in HTML files in Django
I want to know why static CSS files in Django always don't work as expected? I tried to include CSS styles in HTML tag, load static files in HTML. Only add styles directly in tag attributes worked. Some CSS code worked well in static folder, some don't. I can't even style an 's color through CSS files, which is one of the simplest styling things. Still can't find a perfect way that can solve this problem. Please help me with this >< -
django.core.exceptions.FieldError: Unknown field(s) (contact_number, address, user_type) specified for User
how to solve this error: django.core.exceptions.FieldError: Unknown field(s) (contact_number, address, user_type) specified for User. forms.py: from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model=User fields=['first_name','last_name','address','contact_number','user_type','username','password'] widgets = {'first_name': forms.TextInput(attrs={ 'class': 'form-control'}), 'last_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'address': forms.Textarea(attrs={ 'class': 'form-control' }), 'contact_number': forms.IntegerField(attrs={ 'class': 'form-control' }), 'user_type': forms.Select(attrs={ 'class': 'form-control' }), 'username': forms.TextInput(attrs={ 'class': 'form-control' }), 'password': forms.PasswordInput(attrs={ 'class': 'form-control' }) } I am getting difficulty here please tell me what to do. -
How to correctly access parent form's field/s from inline form clean method during Update
I am a little perplexed. Using CreateView, When I try to get the data of a field in the parent table's form from the (child table's) inline form's clean method I can do that: def clean(self): super(CreateMyItemsForm, self).clean() cleaned_data = super(CreateMyItemsForm, self).clean() var_date = self.data.get('valid_to_date') # NOTE: **valid_to_date** is a field in the parent table However, during update (using UpdateView) the same method fails. Why? What am I doing wrong here? Thanks. -
Wagtail: Get data from promote tab?
When creating a new page, there's a "Promote" tab. Under the "for search engines" section there's a "title tag" and a "meta description" value. As I understand, the "title tag" sets the document's title and the "meta description" sets the document's meta description. But how would I actually use these values in my page template? I searched far and wide, but it seems that Wagtail's documentation explains nothing about the Promote tab or what purpose it serves. Are the values defined there available as template variables? How would I actually access a page's "title tag" or "meta description"? -
got an "django local variable 'form' referenced before assignment" error in django form
When I have only one form in view.py it works, but when I add another form I got this error. Error Forms.py Views.py -
Running Django's collectstatic in Dockerfile produces empty directory
I'm trying to run Django from a Docker container on Heroku, but to make that work, I need to run python manage.py collectstatic during my build phase. To achieve that, I wrote the following Dockerfile: # Set up image FROM python:3.10 WORKDIR /usr/src/app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Install poetry and identify Python dependencies RUN pip install poetry COPY pyproject.toml /usr/src/app/ # Install Python dependencies RUN set -x \ && apt update -y \ && apt install -y \ libpq-dev \ gcc \ && poetry config virtualenvs.create false \ && poetry install --no-ansi # Copy source into image COPY . /usr/src/app/ # Collect static files RUN python -m manage collectstatic -v 3 --no-input The Dockerfile builds just fine, and I can even see that collectstatic is running and collecting the appropriate files during the build. However, when the build is finished, the only evidence that collectstatic ran is an empty directory called staticfiles. If I run collectstatic again inside of my container, collectstatic works just fine, but since Heroku doesn't persist files created after the build stage, they disappear when my app restarts. I found a few SO answers discussing how to get collectstatic to run inside a Dockerfile, but … -
ProgrammingError at /blog/ django project in ubuntu vps
I encountered this error after deploying the project on a Linux server. But when running it on localhost, I had no error like this in addition that I say, I have a blog application views.py from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by("-created_at") template_name = "blog/blog.html" class PostDetail(generic.DetailView): model = Post template_name = "blog/blogContent.html" urls.py from django.urls import path from . import views urlpatterns = [ path("", views.PostList.as_view(), name="blog"), path("<slug:slug>/", views.PostDetail.as_view(), name="post_detail"), ] blog.html {% extends 'base.html' %} {% load static %} {% block content %} <main class="main"> <div class="container blog_container"> <h2>وبلاگ</h2> <div class="content_container"> {% for post in post_list %} <div class="content"> <a href="{% url 'post_detail' post.slug %}"><img src="{{ post.image.url }}" alt="" ></a> <a href="{% url 'post_detail' post.slug %}" class="title">{{ post.title }}</a> <p>{{ post.author }} </p> <p>{{ post.created_at|timesince }}</p> <br> <p class="description">{{post.content|slice:":200" }} </p> </div> {% endfor %} </div> </div> </main> <!-- START FOOTER COMPONENT --> {% endblock content %}