Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to concatenate int to str in django template
I have a views integerfield in my model Post I am not able to concatenate the integer field in my django template. {{post.views||stringformat:"s"}} view {{ post.views||stringformat:"s"}}|pluralize }} I would also like to have it pluralized -
The current path, api/v1/latest-products, didn't match any of these
I am experiencing this problem following a tutorial and I can't identify the error. Tried changing to re_path and did not work. I created one product in the django admin database already so it should be showing something else instead of the 404 in the address. "GET /api/v1/latest-products HTTP/1.1" 404 7667 Not Found: /latest-products Below the code: URLS.PY urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')), path('api/v1/', include('product.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) VIEWS.PY from rest_framework.views import APIView from rest_framework.response import Response from .models import Product from .serializers import ProductSerializer class LatestProductsList(APIView): def get(self, request, format=None): products = Product.objects.all()[0:4] serializer = ProductSerializer(products, many=True) return Response(serializer.data) MODELS.PY class Product(models.Model): category = models.ForeignKey(Category, related_name = 'products', on_delete=models.CASCADE) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) image = models.ImageField(upload_to='uploads/', blank= True, null = True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) Thanks for the help. -
Why are comment permalinks for django-comments-xtd going to example.com in Wagtail?
I'm setting up comments in Wagtail using django-comments-xtd and one thing I'm having trouble figuring out is why my comment permalinks keep going to https://example.com/news/bloggy-test-post/#c1 instead of https://localhost:8000/news/bloggy-test-post/#c1. I found a user with a similar issue in the Wagtail Google group who discovered that they had "example.com" set as their site in Wagtail admin. But I have only one site in my settings and it's currently set to "localhost" with a port of 8000. Screenshot of the Wagtail admin site showing there is one site set to localhost with a port of 8000 I searched all my files and libraries for "example.com" and the only other setting I found was the BASE_URL setting in base.py. I tried changing that to http://localhost:8000 and the comment permalinks are still being directed to "example.com". Is there another setting I'm missing? Or another way I'm supposed to get the URL? Currently, I have this code for grabbing the url in my models.py file: def get_absolute_url(self): return self.get_url() This is the comments section code from my template: {% get_comment_count for page as comment_count %} <p> <a href="{% pageurl page %}#comments"> {{ comment_count }} comment{{ comment_count|pluralize }} </a> {{ comment_count|pluralize:"has,have" }} been posted. </p> {% render_xtdcomment_tree … -
.main not formatting correctly - Django
I have the following two files where home inherits from base. base.html: <html> <head> <style type="text/css"> .sidenav { height:100%; width:160px; position: fixed; z-index:1; top:0; left:0; background-color:#111; overflow-x: :hidden; padding-top:20px; } .sidenav a { padding:6px 8px 6px 16px; text-decoration: none; font-size:25px; color: #818181; display:block; } .sidenav a:hover{ color:#f1f1f1; } .main{ margin-left:300px; padding: 0px 10px; } </style> <title>{% block title %}Brandon's Site{% endblock %}</title> </head> <body> <div class="sidenav"> <a href="/">Home</a> </div> {% block content %} {% endblock %} </body> </html> home.html: {%extends 'main/base.html' %} <head> <style type="text/css"> .main{ margin-left:300px; padding: 0px 10px; } </style> </head> <div class = "main"> {% block content %} Add New Plant <form method = "post" action = ""> {% csrf_token %} {{form.as_p}} <button type = "submit", name = "save">Add New Plant</button> </form> {% endblock %} </div> </html> However, the form in home.html for some reason isn't recognizing the left margin and is stuck under the sidebar that I've created to the left. It ends up looking like this: Why isn't it offset to the right like the CSS implies? -
How to post Multiple Json Fields/Objects in Django using JavaScipt
I am Following a Short Tutorial on Django API where I have extended the Model to include a couple more Fields I can get the Front End working but can not Post data for the new Fields The Block of Code Below is where I would like to add a few more Fields to Post..., at least that is where I think it should go...?? var title = document.getElementById('title').value fetch(url, { method:'POST', headers:{ 'Content-type':'application/json', 'X-CSRFToken':csrftoken, }, body: JSON.stringify({'title': title }) } ).then(function(response){ buildList() document.getElementById('form').reset() }) }) **** Model **** from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False, blank=True, null=True) name = models.CharField(max_length=75, blank=True, null=True) price = models.FloatField(default='0.00') productdesc = models.CharField(db_column='ProductDesc', max_length=75, blank=True, null=True) # Field name made lowercase. producttype = models.CharField(db_column='ProductType', max_length=75, blank=True, null=True) # Field name made lowercase. producttypefamily = models.CharField(db_column='ProductTypeFamily', max_length=75, blank=True, null=True) # Field name made lowercase. numworkstation = models.IntegerField(db_column='Numworkstation', default='0') # Field name made lowercase. numserver = models.IntegerField(db_column='Numserver', default='0') # Field name made lowercase. addlconsole = models.IntegerField(db_column='addlconsole', default='0') # Field name made lowercase. productcomplexitybase = models.FloatField(db_column='ProductComplexityBase', default='550') # Field name made lowercase. productcomplexityfac = models.FloatField(db_column='ProductComplexityFac', default='1.0') # Field name made lowercase. digital = models.BooleanField(default=False,null=True, blank=True) def __str__(self): … -
python /Django filtering data
I am quite new to Programming ,I have created 3 model children fields : name , is_active and is_sponsored Sponsor fields : Name Sponsorship fields :children(foreign key), sponsor(foreign key), start_date and end_date. i need to set a condition only those only those children shall be displayed that have less than 2 sponsorship on current date and are active. i have already set filter in sponsorshipForm relating to is_sponsored. but to check and change is_sponsored value with regards to above condition. basically i and unable to write logic for the above condition please help -
Trouble deploying python on Heroku
I forked some code from GitHub and am trying to get it working as an app on Heroku. I'm pretty new to coding so your help is greatly appreciated! My goal is to get the code from GitHub (booking bot) to run so my boss can make tennis court reservations automatically. He likes to play at certain times and the reservations get taken within seconds of being released. I found this code that seems like it will solve the problem and am hoping to get it running. I was able to deploy it on Heroku by connecting to GiHub and made some of the changes necessary but I'm getting this message: Not Found The requested resource was not found on this server. Here's a link to the app on Heroku: https://gary-reserve.herokuapp.com/ Here's a link to my fork on GitHub: https://github.com/GaryKentTeam/booking_bot Thank you for your help! a -
Python/Django URls
Disclamer.....this is an assignment! Can some one tell me why I am getting Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%20%25%20url%20'detail'%20user%20%25%20%7D Using the URLconf defined in bobbdjango.urls, Django tried these URL patterns, in this order: [name='home'] profile [name='profile'] user_detail/<str:user_id> [name='detail'] The current path, { % url 'detail' user % }, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I think its a problem with my URL but I am not seeing source of error. I would just like to click on the link on the home page and move to the user details page. See code below... My Home page <body> {% block content %} <h1>This is home page</h1> <div> <!-- <a href="{% url 'profile' %}">Your profile</a> --> {% for user in users %} <a href="{ % url 'detail' user % }"> <h3>{{user.first_name}}</h3> </a> {% endfor %} </div> {% endblock %} </body> My main URL urlpatterns = [ ## path('admin/', admin.site.urls), path('', include('bobbpets.urls') ), ## path('bobbpets/<int:user.id/>', views.userDetails, name='userDetails'), ] My app URL urlpatterns = [ ## path('admin/', admin.site.urls), path('', views.home, name='home'), path('profile', views.profile, name='profile'), … -
django forms to_field_name for model choice field not selected with instance
Two simple models for example: A product that has a foreign key of warehouse. class Warehouse(models.Model): ... uuid = models.UUIDField(editable=False, default=uuid.uuid4) ... class Product(models.Model): ... warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) ... It is required to hide the PK(ID) of warehouse from select's options to customer. So I apply the to_field_name in the form as below class ProductForm(forms.ModelForm): ... warehouse = forms.ModelChoiceField( queryset=Warehouse.objects.all(), to_field_name='uuid',) # using UUID instead of pk ... Then the pk is replaced by uuid. The problem appears that when I try to edit an existing product, the current warehouse of the instance is not selected anymore. -
I need to run an query on django but i am unable to genrate Algorithum
I have These models in Django class Course(models.Model): Title = models.CharField(max_length=200, unique=True) Card_Title = models.CharField(max_length=200, default='Nothing') Description = RichTextField(blank=True, null=True) Course_Image = models.FileField(upload_to='CoursesImages') Progress = models.IntegerField(blank=True, null=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title class Lesson(models.Model): Course_id = models.ForeignKey(Course, on_delete=models.CASCADE) Number = models.IntegerField() Title = models.CharField(max_length=200) Completed = models.BooleanField(default=False, blank=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title + ' (' + str(self.Number) + ')' class Topic(models.Model): Title = models.CharField(max_length=100) Topic = models.FileField() Lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE) Completed = models.BooleanField(default=False, blank=True) date = models.DateField(default=timezone.now, blank=True) def __str__(self): return self.Title How its work : Every Lessons Will Have one Course So We have Many Lessons in one Course And one Topic can have one Lesson So We have many Topic in one Lesson **I Need To Figure out quey like this {'Lesson1':[Topic1,Topic2,Topic,3,Topic,4],'Lesson':[Topic1,Topic2,Topic,3,Topic,4],........} We will give course id Relevant Lessons and Topic will have to be fetched -
Django model - query with date arithmetic on model with multiple DateTimeField fields
I am using Django 3.2 I have a model like this: class FoodItem(models.Model): display_date = models.DateTimeField() expiry_date = models.DateTimeField() safe_to_eat_days_after_expiry = models.SmallPositiveInteger() # ... I want to run a query to get all items that have expired, but are still safe to eat. This is what I have so far: criterion1 = Q(expiry_date__gt=date.today()) criterion2 = Q(???) # expiry_date +timedelta(safe_to_eat_days_after_expiry ) <= date.today() FoodItem.objects.filter(criterion1 & criterion2) How do I implement this? -
The best way to connect and deploy Next.js CSR React app, Django and PostgreSQL
On the frontend, I have a Next.js React app. I want to render it on the client-side and probably use SWR. On the backend, I have a Django app with a PostgreSQL database. What is the most optimal solution when it comes to connecting all of these together? How would you approach deployment of such a project (e.g. as a single app, separate apps, Docker containers)? -
Django sql error in view but not via admin
I'm getting an unsupported operand type(s) for +: 'float' and 'decimal.Decimal' error. When I debug my code in my update_account function I can see that instance.amount is <class 'float'> and a.balance is <class 'decimal.Decimal'> so the error makes sense. Now if I were to add Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00) manually in my Admin page the code does not throw an error. Both types are <class 'decimal.Decimal'>. Why does adding a transaction via my Admin work but adding a transaction through my view throw an error? And how can I handle this error? Models: class Account(models.Model): user = models.CharField(max_length=30) balance = models.DecimalField(max_digits=500, decimal_places=2) class Transaction(models.Model): user = models.CharField(max_length=30) type = models.CharField(max_length=10) description = models.CharField(max_length=30) amount = models.DecimalField(max_digits=5, decimal_places=2) @receiver(post_save, sender=Transaction) def update_account(sender, instance, created, **kwargs): if created: user = instance.user a = Account.objects.get(user=user) #error occurs here a.balance = instance.amount + a.balance a.save() View: def transaction(request): id = request.user.id t = Transaction(user=id, type='deposit', description='Venmo inc', amount=200.00) t.save() return HttpResponse('Transaction Complete') -
What is the best method for overriding a nested DRF serializer so it creates an object if it doesn't exist?
I have a Django Rest Framework project that uses a nested UserSerializer throughout the app. An example would be a TicketSerializer with a nested UserSerializer for owner. I would like for any time User data is serialized that it get_or_create the User without having to explicitly do this as part of the TicketSerializer create method. I know there are probably a lot of ways to do this, so I’m trying to understand the most “correct” way. Currently, I’m think about overriding the UserSerializer init method or create a custom Validator that would handle the logic. -
how to fetch related items in django many to many relation
In the list l , I need the departments list associated with a particular employee , but it throws 'User' object has no attribute 'dep__department' class Dep(models.Model): department = models.CharField(max_length=255, blank=True, null=True) class EMP(models.Model): id = ShortUUIDField(primary_key=True, editable=False) email = models.EmailField(verbose_name="email address", max_length=255, unique=True) phone = models.CharField(max_length=50, null=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) dep = models.ManyToManyField(Dep) views.py l=[] users=User.objects.filter(some filter condition) for d in users: l.append(d.dep__department) -
Django - Add products to favorite list
I am building a supermarket store, using Django. I have to give user the possibility to add/remove items to/from the Favourite list. So far i have done the following models.py class Product(models.Model): category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) sku = models.CharField(max_length=254, null=True, blank=True) name = models.CharField(max_length=254) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) rating = models.DecimalField(max_digits=6, decimal_places=1, null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) image = models.ImageField(null=True, blank=True) favourites = models.ManyToManyField(User, related_name='favourites', blank=True) def __str__(self): return self.name i created favourites folder and in the folder i have: views.py def favourites(request, product_id): product = get_object_or_404(Product, pk=product_id) if product.favourites.filter(id=request.user.ide).exist(): product.favourites.remove(request.user) else: product.favourites.add(request.user) return render(request, 'favourites/product_favourite_list.html') def product_favourite_list(request): user=request.user favourite_products = user.favourites.all() context = { 'favourite_products': favourite_products } return render(request, 'favourites/product_favourite_list.html', context) urls.py urlpatterns = [ path('', views.favourites, name='favourites'), path('favourites/', views.product_favourite_list, name='product_favourite_list'), ] in product_details i have def product_detail(request, product_id): """ A view to show individual product details """ product = get_object_or_404(Product, pk=product_id) is_favourite = False if product.favourites.filter(id=request.user.id).exists(): is_favourite = True context = { 'product': product, 'is_favourite': is_favourite, } return render(request, 'products/product_detail.html', context) product_details HTML has the following links {% if is_favourite%} <a href="{% url 'product_favourite_list' id=product.id %}"> <i class="fas fa-heart fa-lg"></i> </a> {% else %} <a href="{% url 'product_favourite_list' id=product.id %}"> <i … -
Get django model query data while passing them to javascript
I'm working on a social network. I want to load the comments of each post so I make an API call to the server to fetch all the comments of the required posts. The code will make everything clear: urls.py path("comments/<int:post_id>", views.load_comments) models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') commented_by = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=128) views.py def load_comments(request, post_id): """Returns the comments to index.js""" try: # Filter comments returned based on post id post = Post.objects.get(pk=post_id) comments = list(Comment.objects.filter(post=post).values()) return JsonResponse({"comments": comments}) except: return JsonResponse({"error": "Post not found", "status": 404}) index.js fetch(`/comments/${post_id}`) .then(res => res.json()) .then(res => { // Appoints the number of comments in the Modal title document.querySelector("#exampleModalLongTitle").textContent = `${res.comments.length} Comments`; res.comments.forEach(comment => { modal_body = document.querySelector(".modal-body") b = document.createElement("b"); span = document.createElement("span"); br = document.createElement("br"); span.classList.add("gray") b.textContent = comment.commented_by_id + " "; span.textContent = comment.comment; modal_body.appendChild(b); modal_body.appendChild(span); modal_body.appendChild(br); }) I can get the comment value using comment.comment in js. However, the problem arises when I convert the comments objects to list.values so now I lose the ability to get the user who posted the comment (commented_by) Any help to get the comment and commented_by values is appreciated. -
Django-Python CORS Error: Redirect is not allowed for a preflight request
estoy teniendo un error con Django a la hora de enviar una peticion desde Ajax.. Les dejo el codigo: ENVIO DESDE AJAX: $.ajax({ type: 'POST', url: urlTotal, data: data, success: function (data) { console.log(data); }, }) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ] -
Matchin query does not exist Django
I'm trying to get user info from form, and show it in user profile, like real name and age and description, I did make it happen but there is a problem that if user try to update info again, old tables in database will not be removed, (maybe because i didn't make it to recognize user, i don't know how) anyway i did try to make it that with every update info old queries will be updated, but there is one problem for now, that is: UpdateInfo matching query does not exist. and this is because there is no query in database so system can't find anything for it, but i want to make it if query does not exist > create if query is exist > update here is my code: Models.py class UpdateInfo(models.Model): realname = models.CharField(max_length=100) age = models.CharField(max_length=1000) desc = models.TextField() id= models.AutoField(primary_key=True, null=False) forms.py class Info(forms.ModelForm): class Meta: model = UpdateInfo fields = ['realname' , 'age', 'desc'] and views.py def information(request): if request.POST: uinfo = Info(request.POST) b = UpdateInfo.objects.get(pk=1) if uinfo.is_valid(): form = Info.objects.filter(pk=b).update(realname=realname,age=age,desc=desc) form2 = Info(request.POST, isinstance=form) form2.save() return redirect('profiles:userprof') else: form = forms.Info() return render(request, 'info.html', {'form': form}) I've tried using try like this: … -
Django Rest Framework asking for authentication after sign in
I am able to successfully login via Token Authentication. However, when getting another API, its asking for authentication. {"detail":"Authentication credentials were not provided."} views.py class CreateQuiz(generics.ListCreateAPIView): serializer_class = QuizSerializer authentication_classes = (TokenAuthentication,) permission_classes =(IsAuthenticated,) def get_queryset(self): return somequeryset settings.py REST_FRAMEWORK ={ 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ), } from datetime import timedelta REST_KNOX ={ 'USER_SERIALZIER' :'api.serializer.UserSerializer', 'TOKEN_TTL': timedelta(hours=24*7), } when I test http://127.0.0.0.1:8000/apis/v1/login/?username=xxxx.com&password=xxxx on postman, I get succcessfully authenticated and returns { "expiry": "2021-05-18T19:46:33.841420Z", "token": "f07a35897b070eabfcf1439c4495b8cede5fd9908135692e2c516127a926f2ab" } -
why mu user model throws an error like filter_horizontal
below is my django user model . as you can see i created two diffrent models and sync them on a foreign keys but cant migrate my project # accounts/models.py from django.db import models class MyUser(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=50) username = models.CharField(max_length=50) password = models.CharField(max_length=50) NationalID=models.IntegerField(unique=True,max_length=10) def __str__(self): return self.username class Mykeys(models.Model): userid = models.ForeignKey(MyUser,on_delete=models.CASCADE) public_key = models.TextField(unique=False) private_key = models.TextField(unique=True) def __str__(self): return self.public_key -
How to Implement Django Case Insensitive Model Field?
Django do not come with case insensitive model field so how do I make a model field case insensitive without breaking my existing codes? For example: I have a username field on my UserModel but I noticed that despite making the field unique it would still allow me to use the case variant of the same word: Example below: from django.db import models class UserModel(models.Model): username = models.CharField(max_length=16, unique=True) user1 = UserModel(username='user1') # will go through user1.save() user2 = UserModel(username='User1') # will still go through user2.save() -
What is wrong with my javascript fetch API call?
I have a javascript fetch API call made to a Django backend server const res = fetch(url, { credentials: 'include', method: 'POST', mode: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify(requestBody), }) .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); If I output the requestBody on the console before using it in the request, it looks like follows {"add-Choice":["L"],"add-Left":["1"],"add-Right":["1"],"add-Value":["100"],"add-match":["8"],"user":["siteuser1"],"csrfmiddlewaretoken":["3K89ZvofjhIL2nZQoCcxphjmXborujsaLPn2FzlYiVmiBLODWhQQiAB5BhSXkQcF"],"add":["Submit"]} Here string "add-" is used as a form prefix on the Django side view post methode. However, on the server view side, if I print the request.POST as follow def post(self, request, *args, **kwargs): print('Post request: ', request.POST) I get the output as an empty QueryDict as follow Post request: <QueryDict: {}> Internal Server Error: /matchoffers/8 The request is being sent to the correct URL and is picked up the correct view-post methode. But it fails because the request is empty. -
Django file object always 0 bytes when uploaded from python requests
I have been trying to upload a file to django using python requests. I create the file object and verify the length, which is not 0 testfile.seek(0, os.SEEK_END) filesize = testfile.tell() I create the files object test_files = { "file": ("testsave.zip", test_save_file, "application/zip") } I put the file, and some other data r = self.session.put( f"{hello_url}/shadow_pbem/savefile_api/", files=test_files, data={"hash": test_save_file_hash, 'leader': 78}, headers=good_token_header, ) I get a 200 response, the model saves all the data correctly as expected, including a correctly named save file in /media, except the save file in /media is always 0 bytes. I put some code in the view to verify, and the file object in the view is there, but it is 0 bytes. here is the relevent part of the view. It seems to work fine, but all files are 0 bytes. class SaveFileUploadView(APIView): parser_class = (FileUploadParser,) # permission_classes = (IsAuthenticated,) def put(self, request): if "file" not in request.data: raise ParseError("Empty content") f = request.data["file"] print(f"file {f} size:{f.size}") # prints file testsave.zip size:0 # rest of view works fine... I have tried with various files and formats, also using post. Files are always 0 bytes. Any help appreciated I am going crazy.... -
Django displays twice the same message
Django displays twice the same message, even when the messages are not passed in the views.py. #login.html {% extends 'login_system/base.html' %} {% block body %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" role="alert"> {{ message }} </div> {% endif %} {% endfor %} <form method="POST"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary">Submit</button> </form> {% endblock %} # views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm, LoginForm # Create your views here. def login(request): if request.method == 'POST': form = LoginForm(data=request.POST) print(request.POST) if form.is_valid(): messages.success(request, 'Successfully Logged In!') print('ok') return redirect('home_page') else: #print(form.errors.get_json_data()) if form.errors: for error in form.errors.get_json_data()['__all__']: messages.error(request, error['message']) else: messages.error(request, 'Something went wrong. Please try again.') print('nie ok') else: form = LoginForm() return render(request, 'login_system/login.html', {'form': form}) This code renders error message twice for me. One is from the views.py, Second I do not know. The base.html file can look like this <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% block body %} {% endblock %} </body>[![enter image description here][1]][1] </html> And I can delete sending message from the views.py and the nonstyled version still is rendered. Why …