Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get my like button in django to work?
I am trying to get my like button to work on my website. You can make "tweets" on my website, but users are not able to like the post. I already have the front end set up with ajax. that works perfect. The problem lies in my views. Here is my models class Tweet(models.Model): tweet_user = models.ForeignKey(User, on_delete=models.CASCADE) tweet_message = models.TextField() tweet_date = models.DateTimeField(auto_now_add=True) tweet_like_counter = models.IntegerField(default=0) tweet_picture = models.FileField(null=True,blank=True) def __str__(self): return self.tweet_message class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class Disike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey(Tweet, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweet.tweet_message class TweetComment(models.Model): class Meta: ordering = ['-id'] tweetcomment = models.ForeignKey(Tweet, on_delete=models.CASCADE, related_name='tweetcomments') tweetcommentauthor = models.ForeignKey(User,on_delete=models.CASCADE) tweetcommentmessage = models.TextField() tweetcommentcomment_date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tweetcommentmessage Here is my view from django.views.decorators.csrf import csrf_exempt @csrf_exempt @login_required def like(request, pk): currentTweet = get_object_or_404(Tweet,pk=pk) user = User.objects.get(pk=request.user.id) like = Like.objects.create(tweet=currentTweet, user=user) like_queryset = Like.objects.filter(tweet=currentTweet, user=user) dislike_queryset = Disike.objects.filter(tweet=currentTweet, user=user) if like_queryset.exists(): Like.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() if dislike_queryset.exists(): Disike.objects.filter(tweet=currentTweet, user=user).delete() dislikeobject = Disike.objects.filter(tweet=currentTweet).count() likeobject = Like.objects.filter(tweet=currentTweet).count() currentTweet.tweet_like_counter = likeobject - dislikeobject currentTweet.save() return JsonResponse({ 'like_counter': currentTweet.tweet_like_counter … -
Django login redirect to password reset page instead of profile page
I am new at django and building my first app. At this stage, I am trying to login with django without using a custom view function. Unfortunately, after creating users in the django admin page, and trying to login, I found that the login button redirects me to the password reset page having entered an invalid link. I don't know if the login have failed or succeeded. Thank you to take my question into consideration. I have looked for many similar problems, but never encountered the same situation. url from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #Add Django site authentication urls (for login, logout, password management) urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), path('accounts/login/', include('django.contrib.auth.urls'), name = 'login'), path('accounts/logout/', include('django.contrib.auth.urls'), name = 'logout'), path('accounts/password_change/', include('django.contrib.auth.urls'), name = 'password_change'), path('accounts/password_change/done/', include('django.contrib.auth.urls'), name = 'password_change_done'), path('accounts/password_reset/', include('django.contrib.auth.urls'), name = 'password_reset'), path('accounts/password_reset/done/', include('django.contrib.auth.urls'), name = 'password_reset_done'), path('accounts/reset/<uidb64>/<token>/', include('django.contrib.auth.urls'), name = 'password_reset_confirm'), path('accounts/reset/done/', include('django.contrib.auth.urls'),name='password_reset_complete') ] html base <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block title %} <title>Acceuil</title> {% endblock %} {% load static %} <link rel="stylesheet" type=text/css href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/menu.css' %}"> <link rel="stylesheet" type=text/css href="{% static 'css/style.css' %}"/> </head> <body> <section id="global"> {% block nav%} <!-- <nav … -
Django ModelForm shows "Select a valid choice. That choice is not one of the available choices" when I submit my ForeignKey field
I have a form where users can register the name of Cause Construct by selecting from a list of construct. Every time I try to submit, the field raises "Select a valid choice. That choice is not one of the available choices" Here are my models: class Construct(models.Model): name = models.CharField(max_length=200, help_text='Enter construct name') area = models.ForeignKey(AreaOfInterest, on_delete=models.CASCADE, related_name="construct") def __str__(self): return self.name class Cause(models.Model): name = models.ForeignKey(Construct, on_delete=models.CASCADE, related_name="cause") reference_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="cause_ref") observed_value = models.ForeignKey(Value, on_delete=models.CASCADE, related_name="cause_obs") def __str__(self): return self.name.name This is my form: class CauseForm(forms.ModelForm): def __init__(self, area, *args, **kwargs): super(CauseForm, self).__init__(*args, **kwargs) self.fields['name'].queryset = Construct.objects.filter(area=area) class Meta: model = Cause fields = '__all__' And this is my view: def new_theory(request, name): current_area = get_object_or_404(AreaOfInterest, name=name) if request.method == 'POST': causeform = CauseForm(current_area, request.POST) if causeform.is_valid(): newcause = causeform.save(commit=False) newcause.save() return redirect('area_of_interest', name=name) else: print(causeform.errors) else: causeform = CauseForm(current_area) return render(request, 'swetheory/createtheories.html', {'current_area': current_area, 'causeform': causeform}) How can I correctly submit my form? -
How to run a docker django app in my Centos VPS
I have a VPS and Docker with Django Application, How I can deploy and run it on my VPS in specified Domain? -
How to get all Django REST Framework permission classes?
After starting a Django shell using ./manage.py shell I can't see any of the custom permission subclasses in the application: In [1]: from rest_framework.permissions import BasePermission In [2]: BasePermission.__subclasses__() Out[2]: [rest_framework.permissions.AllowAny, rest_framework.permissions.IsAuthenticated, rest_framework.permissions.IsAdminUser, rest_framework.permissions.IsAuthenticatedOrReadOnly, rest_framework.permissions.DjangoModelPermissions] How can I get all the permission classes, including the custom ones? -
How can i display "Tags" feature implemented from my views.py to the template in DJANGO?
I have implemented a "Tag" feature but i am unable to show it in the template. As matter of fact, my query in the view show "None" as result when i try to debug it with PDB. I dont know what to do, it been a few days now. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete='models.CASCADE', related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post_detail', args=[self.publish.year,self.publish.month,self.publish.day,self.slug]) views.py from django.shortcuts import render, get_object_or_404 from .models import ( Post, Comment ) from django.core.paginator import ( Paginator, EmptyPage, PageNotAnInteger ) from django.views.generic import ( ListView, ) from .forms import ( EmailPostForm, CommentForm ) from django.core.mail import send_mail from taggit.models import Tag def post_list(request, tag_slug=None): """ Tags also included. """ page_posts = Post.published.all() # Tags tag = None if tag_slug: tag … -
Determine whether the user was authenticated in "LogoutView"
Django always show the same page when you go to 127.0.0.1:8000/admin/logout, whether you were logged-in before or not. What I want is showing a Logout Successful Message only if the user was authenticated before; and show an error message if the user wasn't authenticated and try logging out. I also need to include the user's first_name in my logout successful message. I am using class-based django.contrib.auth.views.LogoutView view like this: class SignoutView(LogoutView): template_name = "users/signout.html" def get_next_url(self): redirect_to = self.request.GET.get("next", "/") return redirect_to and here is the template: {% extends "base.html" %} {% block content %} <h1>Sign out Page</h1> <br> {% if was_authenticated %} <div class="alert alert-success" role="alert"> <h4 class="alert-heading">You have logged out from your account {{first_name|capfirst}}!</h4> <p>Thanks for spending some quality time with my web site today.</p> <hr> <p class="mb-0" id="displayTimer"></p> </div> {% else %} <div class="alert alert-danger" role="alert"> <h4 class="alert-heading">Ooh no!</h4> <p>Looks like you are not logged in! So you can not log out! Cool yeah?</p> </div> {% endif %} {% endblock %} {% block js %} {% if was_authenticated %} <script type="text/javascript"> var count = 5; var url = "{{redirect_address}}"; var countdown = setInterval(function() { $('#displayTimer').text("You will be redirected to the home page in " + count-- + … -
Django using ajax
I am finish with my project using django but I want it to be a asynchronous so I use jquery and ajax but i am stuck right now, The problem is when I add a product in the cart all of the product fields in the table are having the same values but when I refresh it came back to their own values. Can any body help me with this, I am new in using ajax. html link <a class="add-to-cart"href="{% url 'cart:add_cart' cart_item.product_format.id %}" class="custom_a" data-endpoint="{% url 'cart:add_cart' cart_item.product_format.id %}"><i class="fas fa-plus-circle custom_icon"></i></a> html table <td class="text-left"> <strong class="table-format"><span class="product-format">{{ cart_item.product_format.bformat }}</span></strong> <br> SKU: {{ cart_item.product_format.id }} <br> Unit Price: $<span class="cart-unit-price">{{cart_item.product_format.price}}</span> <br> Discount: <span class="cart-discount">{{cart_item.product_format.discount}}%</span> <br> Qty: <span class="cart-qty-price">{{ cart_item.quantity }} x ${{ cart_item.product_format.price }}</span> </td> <td class="text-primary"> <strong> <span class="cart-subtotal">${{ cart_item.sub_total|floatformat:2 }} </span></strong></td> script <script> $(document).ready(function(){ /* AJAX add to cart */ var cartAdd = $('.add-to-cart') cartAdd.unbind('click').click(function(event) { event.preventDefault(); var thisLink = $(this) var hrefEndpoint = thisLink.attr('data-endpoint') var addCartMethod = "GET" var linkData = thisLink.serialize(); $.ajax({ url: hrefEndpoint, method: addCartMethod, data: linkData, success: function(data){ console.log(hrefEndpoint) var productFormat = $('.product-format') var cartSubtotal = $('.cart-subtotal') var cartQtyPrice = $('.cart-qty-price') var cartDiscount = $('.cart-discount') var cartUnitPrice = $('.cart-unit-price') var cartTotal = … -
Use d3.queue() to load .tsvs when working within Django
I am trying to convert my old website to use Django. However, I don't know how to successfully load my data in d3 when working inside of Django frameworks. I know the D3 visualization works because it renders it on the old website frameworks. It appears to just be an issue of how do I properly call the pathing for the data files. I have tried various call methods to the files by making duplicate copies and placing them in different directories. But so far I can't figure out how to call the paths correct! Here is the original set of code: queue() .defer(d3.json, "../core/world_countries.json") .defer(d3.tsv, "worldData.tsv") .await(ready); Here are two different method calls I have tried queue() .defer(d3.json, "world_countries.json") .defer(d3.tsv, "{% static 'data/worldData.tsv' %}") .await(ready) 2 different errors occur: GET http://127.0.0.1:8000/web_app/world_countries.json 404 (Not Found) GET http://127.0.0.1:8000/web_app/%7B%%20static%20'data/worldData.tsv'%20%%7D 404 (Not Found) -
How to provide "add" option to a field in django admin?
In django admin i had one model named 'student', here it has three fields, NAME, ROLL NO. & SUBJECT. in models.py: from django.db import models class Student(models.Model): Name = models.CharField(max_length=255, blank = False) Roll_No = models.CharField(max_length=10, blank = False) Subject = models.CharField(max_length=20, blank = False) def __str__(self): return self.Name now i want this SUBJECT field to be Dynamic, like there will be "+" sign besides the SUBJECT field, by clicking that one more SUBJECT field will be added right after it and so on, but maximum 10 SUBJECT fields can be added like that. -
Will Xprinter - Xp-n160 || 80 mm OR Gprinter GP58L/UBL be compatible with my software in order to print the bill?
I have a billing web application that is built in React Js for front end and Django for backend (Django rest framework).I am setting up a new server, and want to support thermal POS printing in my web application. I want the application to print either from browser(Desktop) or browsers from mobile device. I have mentioned currently available printers. If these are not compatible, please suggest a compatible thermal printer. -
How send URL as response whenever user send post value in django rest framework?
Guys i want to return a URL of HTML page as response , when ever user send value by post method Actually the HTML page will contains data posted by user, But what actually happening is when user post data it opening that HTML page , code i tried class CoordView(viewsets.ModelViewSet): queryset = Coord.objects.all() renderer_classes = (TemplateHTMLRenderer,) serializer_class = CoordSerializer template_name = 'index.html' id = {'id':id } Response ('http://127.0.0.1:8000/detail/{{id}}') But I want to return that HTML page URL to user. -
Simple wagtail streamfield template not working
Its my template code: {% for post in page.get_children %} ONE {{ post.title }} <--- it shows correct, excepted title {% for block in post.body %} TWO <--- this is NEVER showen {% endfor %} {% endfor %} Its my BlogIndexPage: class BlogIndexPage(Page): body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), ] Its my BlogPage: class BlogPage(Page): date = models.DateField(auto_now=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) body = StreamField([ ('heading', blocks.CharBlock(classname="full title")), ('paragraph', blocks.RichTextBlock()), ('image', ImageChooserBlock()), ]) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), StreamFieldPanel('body'), ] I just cannot access to the block propeties, because post.body fells like empty array (I added BlogPage as child of BlogIndexPage, and I filled StreamField with some text, headings and pictures - it isn't empty) I am sure i am missing somehting obvious but I cannot see it myself. -
Django save object to db if condition met
I'm trying to use django pre_save signal to write the instance into db if a specific condition is met. How can I achieve this ? I'm having a function handler which is called by pre_save and I want to drop saving the instance if a condition is not met. I want to abort the whole save chain. Is it pre_save signal the proper way to do this ? -
Is it possible to save html2canvas image on page load automatically to directory without clicking a download button?
Guy i want to download html2canvas captured image automatically without pressing a download button manually , how to do ??? -
Where do I start
I am currently working as a Electrical Engineer for a mining company out of West Virginia. I have been given the task of creating a program that will do the following. Web Based User accounts and login Have a interactive mine map that allows objects to be placed on it and the map would be broke down into zones. The objects would be placed in these zones. They frequently move equipment from zone to zone. On this map we would be able to use a click and drag method to move the objects from one zone to the other. The objects should also be right clicked and show a menu that allows additional options such as electrical and hydraulic prints. These files are available in PDF. Finally, assign each member to a zone and have them complete the weekly exams on that equipment. A list will be available on their home page of what they are assigned. Using available sources, I have been able to create a basic web based application and a login server with python and Django. As far as everything else I don't know where to start. I spend more time searching for hours in one direction … -
How to get URL after form post request inside view.py function to use it in if else
I need to get current URL of the form post request and based on page URL return the corresponding template part In a views.py I just doubled the same function twice with a new name and it works but for the future when I have 5 or more URLs it will become a dirty code I have a two dirs / the main /dir/ the second and plan to add up to 10 new dirs I tried this, it works, but a lot of repetitive code #views.py def func_name(request): global context form = Form(request.POST or None) return render(request, 'home.html', context) def func_name_dir(request): global context form = Form(request.POST or None) return render(request, 'home.html', context) #urls.py urlpatterns = [ path('', func_name), path('ru/', func_name_dir), ] #I just want to use something like this to return right template #views.py def func_name(request): global context form = Form(request.POST or None) if url == '/dir/': return render(request, 'home-dir.html', context) elif url == '/dir1/': return render(request, 'home-dir1.html', context) else: return render(request, 'home.html', context) How to do this? -
Cannot add tags to frontend views Django queryset
I'm trying to add tags to my view from a query set column that looks like this for one observation like synonyms for great: ['fun, cool, awesome'] When I try to display as separated tags, it just prints as one block: 'fun, cool, awesome' This is what views.py looks like passing this data: class SynDetailView(generic.DetailView): model = Syn template_name = "synonoms/syn_detail.html" def get_context_data(self, **kwargs): context = super(SynDetailView, self).get_context_data(**kwargs) tags = Syn.objects.filter('synid'=self.kwargs.get('pk')).values_list('tags', flat=True) tags = str(tags) context['tags'] = [x.strip() for x in tags.split(',')] return context -
How can django channels communicate to other microservices?
We are developing microservices and communicating between them over rabbitmq. We would like to add a django app to the mix and currently are looking for elegant solutions. I have taken a look at django channels. While they are able to communicate over rabbitmq, I haven't found mentioning on how to send messages to specific exchange (and preferably with specific routing key as we are mostly using topic exchanges). asgi-rabbitmq seems to be the one translating between asgi (protocol used by channels) and amqp (protocol used by rabbitmq). From the docs, however, I only understood how to enable it - not how to actually use it to publish messages. Have I missed something? -
How to pass positional arguments to form submission on testing?
I have a signupView that shows 2 forms: SignUpForm and ProfileForm. Basically, SignUpForm collects data like first_name, last_name, user_name, email, password1, password2. And ProfileForm collects data like dni, birthdate, shipping_address, etc. ProfileForm also display 3 pre-populated fields that are list of options, this list of options depend on eachother and I make this work with AJAX. The fields are: department_list, province_list and district_list. The form collects the data collects, but I cannot replicate this behaviour with pre-defined values for these fields on my test. Test error: Says that the hardcoded values are not valid options. <ul class="errorlist"><li>shipping_province<ul class="errorlist"><li>Escoja una opción válida. Huánuco no es una de las opciones disponibles.</li></ul></li><li>shipping_district<ul class="errorlist"><li>Escoja una opción válida. Yacus no es una de las opciones disponibles.</li></ul></li></ul> test_forms.py def test_profile_form(self): call_command('ubigeo_peru') peru = Peru.objects.all() department_list = set() province_list = set() district_list = set() for p in peru: department_list.add(p.departamento) department_list = list(department_list) print("## DEPARTMENT LIST ###") print(type(department_list[0])) print(department_list[0]) if len(department_list): province_list = set(Peru.objects.filter(departamento=department_list[0]).values_list("provincia", flat=True)) province_list = list(province_list) print("### PROVINCE LIST ###") print(type(province_list[0])) print(province_list[0]) else: province_list = set() if len(province_list): district_list = set( Peru.objects.filter(departamento=department_list[0], provincia=province_list[0]).values_list("distrito", flat=True)) else: district_list = set() form_data = {'user': self.user, 'dni': 454545, 'phone_number': 96959495, 'birthdate': datetime.datetime.now(), 'shipping_address1': 'Urb. Los Leones', 'shipping_address2': 'Colegio X', 'shipping_department': … -
Adding an extra field and value to a django queryset's objects
Let the following Model: class Books(models.Model): b_name = models.CharField(max_length=10) b_page = models.IntegerField() What I want is to add an extra field with different values based on the logged user in the views and then render it to the templates, so that I can use it like following: {% for b in books_qs %} {{b.extra_field}} {% endfor %} May be in views like this: qs = Books.objects.filter(...) for q in qs: some_values = random_value_with_logged_user: q.add("some_field", random_value_with_logged_user) And because the values should be random and depending on user, so I can't use a model field for this task. So please help me with some solution. Please HELP!!!! -
How to fix "the model is used as in intermediate model but it does not have foreign key to a model"?
Error Message: blogs.Permission: (fields.E336) The model is used as an intermediate model by 'blogs.Category.permission', but it does not have a foreign key to 'Category' or 'Permission'. I have tried to add a Foreign Key to 'Category' under Permission model, same error still occurs. models.py: from django.db import models class Category(models.Model): name = models.CharField(max_length=50) permission = models.ManyToManyField('Permission', related_name='category_permissions', through='Permission' ) def __str__(self): return self.name class Permission(models.Model): HIGH = 'High' MEDIUM = 'Medium' LOW = 'Low' CLASSIFICATION_CHOICES = [ (HIGH, 'High'), (MEDIUM, 'Medium'), (LOW, 'Low') ] category_name = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category_name') name = models.CharField(max_length=100) description = models.TextField() platform = models.CharField( max_length=10, choices=PLATFORM_CHOICES, default=BOTH, ) classification = models.CharField( max_length=10, choices=CLASSIFICATION_CHOICES, default=LOW, ) def __str__(self): return self.name class MobileApp(models.Model): name = models.CharField(max_length=200) icon = models.ImageField(upload_to='app_icons', blank=True, null=True) platform = models.CharField( max_length=10, choices=PLATFORM_CHOICES, default=IOS, ) category = models.ManyToManyField('Category') provider = models.CharField(max_length=200) identifier = models.CharField(max_length=200) permission = models.ManyToManyField(Permission, related_name='mobile_app_permission', ) def __str__(self): return self.name I am trying to use 'through' argument to include the description field of the permission m2m for MobileApp and Category -
Django get_total_topup() missing 1 required positional argument: 'request'
class IndexAjaxView(View): def get(self, request): param = request.GET.get('param') if param == 'get_total_topup': return self.get_total_topup() return JSONResponse({}, status=404) def get_total_topup(self, request): return JSONResponse({ 'value': 'Rp.{:,.0f},-'.format( TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum'] ) }) somebody can help me ? I want to get data via ajax, but the response is 500 with message get_total_topup() missing 1 required positional argument: 'request' -
I'm trying to implement blog app with django.In homepage of app there will be list of posts alongside i need show there profile picture?
I'm trying to implement blog app with django.In homepage of app there will be list of posts alongside i need show there profile picture.I don't know how to approach? models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User # Create your models here. class Post(models.Model): title=models.CharField(max_length=100) desc=models.TextField() date=models.DateField(auto_now=True) author=models.ForeignKey(settings.AUTH_USER_MODEL, to_field="username",on_delete=models.CASCADE) class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='pics') <!----Post------> {% for post in posts %} <div class="list"> <div class="con"> <div class='logo2'> {% for img in img %} <img src='' > {% endfor %} </div> <h3 style="color:DodgerBlue;">{{post.author}}</h3> <h6 style="font-family: montserrat,sans-serif;"> {{post.date}} </h6> <div class="line"></div> <a href="{% url 'post_detail' pk=post.pk %}"><h1><b> {{post.title}}</b></h1></a> <div style="font-size: 17px;"> <p>{{post.desc}}</p> </div> </div> </div> {% endfor %} I need to show profile picture of user corresponding to thier post.I tried but i didn't got. -
Invalid block tag on line 10: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag?
I am using Django 2.2, chrome and this is a snippet from the Web Browser's error page. Error during template rendering In template D:\Django Projects\mysite\blog\templates\registration\login.html, error at line 10 Invalid block tag on line 10: 'form.as_p', expected 'endblock'. Did you forget to register or load this tag? 1 {% extends 'blog/base.html' %} 2 {% block content %} 3 <div class="jumbotron"> 4 <h1>Please Login:</h1> 5 {% if form.errors %} 6 <h3>Username or Password mismatch. Try again!</h3> 7 {% endif %} 8 <form action="{% url 'login' %}" method="POST" > 9 {% csrf_token %} 10 {% form.as_p %} 11 12 <input type="submit" class="btn btn-primary " value="Login"> 13 <input type="hidden" name="next" value="{{ next }}"> 14 </form> 15 </div> 16 {% endblock %} My project's url.py looks something like this from django.contrib import admin from django.urls import path,include from django.contrib.auth.views import LoginView,LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls')), path('accounts/login',LoginView.as_view(), name='login'), path('accounts/logout',LogoutView.as_view(), name='logout',kwargs={'next_page':'/'}), ] Why am I not able to go to login page?