Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AUTH_LDAP_HASH_PASSORD DJNAGO
I have a problem with the connection with an LDAP user who has a hashed password. if I change the user's password with raw text the connection is successful but with hash no. this is the code of authentification : logger.info("Trying to authenticate the user %s against the LDAP" % username) user = super(LDAPBackendCustom, self).authenticate(request, username, password, **kwargs) also if I run ldapsearch -H ldap://10.110.0.150 -D "bgleeson@contoso.com" -w 2fourall if the password is in raw text this commande return the user but if it is in hash format the LDAP_SEARCH invalid bind credential -
recording user's post like time
I am building a simple BlogApp and I am trying to record user like post time. I have created a field named like_time But the problem is when user_1 like the post than the time is recorded But when user_2 like than it resets the user_1 time, But i am trying to store different like time of different of different users. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length-300) likes = models.ManyToManyField(User, related_name='likes') body = models.CharField(max_length=300) like_time = models.DateTimeField(auto_now=True) views.py def blog_post_like(request, blogpost_id): post = get_object_or_404(BlogPost, pk=blogpost_id) if request.user not in post.likes.all(): post.likes.add(request.user) post.like_time = timezone.now() post.save() return JsonResponse({'disp':'success'}) The Problem :- It is resetting every for every user on same post, But I am trying to store different like time for different users, like :- user_1 - liked time - 40 seconds ago user_2 - liked_time - 30 seconds ago Any help would be much Appreciated .Thank You -
That choice is not one of the available choices django
I have a form to update user, the error is on the role field. I am filtering the role based on customer. I am getting the right values for role but anyways the error pops up. Select a valid choice. That choice is not one of the available choices views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): form_class = UserUpdateForm template_name = 'users/modals/update_profile_modal.html' success_message = "User updated successfully." def get_form_kwargs(self): kw = super().get_form_kwargs() kw['request'] = self.request return kw def get_object(self, *args, **kwargs): user_id = self.request.session['user_detail'] return TbUser.objects.get(id=user_id) def form_invalid(self, form): messages.error(self.request, form.errors) print(form.errors) return redirect('user-detail', pk=self.object.pk) def get_success_url(self): return reverse('user-detail', kwargs={'pk': self.object.pk}) forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if request.user.customer: self.fields['department'].queryset = TbDepartment.objects.filter( customer=request.user.customer) self.fields['role'].queryset = TbRole.objects.filter( customer=request.user.customer) self.fields['username'].required = True self.fields['real_name'].required = True self.fields['email'].required = True self.fields['cellphone'].required = True self.fields['department'].required = True self.fields['role'].required = True class Meta: model = TbUser fields = ['username', 'real_name', 'email', 'cellphone', 'department', 'role'] -
A platform to create a system for managing data and users with proper access to data and related actions
I want to create a website for a company to handle its workflow. The company has some data and its users should work on that. There are some different kind of user such as regular with limited access, manager with full access, expert with some access to data and ... Also they can do something with data and modify data. Also there is a workflow, ie regular user submits a form and manager see the form and add something else to data and pass it to expert and ... Is there a platform to create such a system like CMS platforms? -
DJANGO settings using namedtuple
I want to create a variable of type namedtuple in Django settings: SCHEMA_VERSION: namedtuple = config("SCHEMA_VERSION", cast=namedtuple(typename="SCHEMA_VERSION", field_names=["subject", "schema_id", "version"], defaults=[None, None, None]), default=None) But when I want to use it in code below: result = ujson.loads(result) result = settings.SCHEMA_VERSION(**result) I get the following error: AttributeError: 'Settings' object has no attribute 'SCHEMA_VERSION' Of course, I import Django setting like this: from django.conf import settings What I'm doing wrong? -
Django convert postgresql query with Array and subquery to ORM
The problem is I can't convert this query to Django ORM select weekday, (array( select termdelay from call_schedule_history c_in where c_in.is_active and c.weekday = c_in.weekday order by 1 )) from call_schedule_history c where is_active group by 1, 2 I tried: history_in = History.objects.filter(weekday=OuterRef('pk')) history_out = History.objects.values('weekday').annotate( newest_commenters=ArrayFormat(history_in.values('termdelay')), ) but sql query of history_out is: select "call_schedule_history"."weekday", array(select U0."termdelay" from "call_schedule_history" U0 where U0."weekday" = "call_schedule_history"."id") as "newest_commenters" from "call_schedule_history" So how can I replace "call_schedule_history"."id" to "call_schedule_history"."weekday" in Django ORM? -
django rest framwokr. How i can filter quryset in range?
I need filtering data from get request in range: Here is my code: model.py class MainModel(TimeStampedModel): model_name = models.CharField(_("model_name"), max_length=240) model_price = models.DecimalField(_("model_price"), max_digits=8) class ModelAdditionalData_1(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data1', related_query_name='model_water_flow_data1' ) model_param_1 = models.models.DecimalField(_("model_param_1"), max_digits=8) class ModelAdditionalData_2(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data2', related_query_name='model_water_flow_data2' ) model_param_2 = models.models.DecimalField(_("model_param_2"), max_digits=8) view.py : class ModelsViewSet(ReadOnlyModelViewSet, GenericViewSet): serializer_class = ModelsSerializer def get_queryset(self): model_param_1 = self.request.query_params.get('model_param_1') model_param_2 = self.request.query_params.get('model_param_2') filters = {} if model_param_1: filters['model_water_flow_data1__model_param_1'] = model_param_1 if model_param_2: filters['model_water_flow_data2__model_param_2'] = model_param_2 if filters: return MainModel.objects.filter(**filters) return MainModel.objects.all() How i can apply my filters for filtering data in range? For example, i wont filtering data by model_param_1 betwen 1 and 10. -
UnboundLocalError at /accounts/register/
hi i was trying to check if a user with a same number is in my database , i show a error that this number is exists from before but ... UnboundLocalError at /accounts/register/ forms.py html views.py -
Django - retrieve objects from latest date for each group - PersonPhoto
My DB contains passport images of different people. Something like: class Person(models.Model): pass class PersonPhoto(models.Model): date_captured = models.DateField() person = models.ForeignKey(Person, null=False) I want to extract for each person all of the images from the latest date he was photographed. So if person A has photos from August 5, 5, 9, 11, 11, and person B has images from August 7, 9, 13, 13, 19, 19 then I want to fetch both images from August 11 for person A, and both images from August 19 for person B. The way I'm currently doing that is something like: specific_dates_queryset = Q() for photo in PersonPhoto.objects.all().annotate(max_date=Max('date_captured')).values('person_id'): specific_dates_queryset |= Q(person_id=photo["person_id"], date_captured=photo["max_date"]) for photo in PersonPhoto.objects.filter(specific_dates_queryset).order_by("person_id"): print(f"image for person {photo.person_id}, of date {photo.date_captured}") The idea is to first find the latest date of a photo for each person, and then in a new query to fetch these images for these people from these dates. Is there a simpler solution that does everything within the DB and avoids redundant queries and data fetching? -
GitHub Actions not picking up Django tests
I want to write a simple GitHub Action that runs my Django app's tests when I push to GitHub. GitHub runs the workflow on push, but for some reason, it doesn't pick up any of the tests, even though running python ./api/manage.py test locally works. The Run tests section of the Job summary shows this: 1s Run python ./api/manage.py test System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK 1s 2s 0s For background, my local setup is using docker-compose, with a dockerfile for each app. The Django app is the API. All I want to do is runn the django tests on push. I've come across GitHub service containers, and I thought they might be necessary since django needs a postgres db connection to run its tests. I'm new to GitHub Actions so any direction would be appreciated. My hunch is that it should be simpler than this, but below is my current .github/workflows/django.yml file: name: Django CI on: push: branches: [ master ] pull_request: branches: [ master ] jobs: tests: runs-on: ubuntu-latest container: python:3 services: # Label used to access the service container db: # Docker Hub image image: postgres # Provide the … -
Why does not template recognize my models field?
I have an app called ecommerce and I have already created the database and that's all I have to do is make the template. In the template I tried to create a dynamic navbar called "Categories"; But when I write "{{object.category}}" in 'for' loop, it don't work. Help me if you know where the problem is, thanks. this is my model: from django.db import models class CategoryManager(models.Manager): def active(self): return self.filter(status=True) class ProductManager(models.Manager): def published(self): return self.filter(status='p') class Category(models.Model): name = models.CharField(max_length=200, verbose_name = "title") slug = models.SlugField(max_length=100, unique=True, verbose_name = "slug") status = models.BooleanField(default=True, verbose_name= "to be displayed?") class Meta: verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name objects = CategoryManager() class Product(models.Model): CURRENCY_CHOICES = ( ('$', 'Dollar'), ('€', 'Euro'), ) STATUS_CHOICES = ( ('p', 'published'), ('d', 'drafted'), ) name = models.CharField(max_length=200, unique=True, verbose_name="product") category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) description = models.TextField(null=True, verbose_name = "description") thumbnail = models.ImageField(upload_to="images", verbose_name="image") slug = models.SlugField(max_length=100, unique=True, verbose_name="slug") price = models.DecimalField(decimal_places=2, max_digits=10) currency = models.CharField(max_length=1, choices=CURRENCY_CHOICES, verbose_name="currency") status = models.CharField(max_length=1, choices=STATUS_CHOICES, default="p", verbose_name="status") newprice = models.DecimalField(decimal_places=2, max_digits=10, null=True, blank=True) star = models.CharField(max_length=5, null=True, blank=True) class Meta: verbose_name = "product" verbose_name_plural = "products" ordering = ["-price"] def __str__(self): return self.name objects = … -
serviceworker.js pops up when main path
in my website, I have tried to implement PWA using django-pwa, but it works only in localhost, and when i try to open live, text of serviceworker.js pops up. here is my serviceworker.js: var staticCacheName = 'jalarambooks-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); -
if and else - both are executing
I am building a simple question answer site, in which - I am trying to implement a like button But When i like the post then solid liked button is showing and blank liked button is also showing. models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title= models.CharField(max_length=300) class Answer(models.Model): user_by = models.ForeignKey(User, on_delete=models.CASCADE) que = models.ForeignKey(Question, on_delete=models.CASCADE) body = models.CharField(max_length=300) class LikeAnswer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.ForeignKey(Answer, on_delete=models.CASCADE) views.py def question_detail(request, question_id): obj = get_object_or_404(Question, pk=question_id) answers = obj.answer_set.all() context = {'obj':obj,'answers':answers} return render(request, 'question_detail.html', context) quesion_detail.html {{obj.title}} {% for anss in answers %} {% for lks in anss.likeanswer_set.all %} {% if request.user == lks.user %} <button name='submit' type='submit' id="unlike" value="unlike">Unlike </button> {% else %} <button name='submit' type='submit' id="like" value="like"> </button> {% endif %} {% endfor %} {% endfor %} What i am trying to do :- I am trying to show only filled like button after user like, But it is showing both buttons. I have also tried {% empty %} but it didn't made impact on it, It showed same results. Any help would be much Appreciated. Thank You in Advance. -
How do I make Django write the links to pages correctly?
I've set up my Django project website which is a maze generator, to have a navbar which buttons link to other pages I've made. For example, the style page's directory is just /style, so it brings up the page with which reference is styles, then if I click the homepage button on the navbar it goes to /home all good. But when I go to the individual maze pages which references is just a number(for example 3), if I click the navbar button to go to home instead of going to http://127.0.0.1:8000/home it tries going to http://127.0.0.1:8000/3/home which doesn't exist. Is there a way to change how Django processes the links to remove the directory before it. navbar html code urls page in django -
how to get values from admin panel to dashboard
hello i am trying to take all data from admin panel to the dashboard everything works well but only one filed doesnot work manytomanyfield [![enter image description here][1]][1] here is code of models and views class HumanSkills(models.Model): department = models.ForeignKey(Departments, on_delete=models.CASCADE, null=True) human_skills = models.ManyToManyField(HumanSkills, null=False) image = models.ImageField(upload_to='images', null=True) def __str__(self): return self.first_name + ' ' + self.last_name this is now views from .models import Document def dashboard(request): context = { 'posts': Document.objects.all() } return render(request, 'blog/home.html', context) and this is templates [![``` [1]: https://i.stack.imgur.com/HyrK0.png [2]: https://i.stack.imgur.com/LsKc8.png -
Django: Avoid clash of port 8000 (runserver)
I develop on serveral projects at once. If I run the runserver twice, I get this error: System check identified no issues (0 silenced). September 10, 2021 - 10:44:26 Django version 3.1.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. I know that I can supply a different port manually, but a more automatic approach would be nice. How could I solve this clash without manually giving each project a port by hand? -
Django Model Class With Temporary Non-Model Field
Not sure if I am on a completely wrong track, but I want some kind of a temporary runtime variable/field in my Django model. Currently I have this: class BioChemicalProperties(models.Model): mw = models.FloatField(blank=True, null=True) iep = models.FloatField(blank=True, null=True) exco = models.FloatField(blank=True, null=True) molar_exco = models.FloatField(blank=True, null=True) e01 = models.FloatField(blank=True, null=True) def get_protein(self): aa_seq = self.ab.get_lc_protein() aa_seq += self.ab.get_hc_protein() return aa_seq def calc_mw(self, aa_seq=None): if not aa_seq: aa_seq = self.get_protein() analysed_seq = ProteinAnalysis(aa_seq) self.mw = analysed_seq.molecular_weight() + 18.015 def calc_exco(self, aa_seq=None): if not aa_seq: aa_seq = self.get_protein() analysed_seq = ProteinAnalysis(aa_seq) self.exco = analysed_seq.molar_extinction_coefficient()[1] #...more methods here... def calc_all_bioprops(self, aa_seq=None): if not aa_seq: aa_seq = self.get_protein() self.calc_mw(aa_seq) self.calc_iep(aa_seq) self.calc_molexco(aa_seq) self.calc_e01(aa_seq) The aa_seq variable is a temporary value that should not be stored in the database. Nevertheless, to not re-compute the value for each method when multiple methods are to be used, I want to optionally give it as a parameter. I see that giving the aa_seq as a parameter in each method is redundant and also not object-oriented. Now I wonder if it is a good idea (and possible at all) to store it as a class property like: class BioChemicalProperties(models.Model): mw = models.FloatField(blank=True, null=True) iep = models.FloatField(blank=True, null=True) exco = models.FloatField(blank=True, … -
Populate form values from database Django
I am trying to fetch data from database to update and save. I am able to add the data. Since I am trying to do this in class view I don't know how to use generic.Updateview and grab the entry by the id. Here is the FormView I use to submit the data class CompanyView(generic.FormView): form_class = CompanyForm template_name = 'company/company.html' success_url = '/company' def form_valid(self, form): form.save() return super().form_valid(form) I listed the details by adding a edit button to each entry and wrote a view like the same one, but stuck with populating the data with corresponding id. How can I modify this to make the edit ? -
Reverse for 'product_by_catagory' with arguments '('d', 'r', 'e', 's', 's')' not found. 1 pattern(s) tried: ['(?P<c_slug>[-a-zA-Z0-9_]+)\\/$']
urls.py from django.urls import path from . import views app_name='shop' urlpatterns = [ path('',views.allproduct,name='allproductcat'), path('<slug:c_slug>/',views.allproduct,name='product_by_catagory') ] views.py from django.shortcuts import render, get_object_or_404 from . models import catagory,product # Create your views here. def allproduct(request,c_slug=None): c_page=None products=None if c_slug!=None: c_page=get_object_or_404(catagory,slug=c_slug) products=product.objects.all().filter(catagory=c_page,available=True) else: products=product.objects.all().filter(available=True) return render(request,'catagory.html',{'catagory':c_page,'products':products}) catagory.html {% extends 'base.html' %} {% load static %} {% block metadiscription %} {% if catagory %} {{catagory.discription}} {% else %} welcome {% endif %} {% endblock %} {% block title %} {% if catagory %} {{catagory.name}}--ABC store {% else %} see our new collection {% endif %} {% endblock %} {% block content %} {% if catagory %} <div> <div> <a href="{% url 'shop:allproduct' %}">OUR PRODUCT COLLECTION</a> </div> </div> {% endif %} <div> {% if catagory %} <img src="{{catagory.img.url}}" alt="{{catagory.name}}"> </div> <br> <div> <h1> {{catagory.name}} </h1> <p> {{catagory.discription}} </p> </div> {% else %} <div> <img src="{% static 'img/banner.png' %}"> </div> <br> <div> <h1>OUR PRODUCT COLLECTION</h1> <p>INDIA IS MY COUNTRY I LOVE MY COUNTRY</p> </div> {% endif %} <div> <div> {% for product in products %} <div> <div> <a href="" ><img src="{{product.img.url}}"></a> <div> <h4>{{product.name}}</h4> <p>{{product.price}}</p> </div> </div> </div> {% endfor %} </div> </div> {% endblock %} navbar.html <nav> <ul> <li><a href="{% url 'shop:allproductcat' %}">ALL PRODUCTS</a></li> {% … -
No url is responding while making a ajax post request in Django
Hey I am trying to implement a like feature on videos in django with the help of ajax. But when I click on the like icon then server is not trying to post the data on any url and not showing any error or successful attempt. Thus like count remains unchanged. views.py class DetailVideo(View): def get(self, request, pk, *args, **kwargs): video = Video.objects.get(pk=pk) form = CommentForm() comments = Comment.objects.filter(video=video).order_by('-created_on') categories = Video.objects.filter(category=video.category)[:15] context = { 'object': video, 'comments': comments, 'form': form, 'categories': categories } return render(request, 'courses/detail_video.html', context) def post(self, request, pk, *args, **kwargs): video = Video.objects.get(pk=pk) form = CommentForm(request.POST) if form.is_valid(): comment = Comment( user=self.request.user, comment=form.cleaned_data['comment'], video=video ) comment.save() comments = Comment.objects.filter(video=video).order_by('-created_on') categories = Video.objects.filter(category=video.category)[:15] context = { 'object': video, 'comments': comments, 'form': form, 'categories': categories } return render(request, 'courses/detail_video.html', context) class Like(View): def post(self, request, *args, **kwargs): if request.POST.get('action') == 'post' and request.is_ajax(): result = '' pk = int(request.Post.get('videoid')) video = get_object_or_404(Video, pk = pk) if video.likes.filter(pk=request.user.pk).exsits(): video.likes.remove(request.user) video.like_count -= 1 result = video.like_count video.save() else: video.likes.add(request.user) video.like_count += 1 result = video.like_count video.save() return JsonResponse({'result': result}) urls.py app_name = "courses" urlpatterns = [ path('', views.Index.as_view(), name = "home"), path('user-uploads/<str:username>', views.UserUploads.as_view(), name = "user-uploads"), path('create-video', CreateVideo.as_view(), name='video-create'), path('<int:pk>/', … -
How can I use the data in a django form in a different view
I am integrating mpesa api in my django project and I need to pass the phone number dynamically so I have created a form that asks for users phone number which i want that entered data to be passed in the mpesa credentials view. Below is the view for the form: def mpesaNumber(request): if request.method == 'POST': form = phoneNumber(request.POST, request.FILES) if form.is_valid(): phone =form.cleaned_data.get('phone_number') PhoneNumber.objects.get_or_create(phone_number=phone) return redirect('make_payment') else: form = phoneNumber() context = {"form":form} return render(request, 'users/phoneNumber.html', context) Below is the mpesa view def lipa_na_mpesa_online(request): data = cartData(request) order = data['order'] access_token = MpesaAccessToken.validated_mpesa_access_token api_url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest" headers = {"Authorization": "Bearer %s" % access_token} request = { "BusinessShortCode": LipanaMpesaPpassword.Business_short_code, "Password": LipanaMpesaPpassword.decode_password, "Timestamp": LipanaMpesaPpassword.lipa_time, "TransactionType": "CustomerPayBillOnline", "Amount": float(order.cart_totals), "PartyA": phone_number, # replace with your phone number to get stk push "PartyB": LipanaMpesaPpassword.Business_short_code, "PhoneNumber": phone_number, # replace with your phone number to get stk push "CallBackURL": "https://sandbox.safaricom.co.ke/mpesa/", "AccountReference": "Victor", "TransactionDesc": "Testing stk push" } response = requests.post(api_url, json=request, headers=headers) return HttpResponse('success') Below is my phone number form template {% extends "store/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="mt-4"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Submit</button> </form> </div> {% endblock %} and … -
Unable to pass data to Django views using fetch() in js after PayPal
I have some problems to insert new order records to database using PayPal. There is no problem to make payment using PayPal. But, when I was trying to pass the POST data to django views. There is nothing shown. Then, I try to print some value in the views.py but there is still nothing displayed. So, I think the functions in views.py is not triggered and there might be a problem inside the fetch() but I can't find out the problem. Can you guys please help me to see where is the problem. Thank you. Javascript var total = '{{ amount|floatformat:2 }}' function initPayPalButton() { paypal.Buttons({ style: { shape: 'pill', color: 'blue', layout: 'vertical', label: 'paypal', }, createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{"amount":{"currency_code":"MYR","value":total}}], application_context: { shipping_preference: 'NO_SHIPPING' } }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(orderData) { submitFormData(); window.alert('Payment Success') }); }, onError: function(err) { console.log(err); } }).render('#paypal-button-container'); } initPayPalButton(); submitFormData() function submitFormData(){ var url = "/checkout/" fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({ 'email': document.getElementById("txtEmail").value.rstrip(), 'phoneNo': document.getElementById("txtPhoneNo").value.rstrip(), }), }) .then((response) => response.json()) .then((data) => { window.location.href = "{% url 'ecommerce:checkout' %}" }) } urls.py path('checkout/', OrderSummaryView.as_view(), name='checkout'), views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): ... … -
Django custom queryset with pre-filter
Is there a way in django to write a custom queryset class that has a filter "pre-applied" without having to call a method on it? I want to create a manager using QuerySet.as_manager(). But I want that manager to automatically filter out some entries. -
How to call another app view from an app - Django Hosts
I'am using Django hosts for my apps. So my auth app - where registration and authentication is done - is accessed by auth.localhost:800/something. So after a user logs in, how can I redirect the user to the dashboard app which is being handled by dashboard.localhost:8000? Sorry if these explanations aren't enough. Please let me know if more information is required. -
CharField(). Select a valid choice. That choice is not one of the available choices
Models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.ForeignKey(Category ,max_length=60 ,default='Others', on_delete=models.CASCADE, related_name= 'cats') def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) Forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'author', 'category', 'body') widgets = { 'title': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Title'}), 'author': forms.TextInput(attrs={'class':'form-control', 'value':'', 'id':'author_id'}), 'category': forms.Select(choices=choice_list, attrs={'class':'form-select'}), 'body': forms.Textarea(attrs={'class':'form-control', 'placeholder':'Enter Main Content'}), } Getting Error at Title Field when trying to fill-up the form from the webpage. Tried the solutions that were available at other posts but still stuck up here. Any help would be appreciated.