Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF: "Positional argument follows keyword argument unpacking" when trying to add current user
I'm trying to add the currently logged in user into the "user" foreign key field in the "LeadFacilityAssign" model, everytime a leadfacility object gets created. But I'm getting this: "Positional argument follows keyword argument unpacking" models.py class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) agent = models.ForeignKey("User", null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) datetime = models.DateTimeField(null=True, blank=True) user = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True, related_name='owner') serializers.py class AssignedFacilitySerializer(serializers.ModelSerializer): class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'user') class LeadUpdateAssignedSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = AssignedFacilitySerializer(required=False, many=True, allow_null=True) class Meta: model = Lead fields = ( "id", "agent", "is_owner", "assigned_facilities", ) read_only_fields = ("id", "agent", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def update(self, instance, validated_data): assigned_facilities = validated_data.pop("assigned_facilities", []) user = self.context["request"].user instance = instance for item in assigned_facilities: instance.leadfacility.create(**item, user) return instance -
I need to make regular working Queue when its not empty in Django
PROJECT: I am making a web app, where users send a ZIP file, it saves to the folder. There is a VM continuously looking for that folder where the zip gets extracted. Note that VM is only 1. So I have to extract, sleep for 20 seconds and remove the files from that folder, VM generates the results, then my Django app generates a CSV from those files, and return to user as downloadable. This is the flow. Problem: MultiUsers: I am using a file, like below def Uplaoder(request): file=takenFromPost() #lets assume this works. with open('busy.txt', 'r') as f: if "false" in f: with open('busy.csv', 'w') as f: f.write('true') #here I made it true so that if its true, the request doesn't disturb it as single VM f.close() finalcsv=workFurther() #here is the whole process lets say. with open('busy.csv', 'w') as f: f.write('false') f.close() return render(request, 'worked.html', {'finalcsv':finalcsv}) elif "true" in f: Uploader(request) #here I send this request again to this so that the user keeps waiting and when the #files gets generated for the second user, he gets the response. Here is the example logic, same as my code works. Problem: Logic seemed me well but the browser doesn't wait … -
User accessible in views but not in template
I am trying to use {% if user.is_authenticated %} in a template, but the user actually doesn't exist. If I try to output {{ user }}, there is nothing. In my settings I have those options for TEMPLATES: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", I developed an authentication backend class to use the credentials of the active directory and added the class to AUTHENTICATION_BACKENDS in settings.py. class CustomAuthenticationBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): """ Authenticate user from active directory If user is not found, create it """ # Get user from database try: user = User.objects.get(username=username) # If user does not exist, create it except User.DoesNotExist: user = User(username=username) user.displayed_name = kwargs['display_name'] user.email = kwargs['email'] user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I added the authenticate logic and the login logic to a django Form: def authenticate_and_login(self, request) -> bool: """ Method to authenticate the user and login return True if user is authenticated and logged in or False and fill the form with errors """ is_logged = False # Init active directory service ad_service = ActiveDirectoryService() # Get username and password username = self.cleaned_data['username'] password = self.cleaned_data['password'] # Get authorized user from … -
How to store mathematical symbols and formulas in column sqlalchemy Postgres as DB
I have two questions: What I want to do is to be able to store a mathematical question with special symbols, formulas that are part of the text. What column should I define in SQLAlchemy so that I can get back the equation without any issue. Second part involves in data entry, I want to upload questions in bulk, now the special symbols cannot be defined/written as text in excel, I was able to do it in MSWord. Is there any specific rules that I can define so I can read the equation in that rule and transform it into mathematical equation. For Ex. similar to latex, if we type [\sqrt{x^2+1}], we see the math format in pdf. That way I can provide a input text where they can write equations in that format and it automatically converts it into math formulae and display it as such. Now is there any intelligent way to achieve this? I'm using Fastapi with SQLAlchemy and for database, I'm using Postgres. If you could point me to relevant resources, that would have great help. -
Django with mysql, faced 'table doesn't exist' error randomly at different times of the day
I'm currently using Django version 2.2.28 with mysql innodb engine version 5.7, before some days i faced a crazy issue, here: (MySQLdb._exceptions.ProgrammingError) (1146, "Table 'db_name.table_name' doesn't exist") What's driving me crazy is that they happen on different tables at different times (not always). I couldn't even get a specific pattern. i can confirm no change in the code happened from along o week and no release happened, The problem started happening 3 days ago and randomly, same table is currently working fine and a minute later the same exception is returned and then back to working fine. i used RDS from AWS, and have different DBs under of it, the issue happening only on one of these DBs. i also checked logs file from mysql and i don't fond any thing useful, i just found errors like this [ERROR] InnoDB: MySQL is freeing a thd though trx->n_mysql_tables_in_use is 2 and trx->mysql_n_tables_locked is 654 and i think it's irrelevant. I make sure about all permissions for the user too. and i did a failover for the whole RDS and nothing working. I don't think it has to do with django's migration command, because this problem always happened randomly. can any one … -
Static files apply on all pages except index.html and base.html
I have an issue about static files. i uploaded the code on pyanywhere all good, it runs, i linked the static urls in pyanywhere>web page corectly. the issue is that my static does not load on the index and base.html but on the other pages (where i have base.html extend it applies). Can you give me some support please? how it looks python anywhere url STATIC_URL = 'static/' STATIC_ROOT = "home/Tsh2Dns/businessplaner/static/" #i tried to give root from pythonanywhere. still same response STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATICFILES_DIR = [ os.path.join(str(BASE_DIR.joinpath('static')),) ] folders: -
How to use a custom ModelForm in User admin
I'm trying to limit standard user possibilities in the User application Django's admin, to avoid the possibility of privileges escalation. I've tried the approach mentioned in docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form class UserAdmin(BaseUserAdmin): form = UserForm inlines = (UserProfileInline,) def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: kwargs["form"] = SuperUserForm return super().get_form(request, obj, **kwargs) class UserForm(ModelForm): class Meta: model = User exclude = ("is_superuser",) # it is just an example class SuperUserForm(ModelForm): class Meta: model = User fields = "__all__ Unfortunately, this results in such an error: "Key 'is_superuser' not found in 'UserForm'. Choices are: date_joined, email, first_name, groups, is_active, is_staff, last_login, last_name, password, user_permissions, username." If I would decide to exclude "groups": "Key 'groups' not found in 'UserForm'. Choices are: date_joined, email, first_name, is_active, is_staff, is_superuser, last_login, last_name, password, user_permissions, username." -
Django html css
I hava a problem with a background image, I can't load the picture on the page, I don't know what the problem is Here is my code: <style> body { background-image: url("../img/mountains.jpg"); } </style> enter image description here -
SMTPSenderRefused at /contacts
I am using Django. I want to send email via html contact form. And I am facing this error: SMTPSenderRefused at /contacts (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://127.0.0.1:8000/contacts Django Version: 4.1.2 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TSL = True EMAIL_HOST_USER = 'email@gmail.com' EMAIL_PASSWORD = 'Key' EMAIL_PORT = 587 EMAIL_USE_SSL = False Here is my view.py def contacts(request): selected = "contact" if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('comments') data = { 'name':name, 'email': email, 'subject': subject, 'message': message } message = ''' New Message : {} From : {} '''.format(data['message'], data['email']) send_mail(data['subject'], message,'' ,['qweaverinfo@gmail.com']) return render(request, 'layouts/auth-signup-success.html', locals()) return render(request, 'layouts/contact.html', locals()) I don't understand how to fix the STARTTLS. Is anyone here to help me? I tried to use the SSL, I met the same problem. I want to the Django documentation, I did not find anything about the STARTTLS command. I was expecting to send email via a html template using Django. -
What is the diffenrence between psycopg2 vs psycopg3
please give me short explanation what is the difference between https://pypi.org/project/psycopg/ and https://pypi.org/project/psycopg2/ If i have Django3.2 what i have to use? Any advantages? In official manual i didn't see any remarks about psycopg. There is only psycopg2 https://docs.djangoproject.com/en/3.2/ref/settings/#std-setting-DATABASES I tried to migrate my project from sqlite to postgres 9 -
Django Creation View Doesn't save any data
My creation view redirect to blog main page well after creation but i can't find any post's been created in the posts or admin page posts, can anyone help please here is my view @login_required def add_post(request): if request.method == 'POST': post_form = PostForm(request.POST, request.FILES, instance=request.user) snippet_form = SnippetForm(request.POST) if post_form.is_valid() and snippet_form.is_valid(): post = post_form.save(commit=False) snpt = snippet_form.save(commit=False) post.creator = request.user snpt.id = post.id post.save() and snpt.save() return redirect('blog:index') else: post_form = PostForm() snippet_form = SnippetForm() return render(request, 'blog/add_post.html', {'post': post_form, 'snpt': snippet_form}) what's wrong in this view cause i been able to save new post from admin add new post but from client it doesn't save anything Do I need to use model create() method here or what? *Any required snippet i will provide but the problem is in this snippet any help is really appreciable -
Multiple models and multiple serializer in single response in DRF
I'm creating a search functionality that returns all model fields like - users, posts, hashtags, images, and videos. I'm trying to create multiple queryset with their multiple serializers to return in a single response. this is my expected response result. { searchresults{ posts[ ],images[ ],videos[ ],user[ ] } } I tried many methods to do this, but the response was unsuccessful. I also tried that one but that required relationship. class HashTagResponseSerializer(serializers.ModelSerializer): class Meta: model = HashtagName fields = ["hashtag",] def get_hashtag(self, obj): ... class UserFollowSerializer(serializers.ModelSerializer): hashtag = HashTagResponseSerializer(many=True, read_only=True) class Meta: model = User fields = ['user_uuid', 'post_language', "username", "display_name", "profile_picture", "hashtag "] -
Creating a new model with a one-to-one relationship with an existing model Django
I want to add a Profile model relationship through a one-to-one field to the existing User model. However I already have a couple of users in the database. How can I migrate the new model while creating these default relationships at the same time? So for example I have two users Foo and Bar already created in the database and after migrating the Profile model both users should have an associated Profile with them. Models class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) first_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "surname"] def get_full_name(self): return f"{self.first_name} {self.surname}" def __str__(self): return self.email def is_staff(self): return self.staff def is_admin(self): return self.admin ### New model I want to create class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default="gravatar.jpg", upload_to="avatars/") username = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return f"{self.user.first_name}'s profile" -
Adding custom title to django form fields
I would like to add custom title to one of my form fields. I made some modifications but it still not working. My forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30) phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] labels = {'fixed_by' : 'Fixed by/Assigned to'} ` my models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') ` Need to change the form field title "Fixed by" to "Fixed by/Assigned to" -
django django.db.models.query_utils.DeferredAttribute object at 0x000
I'm trying to create a custom id for my project def get_default_id(): last_cl_itemid = ClearanceItem.objects.all().order_by('cl_itemid').last() if not last_cl_itemid: return str(ClearanceItem.sem)+ '00' class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=255, default=get_default_id) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' When I try to post something like this { "sem": "1", } It's should look like this 1-00 but When I check the rows in the ClearanceItem <django.db.models.query_utils.DeferredAttribute object at 0x0000024D625844C0>00 How can I do this or any alternative solution -
Removing items from a list in a request.session is not working I do not understand why
I try to create a basic Q&A game. In the request.session['questions'] I am saving the questions I want to render . The flow should be : Question 1 as son the form is loaded --> once the user click next question 2 shoul be rendered an so on until the request.session['questions'] is empty. whit the following code I Only could show the 2 first options and I don`t know why is not working as expected. def game(request): if request.method == 'GET': request.session['questions'] = ['question1','question2','question3','question4'] print(request.session['questions']) q = request.session['questions'].pop(0) form = QForm({'question':q}) print(request.session['questions']) return render(request, 'game.html', {'form':form}) else: if request.method == 'POST' and len(request.session['questions']) >0: q= request.session['questions'].pop(0) print(name) form = QForm({'question':q}) return render(request, 'game.html', {'form':form}) else: return redirect('home') -
Time gap between message.errors in django
I created a Django app with a form. when the form is submitted and found error, messages.error(request, e) is called, where e is the error text. the real code for field, errors in form.errors.items(): print('Field: {} Errors: {}'.format(field, ','.join(errors))) e = 'Field: {} Errors: {}'.format(field, ','.join(errors)) messages.error(request, e) if I have multiple errors, multiple error boxes pops up at same time, but I want to make a time difference of .5seconds between each error popup. I saw time.sleep(0.5) but the issue is it just takes timegap inside forloop not in gap between the popup. There might be a JS fix, I would like to know how here's my html code {% if messages %} {% for message in messages %} {% if message.tags == 'alert-success' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="success" data-toast-duration="2000" class="noty-tost d-none rounded shadow bg-success"></div> {% endif %} {% if message.tags == 'alert-danger' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="danger" data-toast-duration="5000" class="noty-tost d-none rounded shadow bg-danger"></div> {% endif %} {% endfor %} {% endif %} $(document).ready(function () { $('.noti-toast').click() }); // used to trigger it(using toastify.js from a template, i don't really know much about it, but … -
How to manullay generate a new drf-simplejwt access token post the expiry of old access token using the pre-genrated refresh token for specific user?
I am using django restframework's simplejwt library to manually create tokens for user using the below function. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } The above function get_tokens_for_user will return the serialized representations of new refresh and access tokens for the given user. This function is called while user registration and login. However, after the access token is expired, a new access taken needs to be generated using the refresh token. I am unable to figure out the way/method/function for generating new access token with the refresh token. -
I want to change UTC time zone to Pakistan time zone in Django 4..1.2, can anybody help me?
This is my code below and it is not working LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Pakistan' USE_I18N = True USE_L10N = True USE_TZ = True it is giving me this error A server error occurred. Please contact the administrator. -
Django - Data is not posting to DB
I am currently working on a note/comment system. It is intended to work as adding notes to each individual projects. For example, you set up a "Project" and there is a note or comment sections intended for adding updates to the project. Here is my view.py for updating the project. The top portion is for updating the project itself, the bottom portion is for adding the notes. @login_required(login_url="/login") def update_project(request, pk): queryset = DevProjects.objects.get(id=pk) form = UpdateProject(instance=queryset) if request.method == 'POST': form = UpdateProject(request.POST, instance=queryset) if form.is_valid(): form.save() return redirect('/') project = get_object_or_404(DevProjects, id=pk) notes = project.notes.filter(id=pk) new_note = None if request.method == 'POST': notes_form = AddProjectNotes(request.POST, instance=project) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.project = project new_note.save() else: notes_form = AddProjectNotes() return render(request, 'projects/updateprojects.html', {"form": form, "queryset": queryset, 'project': project, 'notes': notes, 'new_note': new_note, 'notes_form': notes_form}) Whenever I try and submit the notes, it shows that is successfully posted to DB but in DB there is no entries. Here is my template. <div class="container"> {% if new_note %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="post"> {{ notes_form.notes|as_crispy_field }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} </div> <div class="container"> … -
Adding multiple authentication classes in API using Django Rest Framework
I have multiple internal services communicating with a django server using DRF, I have implemented token authentication on django server to authenticate requests coming from different services. I want to develop an API which can be accessed by more than 1 external service. So in my API I declared authentication_classes = [ServiceAuthClass1, ServiceAuthClass2] and permission_classes=[] Following what DRF documentation says for custom authentication the overridden authenticate method in ServiceAuthClass1 and ServiceAuthClass2 should return None if you dont want to attempt authentication using that authentication class and you want DRF to check with another authentication class(ref). Agreed and Done! In case authentication does not happen with any mentioned class DRF is not raising any error/exception. How am I suppose to handle this case? -
Dockerfile is not working correctly in ARM Ubuntu 20
I am trying to build an image that works fine on mac on a ubuntu 20 virtual machine. on my host computer I run docker-compose --debug -f local.yml build and it works fine. docker-compose --debug -f local.yml build when I type the same command into ubuntu i get: DEBU[0000] using default config store "/Users/lancemeister/.docker/buildx" [+] Building 3.9s (20/42) => [meister_affiliate_shop_local_docs internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.85kB 0.0s => [meister_affiliate_shop_local_django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.90kB 0.0s => [meister_affiliate_shop_production_postgres internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [meister_affiliate_shop_local_docs internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_production_postgres internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_local_django internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_local_docs internal] load metadata for docker.io/library/python:3.10-slim-bu 2.9s => [meister_affiliate_shop_production_postgres internal] load metadata for docker.io/library/postgres:1 3.0s => [auth] library/python:pull token for registry-1.docker.io 0.0s => [auth] library/postgres:pull token for registry-1.docker.io 0.0s => [meister_affiliate_shop_local_docs internal] load build context 0.0s => => transferring context: 935B 0.0s => CACHED [meister_affiliate_shop_local_docs python 1/1] FROM docker.io/library/python:3.10-slim-bullse 0.0s => [meister_affiliate_shop_local_django internal] load build context 0.5s => => transferring … -
How to access list items in django jinja template dynamically using variable indexing
Django jinja template error - TemplateSyntaxError I was trying to create sample show users page where I am want to show username, password and role of the users. I will be storing role as numbers and later I am trying to get the role name from a list. I have hard coded this role names to a list roles = ['admin', 'teacher', 'student'] this roles has been passed to html page as context value. Also, I am passing a num variable for accessing the list items(atm its value is also hard coded, I will be changing this in future) views.py def index(request): roles = ['admin', 'teacher', 'student'] num=1 return render(request=request, template_name='show_all.html', context={'roles': roles, 'num': num}) and inside my html page I am trying to access this list using num variable as given below show_all.html {{roles[num]}} but it is throwing an error TemplateSyntaxError at /show_all Could not parse the remainder: '[num]' from 'roles[num]' there are few solutions that saying roles.0 will get you the first result and roles.1 will give next, But I don't want to hard-code the index there. requirements.txt asgiref==3.5.2 Django==4.1.3 sqlparse==0.4.3 tzdata==2022.6 I have tried {{roles.num}} {{roles.get(num)}} {{roles[num]}} nothing is giving me desired result. -
Django - 'object is not iterable' error but there are no iterations on my object
I have a Model called Request with a Many-To-One model relationship where a User can have multiple Request objects. A Request is a custom made painting Model with many fields. I am just trying to isolate the specific Request object the User clicked on and show it on a separate template called 'requestcarousel'. I am not running any for loops on the object so I am not sure why I am getting an 'object is not iterable' error. I've tried to use filter instead of get which doesn't give an error but none of the objects are being shown Here is my view: def requestcarousel(request, pk=None): if request.method == 'GET': allRequests = Request.objects.filter(requested_user=request.user.pk) requestedPaintings = allRequests.get(pk=pk) context = { 'requestedPaintings': requestedPaintings, } return render(request, "requestcarousel.html", context) Here is requestcarousel.html: {% extends "index.html" %} {% load i18n %} {% load static %} {% static "images" as baseUrl %} {% block request_carousel_content %} {% get_current_language as LANGUAGE_CODE %} <!-- START CAROUSEL --> <div class="card"> <!-- Title --> <div class="container p-2"> {% if requestedPaintings %} {% if LANGUAGE_CODE == 'ja' %} <div class="card-title p-3"> <h4>{{requestedPaintings.name}} </h4> </div> {% else %} <div class="card-title p-3"> <h4>{{requestedPaintings.english_name}} </h4> </div> {% endif %} {% endif %} </div> … -
Django - How to prevent form reload if entered incorrectly
I have the following login form: <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "submit" value = "sign_in" >Log In</button> {% for message in messages %} <p id = "messages" style = "color:red; font-weight: bold;" class = "errormessage">{{message}}</p> {% endfor %} In the event that the user incorrectly enters their username/password, I display an error, working with the following view: if (request.POST.get('submit') == 'sign_in'): #-----------SIGN IN FUNCTION---------- context = {} if request.user.is_authenticated: return HttpResponseRedirect("/levels/1") # redirect 2 dashboard else: if request.method == 'POST': # if user isnt already logged in username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) #authenticate user if user is not None: # if user exists login(request, user) return HttpResponseRedirect("/levels/1") # redirect to dashboard else: # if user entered username/password wrong context = {'ALERT':"Username OR password is incorrect"} messages.error(request, 'Username OR password is incorrect') However, the form doesn't work as expected. When the user incorrectly enters the form, the page refreshes and the user has to click back on the Log In button to view the error (the login form is a small modal that comes up) I want to make it so …