Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Swagger internal error 500 with django api
I'm reading all the post about the error 500 internal server with swagger and following the doc of swagger I added the schema_view and pathed it to /doc/. router = routers.DefaultRouter() router.register(r'Resor', views.ResortViewSet, basename='resorts') router.register(r'slopes', views.SlopesViewSet, basename='slopes') router.register(r'forfaits', views.ForfaitViewSet, basename='forfaits') router.register(r'cities', views.CityViewSet, basename='cities') schema_view = get_swagger_view(title='ApiDoc') urlpatterns = [ path('', include(router.urls)), path('doc/', schema_view), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In settings.py I setted to false the debug mode because it wouldn't work anyway and for testing I used '*' in allowed hots. Any ideas about why is this error? -
How not to log out user from all devices on logout?
My users will tend to log in on multiple devices simultaneously. However, I've found that both django-rest-auth and dj-rest-auth serves the same token when logging in, so if a user logs out, he gets logged out from all the devices. I'm trying to figure out how to get separate auth tokens for separate logins with the same account. Any ideas? -
Two Subdomains with one django project
Say I have two subdomains on aws ebs and I want them run different django apps in the same project: django1.mywebsite.com django2.mywebsite.com Would I have to create two django projects and deploy seperately, or is there someway I could make the first subdomain only work with one django app and the other with the other django app? Does this make sense? The reason I want them in the same django project is because the two apps share the same DB and there is overlap in the models that they use. Perhaps is there a better way to achieve what I want to accomplish? Thanks!!! -
Proper logging configuration to disable django error emails
I just got sentry working in my environment and I tried tweaking my logging to make it stop sending error emails, but it still is and I don't understand why. My logging config is: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": '%(levelname)s %(asctime)s (%(pathname)s %(funcName)s): "%(message)s"' }, "simple": {"format": "%(levelname)s %(message)s"}, "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[%(server_time)s] %(message)s", }, }, "handlers": { "null": {"level": "DEBUG", "class": "logging.NullHandler",}, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "simple", }, "log_file": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "filename": "/var/log/courtlistener/django.log", "maxBytes": "16777216", # 16 megabytes "formatter": "verbose", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, }, "loggers": { # Disable SuspiciousOperation.DisallowedHost exception ("Invalid # HTTP_HOST" header messages.) This appears to be caused by clients that # don't support SNI, and which are browsing to other domains on the # server. The most relevant bad client is the googlebot. "django.security.DisallowedHost": { "handlers": ["null"], "propagate": False, }, "django.server": { "handlers": ["django.server"], "level": "INFO", "propagate": False, }, # This is the one that's used practically everywhere in the code. "cl": {"handlers": ["log_file"], "level": "INFO", "propagate": True,}, }, } Is there a missing piece here? I don't know how that'd possibly send emails. … -
Implications of deleting schema from postgreSQL database
I have had some errors recently which are ProgrammingErrors. It says: Internal Server Error: /phone-verification/ ProgrammingError at /phone-verification/ column quiz_sitting.percent_correct does not exist LINE 1: ...rrect_questions", "quiz_sitting"."current_score", "quiz_sitt... ^ The model which it is speaking of called quiz_sitting I assume is this one which is actually called Sitting but has a foreign key to quiz: class Sitting(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_("User"), on_delete=models.CASCADE) quiz = models.ForeignKey( Quiz, verbose_name=_("Quiz"), on_delete=models.CASCADE) percent_correct = models.IntegerField(null=True, verbose_name=_("Percent Correct")) This error seems to be only happening on one schema and I think I have fixed the issue outside of this. But it is causing me to not be able to delete the schema from the admin panel. Is it okay to erase this schema from psql? Or will there be other issues which occur if I do this? Seems not but I want to be sure. -
Configure Ngnix with Django and Gunicorn
I have the Nginx code below. It sort of works. If I enter 'https://' to go to the site, the SSL kicks in. However, if I just enter www.thaifoodbypla.com, it does not re-direct to HTTPS, it just loads HTTP. Nginx config: upstream gunicorn{ # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). # for UNIX domain socket setups: server unix:/home/ubuntu/thaiFoodByPla/project.sock fail_timeout=0; # for TCP setups, point these to your backend servers # server 127.0.0.1:9000 fail_timeout=0; } server { listen 80; listen 443 ssl http2; server_name www.thaifoodbypla.com; ssl_certificate /etc/ssl/private/ssl-bundle.crt; ssl_certificate_key /etc/ssl/private/briefing_key.pem; # path for static files root /home/ubuntu/thaiFoodByPla/project/project; location / { # checks for static file, if not found proxy to app try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # When Nginx is handling SSL it is helpful to pass the protocol information # to Gunicorn. Many web frameworks use this information to generate URLs. # Without this information, the application may mistakenly generate http # URLs in https responses, leading to mixed content warnings or broken # applications. In this case, configure Nginx to … -
How to link to user's profile on django
I have been trying to link to user's profile page but everytime I try it, it returns a 404 error. I dont know but maybe the error is on the urls.py file. views.py def profile(request, username=None): if username: post_owner = get_object_or_404(User, username=username) else: post_owner = request.user args1 = { 'post_owner': post_owner, } return render(request, 'profile.html', args1) urls.py urlpatterns = [ path('<str:username>/', views.profile, name='profile'), path('login', views.login, name='login'), path('register', views.register, name='register'), path('logout', views.logout, name='logout'), ] index.html <a class="nav-link" href="{{ request.user }}">{{ user.username }}</a> -
Django: Run a function if certain condition is met
I have a Word model, where a user can add words and various fields, like this (shortened version): class Word(models.Model): target_word = models.CharField() source_word = models.CharField() add_to_review = models.BooleanField(default=True) example_sentence = models.CharField() image = models.ImageField(upload_to='images/',blank=True) audio = models.FileField(upload_to='audio/',blank=True) I also have a Flashcard model where a user can add and study flashcards. Here I show only the relevant code: class FlashcardManager(models.Manager): def create_flashcard(self, user, question, answer, deck_name): try: deck = Deck.objects.get(owner=user, name=deck_name) except ObjectDoesNotExist: deck = Deck(owner=user, name=deck_name) deck.save() self.create(owner=user, question=question, answer=answer, deck=deck) return deck class Flashcard(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) deck = models.ForeignKey(Deck, on_delete=models.CASCADE) question = models.TextField() answer = models.TextField() created_at = models.DateTimeField(auto_now_add=True) last_shown_at = models.DateTimeField(auto_now_add=True) next_due_date = models.DateTimeField(default=timezone.now) difficulty = models.FloatField(default=2.5) consec_correct_answers = models.IntegerField(default=0) objects = FlashcardManager() def __str__(self): return self.question When a user creates a new word, I want to give them the option of automatically creating a flashcard using the info provided. In other words, question = target_word, answer = source_word, and the deck name can either be some default value, or I can add a field to the Word model. Is there a way I can do this by using the add_to_review field of the Word model and the create_flashcard method of the FlashcardManager model? … -
Custom user manager: only required fields being populated
I switched to a custom user manager to use email as a username. Since making that change, all fields aside from email and password are not being populated on register, eg, a user is created but has no first_name, last_name, etc. I was under the impression django classes could be overridden on a field fo field basis without disrupting other fields. Is that not the case? Manager: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) Serializer: class RegisterSerializer(serializers.ModelSerializer): class Meta: User = get_user_model() model = User fields = ('first_name', 'last_name', 'email', 'password', 'startTime', 'groups') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): request … -
Using a primary key within a form view (Django)
I have a form that is associated with a model, and want to specify the form data using the model's PK to log the response. However, when I do this, I get the error: QuestionRecordSubmitView() got an unexpected keyword argument 'pk' urls.py path('survey/<int:pk>/record_submit_question/', views.QuestionRecordSubmitView, name='survey-question-submit-record') views.py def QuestionRecordSubmitView(request): model = Question if request.method == 'POST': form = PostAudio(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('survey-share', kwargs={"pk": form.question})) else: form = PostAudio() return render(request, 'survey/question_audio_submit.html') models.py class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) response_file = models.FileField(blank=True, upload_to='audio_responses') def save(self, *args, **kwargs): super().save(*args, **kwargs) forms.py class PostAudio(forms.ModelForm): class Meta: model = Choice fields = ('response_file',) -
Recucurrences dates with ICalendar RRULE with Python vs Javascript?
I'm build an application with django that is not similar to google calendar, bu it a booking application and I need create frequencies rules and storage it in the database to display a calendar with available date. My question are this: What the below option is better? Do you recommend other better options? I want to use two library dateutils > https://pypi.org/project/python-dateutil/ rrule.js > https://github.com/jakubroztocil/rrule Note: I have installed django-recurrence to test it Option 1 I Use python library to validate available date in backend and use rrule.js in frontend Option 2 I use python library to validate available date in backend and calculate recurrence rule and send a list of dates in objects Json to process in a javascript and display in calendar the available dates. I know the first approach distributes the work between server side and client side, however the second option the work is responsibility the server. -
How to create a record that contains a user in Django test setUp
I have this model in my Django application: class ClubSession(models.Model): location = models.CharField(max_length=200) coach = models.ForeignKey('auth.User', on_delete=models.CASCADE) date = models.DateTimeField(default=now) details = models.TextField() def __str__(self): return self.location This view implements it: class SessionListView(ListView): model = ClubSession template_name = 'club_sessions.html' context_object_name = 'all_club_sessions_list' I'm trying to test the view. My test class has a setUp which creates a record: def setUp(self): ClubSession.objects.create(location='test location', coach=User(id=1), date='2020-06-01 18:30', details='this is another test') When I run my test I get this error: IntegrityError: The row in table 'club_sessions_clubsession' with primary key '1' has an invalid foreign key: club_sessions_clubsession.coach_id contains a value '1' that does not have a corresponding value in auth_user.id. A user with id 1 exists so how do I get this to work? I've tried adding the username but that didn't work either. -
Django and crispy form, how to add id and name in the crispy Layout
I'm trying to use the crispy form in my template, but I have a problem to hold name, id and class in the layout. In other words I have the following templates: <div class="modal-body"> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> </div> So I want to delete the input row and add the crispy field holding id="form-conto" name="formConto". I know that I have to add the layout in my Model.forms but I do not understand how get it. This is my form: class MaterialeForm(forms.ModelForm): class Meta: model = Materiale fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() And here my models: class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) -
For Django (using whitenoise) apps deployed on Heroku, am I supposed to collectstatic files locally, commit, then deploy to Heroku?
If I want to deploy a Django app on Heroku, am I supposed to do the following locally (STATIC_ROOT in settings.py is set to staticfiles): python manage.py collectstatic git add staticfiles/* git commit -m "Added the static files" git push heroku master Is this how it is supposed to work? It's the only way that made my only css file get picked up by the app, but I think it's strange because the static files are already in the repo. I tried: Using the django-heroku as suggested by the Heroku docs but it starts throwing 500 server error, and when checking the heroku logs it says manifest not found for my only css file. Manually running heroku run python manage.py collectstatic --clear --noinput but it returns the same result as the deployment command, and the css file is not picked up when I access the app. Any suggestions/pointers are very much appreciated. -
Changed django model then heroku app won’t show the new updates
I updated my Django model and my website runs just fine locally. However, when I deployed it to heroku, it doesn't display the new things that I've added on the template. I checked Django admin and my Postgres table and the data are there. This was running just fine but when I updated the model this happened. I also checked the migrations table in Postgres and I saw that the changed that I made in the model were there. Before deployment, I ran python manage.py makemigrations, python manage.py migrate, and finally heroku run python manage.py migrate and all changes to the model where migrated. Then since I've connected my github repo to my heroku app, the final step was I pushed it to github. I also didn't find any errors in my application log. Did I miss a step or anything? Here is my build log: -----> Python app detected -----> No change in requirements detected, installing from cache -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput 242 static files copied to '/tmp/build_c7d3574a89c64ead4253fd044003c3b3/staticfiles', 746 post-processed. -----> Discovering process types Procfile declares types -> web -----> Compressing... Done: 92.7M -----> Launching... Released v28 https://.herokuapp.com/ deployed … -
Upgrading to Django 3.0: 'django.contrib.admin.templatetags.admin_static': cannot import name 'RemovedInDjango30Warning'
My project was created with Django 2.2 and I would like to upgrade it to use 3. My problem is the same as django error cannot import name 'RemovedInDjango30Warning' . The accepted answer is to manually edit files in the Python packages which I don't think is a good practice(?). The other answers say to downgrade, so is there really no way to upgrade the project without creating it from scratch? -
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
hi i create a custom manager class called usermanager in monage.py to customise my login template for 2 types of user admin,entrepreneur #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os from django.contrib.auth.models import BaseUserManager import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oasisconsuting.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError("The given email must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault("is_staff", False) extra_fields.setdefault("is_superuser", False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self._create_user(email, password, **extra_fields) after running the makemigration (it's ok) when i run the migration code we receive the errors what is the wrong in this code to show me this errors : C:\Users\hp\PycharmProjects\business\Scripts\python.exe C:/Users/hp/PycharmProjects/business/oasisconsuting/manage.py runserver Traceback (most recent call … -
Redirect if query has no result
I've made a page with an input which connects to this view: class SearchResultView(ListView): model = RecipeSet template_name = 'core/set_result.html' context_object_name = 'recipe_set' def get_queryset(self): query = self.request.GET.get('q') object_list = RecipeSet.objects.filter( Q(set_name__exact=query) ) if object_list.exists(): return object_list else: return redirect('core:dashboard') I've used set_name__exact for this query and want to redirect users if the search returned no objects, how do I go about this? I've tried to use an if/else statement to check the objects but that doesn't seem to work. -
Cannot assign "'Math'": "SubjectClas.subject" must be a "Subject" instance
So, I have some problems witn my django project. Im wanting to assign Subject from droplist(that formed from database called Subject) to another database called SubjectClas but Im keep getting this error. Any suggestions? Thanks. Cannot assign "'Math'": "SubjectClas.subject" must be a "Subject" instance. My code from html {% block add %} <form action="{% url 'marks:addsubject' class.id%}" method="POST"> {% csrf_token %} <select required name="sub"> {% for d in subjectslist %} <option value='{{d.id}}'>{{d.SubjectName}}</option> {% endfor %} </select> <button type="submit">готово</button> </form> {% endblock %} My models.py from django.db import models class Class(models.Model): classtitle = models.CharField('класс', max_length = 50) def __str__(self): return self.classtitle class Subject(models.Model): SubjectName = models.CharField('Предмет', max_length =50) def __str__(self): return self.SubjectName class SubjectClas(models.Model): subject = models.ForeignKey(Subject, null=True, on_delete= models.SET_NULL) clas = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL) My views.py def addsubject(request, classid): try: a = Class.objects.get( id = classid ) except: raise Http404("Http404") SubjectClas.objects.create(subject = request.POST['sub'], clas = a) Thanks. -
Waypoints infinite scroll function gets triggered but doesn't load in django
So I wanted to add infinite scroll to one of my pages and found a very helpfull article on it:https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html I fallowed all the steps but at the end I couldn't get it to work. The problem occures in two different ways; sometimes the function keeps triggering forever and views.py keeps rendering request but nothing is loaded or it only triggers once and doesn't load anything at neither. I'm not sharing the whole function as it works fine while performing a standart pagination. I think the only part I need to tell is that in html I do not iterate over the paginator list but instead I use another list that my code creates by modifying query objects. I do not know if that is the problem. Html code: {% extends "layout.html" %} {% load static %} {% block body %} <h1 class=yazar>{{yazar}}</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus auctor pharetra purus in viverra. Suspendisse nec sem eget urna blandit malesuada. Duis pellentesque nibh vel rutrum placerat ligula.</p> <div class=yazar-top> <a class=t-holder href=""> <p class=p1>takipçiler</p> <b class=b1>{{follow}}</b> </a> <a class=t-holder href=""> <p class=p1>takip ettikleri</p> <b class=b1>{{followed}}</b> </a> <a class=t-holder href=""> <p class=p1>başlıkları</p> <b class=b1>{{titles}}</b> </a> <a class=t-holder2 … -
javascript Client side validation in Django
i am using Django. I have a template with two input fields and one button. the html code as follows: the page will show results of search in same page itself. search.html <form method="get"> <input type="text" id="search" name="search"> <input type="text" id="areasearch" name="asearch" ><hr> <button type="submit" id="search" onclick="enteranyone()">Search</button> </form> <p id="note"></p> <script> function enteranyone() { var sub = document.getElementById("subsearch"); var area = document.getElementById("areasearch") if (sub.value=="") { document.getElementById("note").innerHTML = "subject or area required"; return false } } </script> I want to do client side validation, that any one of the input must be filled. I tired the above code, its working, but not staying for few sec also. how to do overcome this? should i have to do anything in views.py file? following is code in views.py def search(request): a=request.GET.get("search",None) b=request.GET.get("asearch",None) if a or b: trail=Trial.objects.filter(name__icontains=a,data__icontains=b) context={'trail':trail} return render(request,'search.html',context) I want to display "subject or area required" when both input fields are empty. it showing for few sec then disappering. -
Show/Hide dropdown menu based on previous selection
I would like to show an additional dropdown menu based on a user's selection. Using my case, if a user selects installments an additional dropdown menu would appear, it would then be hidden if the user changes its selection. This is what I have tried <select name='installments' required class="form-control my-2" onclick="choose()"> <option value="" disabled selected hidden>How would you like to pay?</option> {% for value, name in form.fields.installments.choices %} <option value="{{value}}">{{name}}</option> {% endfor %} </select> <!-- if installments --> <select name='installnum' class="form-control my-2" style="display:none"> <option value="" disabled selected hidden>How many months would you like to pay this over?</option> {% for value, name in form.fields.installmnum.choices %} <option value="{{value}}">{{name}}</option> {% endfor %} </select> This is the javascript I wrote <script> function choose() { if (document.getElementById('installments').value == 'installments') { document.getElementsById('installnum').style.display == 'block'; } else { document.getElementById('installnum').style.display = 'none'; } } </script> The idea is supposed to be if you select installments the dropdown menu installnum would appear This is my forms.py with the list of options for each dropdown menu installment_choices = ( ('upfront', 'Upfront'), ('installments', 'Installments'), ) installnum_choices = ( ('2', '2 months'), ('3', '3 months'), ('4', '4 months'), ('5', '5 months'), ('6', '6 months'), ('7', '7 months'), ('8', '8 months'), ('9', '9 … -
For Django (with whitenoise) apps deployed on Heroku, am I supposed to collectstatic files locally, commit, then deploy to Heroku?
As the question says. If I want to deploy a Django app on Heroku, am I supposed to do the following locally? (STATIC_ROOT in settings.py is set to staticfiles: python manage.py collectstatic git add staticfiles/* git commit -m "Added the static files" git push heroku master This is the only way I was able to make the static files (just 1 css) show up on the Heroku app. But I find it a bit strange since the files are already in the repo in other places. I tried to rely on Heroku magically performing collectstatic and I tried to do that on the Heroku instance manually but nothing worked. The css file is never found otherwise (which indicates an issue with collectstatic I suppose?) I also tried using the django-heroku helper app but it was causing strange 500 errors and was adding more issues than what's already there. Locally everything works fine, even with DEBUG set to False, so I suppose whitenoise is not at fault here? -
django how to load url but stay on same page
I have a sign up button on my home page and when user clicks it, it opens sign-up modal form. The problem is I need to have a URL and view for sign-up form and when I click the button server redirects to signup URL and quits from my home page. How can I prevent this? --Views.py def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): #Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) #Set the chosen password new_user.set_password(user_form.cleaned_data['password']) #Save the user object new_user.save() return redirect('home') else: user_form = UserRegistrationForm() return render(request,'account/signup.html',{'user_form':user_form}) --urls.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(authentication_form=LoginForm), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('signup/', user_views.register, name='signup'), ] --signup.js var signup_form = document.querySelector(".signup-form"); var trigger = document.querySelector(".signup-btn"); var closeBtn = document.querySelector(".close-btn"); function toggleModal(){ signup_form.classList.toggle("show-signup-form"); } function windowOnClick(event) { if (event.target == signup_form){ toggleModal(); } } trigger.addEventListener("click", toggleModal); closeBtn.addEventListener("click", toggleModal); window.addEventListener("click", windowOnClick); -
AttributeError when returning post.title in a comment model
I was working on a comment section for post and was getting an AttributeError when I return return '{}-{}'.format(self.post.title, str(self.user.username)) in the comment model I am trying to link users and posts to the comment I am getting the same error Here is the Models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=160) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{}-{}'.format(self.post.title, str(self.user.username)) Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, slug=self.kwargs['slug']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect("post_detail.html") else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context class PostCommentCreateView(LoginRequiredMixin, CreateView): model = Comment form_class = CommentForm def form_valid(self, form): post = get_object_or_404(Post, slug=self.kwargs['slug']) form.instance.user = self.request.user form.instance.post = post return super().form_valid(form) def form_invalid(self, form): return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('score:post-detail', kwargs=dict(slug=self.kwargs['slug']))