Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelChoiceField choices not updating
Well, I'm stuck in that problem for quite long now. Went to read some question / answers and blog, and at this point I don't understand why this is not working. I'm gonna make my example as simple as possible. Let's say I have a ModelMultipleChoiceField : myfield = ModelMultipleChoiceField( queryset=SomeObject.objects.none(), label='', widget=forms.CheckboxSelectMultiple( attrs={ 'class': 'mtlz-checkbox-group', 'label': 'some label: ' } ), required=False ) I set my queryset to none cause I need to compute the result dynamically. Note that this is in a ModelForm and that this field is a field of my object that I needed to custom (with some custom widget). Well now i'm changing the queryset in the __init__() method : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() Here self.method() is a method that's computing my queryset, and it's working fine. So, whatever, the choices were not getting updated except when I refresh (just pressing f5, not cache and stuff). Continuing my reading, I read that self.base_fields['myfield'].widget.choices were cached and so I had to force the "refresh" too in my init : def __init__(self, *args, **kwargs): super(EquipeForm, self).__init__(*args, **kwargs) self.base_fields['myfield'].queryset = self.method() self.base_fields['myfield'].widget.choices = self.base_fields['myfield'].choices Using a pdb, I saw the choices were … -
Django What really is compress and decompress in MultiValueField
For past 6 - 7 hours I have been stuck on understanding how actually these things work. Actually right now I am working on creating dynamic multiValueField Forms by using Formset factory and setting max_num to some value. I am able to create dynamic form but when it comes to extracting data from form then I am not able to understand that how I can decompress values from MultiValueField When I try to iterate over forms and print them, then I notice that compress method is called but how can I explicitly call it. In simple words how it actually works ? -
NoReverseMatch with Regex when Trying To create Email from Template that takes an url as the parameter
I'm trying to send email from Django using gmail to gmail. with a send_mail: @method_decorator(csrf_exempt, name='dispatch') class AuthenticationView(View): @classmethod def send_email(cls, request, user): current_site = get_current_site(request) mail_subject = 'Activate your Poros account.' message = render_to_string('email_verification.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() Then I set url patterns for my app like this below: from django.conf.urls import url from django.urls import path from .views.activation import activate from .views import UserView, ProfileView, AuthenticationView urlpatterns = [ path('users/', UserView.as_view()), path('auth/', AuthenticationView.as_view()), path('profiles/<str:pk>/', ProfileView.as_view()), url(r'activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', activate, name='activate'), ] and will included by the project urls: from django.conf.urls import include from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls'),) ] and the activate view is coming from an activate() like this below: from django.http import HttpResponse from django.contrib.auth import login from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from accounts.utilities import account_activation_token from django.contrib.auth.models import User def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponse('Thank you for your email confirmation. … -
Search endpoint with ViewSet & Routers in Django-REST-FrameWork
Views.py class ClientViewSet(ModelViewSet, GetOrRaiseMixin): serializer_class = ClientSerializer queryset = Client.objects.all() def list(self, request): serializer = ClientSerializer(self.queryset, many=True) return JsonResponse(serializer.data, status=HTTP_200_OK, safe=False) def retrieve(self, request, pk=None): client = self.get_or_raise('Client', pk) serializer = ClientSerializer(client) return JsonResponse(serializer.data, status=HTTP_200_OK) def create(self, request): serializer = ClientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=HTTP_200_OK) else: return JsonResponse({'error': 'Invalid'}, status=HTTP_400_BAD_REQUEST) def destroy(self, request, pk=None): client = self.get_or_raise('Client', pk) client.datetime_deleted = datetime.now() client.save() return JsonResponse(serializer.data, status=HTTP_200_OK) Urls.py router.register('clients', ClientViewSet, base_name='clients') urlpatterns = [ path('api/', include(router.urls)), ] Problem Above works great for standard behaviour like create / retrieve_all / retrieve_by_id / update_by_id / delete_by_id. But what I want is to add an additional enpoint for search_&_retrieve. For example: /api/clients/search/?title='John'&age='32' etc. So generally I need 5 endpoints: Create/Retrieve/Update/Delete/Search Can I achieve that with "ViewSet+Routers" concept or I need to do something else ? -
get user role and add that to jwt payload
I have user login Serializer like below I want to add user role to my jwt payload when user is authenticated how can I access user info for example "is_stuff" field in my validate function ? user object contain <QuerySet [<User: admin>]> class UserLoginSerializer(ModelSerializer): token = CharField(allow_blank=True, read_only=True) username = CharField(required=False, allow_blank=True) email = EmailField(label='email address', required=False, allow_blank=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', 'is_staff', ] extra_kwargs = { "password": { "write_only": True } } def validate(self, data): user_obj = None email = data.get('email', None) username = data.get('username', None) password = data.get('password') if not email and not username: raise ValidationError("email or username is required!") if '@' in username: email = username user = User.objects.filter( Q(email=email) | Q(username=username) ).distinct() # user = user.exclude(email__isnull=True).exclude(email__iexact='') if user.exists() and user.count() == 1: user_obj = user.first() else: raise ValidationError("this username/email is not valid") if user_obj: if not user_obj.check_password(password): raise ValidationError("password is incorrect") payload = jwt_payload_handler(user_obj) payload["role"] = ??? data['token'] = jwt_encode_handler(payload) return data view: class UserLoginApiView(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Django Signup form validation
i have signup form in django which has only 3 fields(username ,password and confirm password) created using default userCreationForm with default input fields validations.Signuppage now i want to write test case for those validation logic in picture. how to write it? i have done basic tests which are as follows tests.py class SignUpPageTests(TestCase): username = 'sampleuser' email = 'sampleuser@email.com' def test_signupStatusCheck(self): resp = self.client.get('/accounts/signup/') self.assertEqual(resp.status_code, 200) def test_signupViewName(self): resp = self.client.get(reverse('signup')) self.assertEqual(resp.status_code, 200) def test_signupViewFile(self): resp = self.client.get(reverse('signup')) self.assertEqual(resp.status_code, 200) self.assertTemplateUsed(resp,'signup.html') def test_signupFormTest(self): self.newuser = get_user_model().objects.create_user( self.username,self.email ) self.assertEqual(get_user_model().objects.all().count(),1) self.assertEqual(get_user_model().objects.all() [0].username,self.username) self.assertEqual(get_user_model().objects.all()[0].email,self.email) Signup.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Sign Up{% endblock title %} {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Sign up</button> </form> {% endblock %} -
Serializer for inherited model
I have following models declared: class Parent(models.Model): active = models.BooleanField(default=False) class Child(Parent) name = models.CharField(max_length=100, unique=True) and serializer: class ChildSerializer(serializers.ModelSerializer): class Meta: model = Child fields = ('active', 'name') At glance everything seems to be ok, it's correctly generated in the browsable api. Neverthless when I want to update both fields only 'active' is updated. When I do put in return I receive correct resonse: { "active": true, "name": "foo" } But the name field is not updated at all. I went further and tried to implemented custom update method in the serializer: def update(self, instance, validated_data): print(str(type(instance))) return instance After that in a put response I'm receiving only active field ?: { "active": true, } And on console even more astonishing: rest_1 | <class 'applic.models.Person'> I'm completely lost :) Why on earth serializer treats explicitly provided Child model as a Person ? How to force ChildSerializer to work on Child model ? Thank you in advance Piotr -
Multiple paginations in Django for same model, links not working properly
I am trying to do multiple paginations, because I want to display my Course model by different categories. I noticed I cannot use same variable for iteration and pagination because of some other behavior that I have in my web page. So I created another variable and it worked (page). But then when I created a third variable, all the time I try to access some page I get redirected to the first pagination, though the link that appears is still for page2. What should I do ? https://i.imgur.com/7Br1a0o.png def index(request): course_list = Course.objects.all() page = request.GET.get('page', 1) paginator = Paginator(course_list, 1) try: courses2 = paginator.page(page) except PageNotAnInteger: courses2 = paginator.page(1) except EmptyPage: courses2 = paginator.page(paginator.num_pages) page2 = request.GET.get('page2', 2) paginator2 = Paginator(course_list, 1) try: courses3 = paginator2.page(page2) except PageNotAnInteger: courses3 = paginator2.page(1) except EmptyPage: courses3 = paginator2.page(paginator2.num_pages) context = { 'courses3': courses3, 'courses2': courses2, 'courses': Course.objects.all(), 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="col-md-9"> <div class="jumbotron"> <div id="crs"> <h3>All courses</h3> <ul> {% for course in courses2 %} <li><a href={{ course.slug }}>{{ course.name }}</a></li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if courses2 %} {% if courses2.has_previous %} <a href="?page=1">&laquo; first</a> … -
Combine Django extra with model query
I tried to combine my model query with extra because of the simplicity. The first query make a GROUP BY and claculate the max value. I want to add these numbers that is why I created a extra query which to this but unfortunately this query give the same result than the first. I attach an expample. My first query: query_1=Table.objects.filter(time_stamp__gte=sat_last_date.day) .order_by('table_id') .values('table_id') .annotate(one=Max('one')) .annotate(two=Max('two')) .annotate(three=Max('three')) My second query: query_2=query_1.extra(select={'sum':'abs(one)+abs(two)+abs(three)'})** The result of the second query is not the a sum column, instead i got the three column of the first query. -
How to freeze a template page or disable button and display some message when a button is clicked in Django?
I have a Django template. I have a Submit button. I need to freeze or lock the entire page for a duration of about 1 minute when the button is clicked. is this possible ? If so, how can it be done ? please help. Or else can I change the value of the button without affecting it's backend functionality and disable it at the same time ? Thanks in advance. This is my input button code : <input id='btn' type='submit' class="btn btn-primary" style="background-color:#3facdb;border-color=#3facdb;" value='Submit' /> -
Only last object inside for loop is being saved in Django Python
When I loop through for loop, only last comment object is getting saved. I'm instantiating the object every time in the loop. Do I need to pass anything else after save() method in for loop? Here is my code in views.py file : def create_form(request): post = Post() post.name = 'Post Tite' post.save() list = [{'message':'comment1'},{'message':'comment2'},{'message':'comment3'}] for obj in list: comments = Comments() comments.message = obj.message comments.save() return render(request, 'post/news_post.html', {}) Code in models.py file: class Post(models.Model): created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=100) objects = UserManager() class Comments(models.Model): created_at = models.DateTimeField(default=timezone.now, editable=False) updated_at = models.DateTimeField(default=timezone.now) post = models.ForeignKey(Post, on_delete=models.CASCADE) message = models.CharField(max_length=5000, default='') objects = UserManager() -
group by with all fields django
I want to run 2 queries in django, Please help me first one SELECT * FROM `invitations` WHERE post_id = 19215 GROUP BY (user_id) it is not group by from user_id data = Invitations.objects.filter(post_id=19215).annotate(user_id=Count('user_id')) now i have add value data = Invitations.objects.values('user_id').filter(post_id=19215).annotate(user_id=Count('user_id')) it return me not all fields select * data = Invitations.objects.values('user_id', 'xyz').filter(post_id=19215).annotate(user_id=Count('user_id')) it group by user_id and xyz Please give me solution and second is SELECT *, GROUP_CONCAT(interview_mode) FROM invitations WHERE post_id = 19215 GROUP BY (user_id) -
I want to add a color picker to my OpenCV taskbar so i can dynamically chose the color to fill drawn rectangles
I am working on an OpenCV/Django project,but I want to be able to select a color dynamically so I can draw a filled shape on the image,using the color selected.One efficient way i thought of doing this is having a color chooser on my taskbar. But I have searched everywhere I could without any luck. Can the openCV taskbar be customized to add a color chooser? And how can it be done? -
What's the main advantages of django? And career strength if you do this?
What are the differences between other web frame works and django ,can anyone explain me -
Create objects based on date and time
I have an Event model, and each event will have different shows. class Event(models.Model): title = models.CharField(max_length=200) class Show(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) date_time = models.DateTimeField(unique=True) I need to create shows based on the start date and end date provide by the user. Suppose this is an example of JSON post: { "event_id": 1, "start_date": "2018-02-16", "end_date": "2018-02-30", "time_list": ["11:00 AM", "5:00 AM", "8:00 AM"] } I am using python 3, django 2 and django rest frameowork. How can I create Shows with the event, and date_time based on the event_id, start_date, end_date and the time_list? -
Getting a django.db.utils.OperationalError: no such table With a Custom User Model
Well, I have a custom User Model in an app called accounts. The accounts.User looks like this: from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from accounts.managers import UserManager from base.models import Model from accounts.models.profiles import Profile class User(Model, AbstractBaseUser): objects = UserManager() phone_regex = RegexValidator( regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. 9-15 digits allowed.", ) phone = models.CharField( validators=[phone_regex], max_length=17, blank=True ) email = models.EmailField( max_length=255, unique=True, ) active = models.BooleanField( default=True ) staff = models.BooleanField( default=False ) superuser = models.BooleanField( default=False ) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return self.active @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser def serialize(self): data = { 'id': self.id, 'email': self.email, } return data @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() and the UserManager looks like this: from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password): if not email: raise ValueError('Users must have an email') if not password: raise ValueError('Users must have a password') user … -
How to lock/freeze a template page until an alert box is displayed in Django template?
I have a Django views function to create a lab, which includes many aws resources like an aws account, vpc, subnet, etc. I have a main.js file in which I have an ajax method inside that displays an alert. I need to freeze/lock the page for about a minute when the alert box comes up. In that gap of one minute, in the backend the aws resources will be created. Here is my main.js snippet : function create_post() { alert("Creating Lab. Please Wait"); var labname1 = $('#form-labname').val() var cidr1 = $('#form-cidr').val() var type1 = $('#form-type').val() var budget1 = $('#form-budget').val() var email1 = document.getElementById("myemail").value; console.log("create post is working!") // sanity check $.ajax({ url : "/createlab/", // the endpoint type : "POST", // http method data : { labname : labname1, cidr : cidr1, type : type1, budget : budget1 ,email : email1}, // data sent with the post request How can I do this ? Please help. -
Django-ratelimit does not limit
I have the issue using Django-ratelimit on heroku that the limiter is not working. I don't get any error. Any suggestions what I am doing wrong? views.py from django.core.cache import cache from ratelimit.mixins import RatelimitMixin [...] class LoginView(RatelimitMixin, FormView): ratelimit_key = 'user' ratelimit_rate = '1/5m' ratelimit_method = 'GET' ratelimit_block = True template_name = "account/login.html" template_name_ajax = "account/ajax/login.html" form_class = LoginUsernameForm form_kwargs = {} redirect_field_name = "next" @method_decorator(sensitive_post_parameters()) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(LoginView, self).dispatch(*args, **kwargs) def get(self, *args, **kwargs): if is_authenticated(self.request.user): return redirect(self.get_success_url()) return super(LoginView, self).get(*args, **kwargs) Setting.py # RATELIMIT SETTINGS #RATELIMIT_CACHE_PREFIX = 'rl:' RATELIMIT_ENABLE = True RATELIMIT_USE_CACHE = 'default' #RATELIMIT_VIEW = None -
parameter passing in django
I am trying to use REST API in django for retrieve some data in json format. When i hit this url: http://192.168.2.87:8000/locker/123/ It gives me output like this (from Database) {"id": 1, "locker_id": 123, "locker_user_name": "taimur"} But if i want to get the output by passing the parameters like this http://192.168.2.87:8000/locker/?locker_id=123&locker_user_name=taimur&id=1 from postman, How can i do this?? -
Django calling API from view and nested POST
I am trying to do a POST method into the api from another project. Firstly, i do a post to create appointment. If appointment success, i will post the current user profile into the Patient table from another project. How do i do a POST in a POST and also how to post the current user information ? I tried to do it, as shown below on my code but its just bad. The field i am posting into Patient table. My user profile field ---> Patient table userId > patientId first_name > first_name last_name > last_name email > email Here is my code: views: @csrf_exempt def my_django_view(request): # request method to api from another project if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/makeapp/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/makeapp/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() print(data) # Have to post the user profile information into Patient table in another project. user_profile_attrs = { "patientId": self.request.userId, "first_name": self.request.userId, "last_name": self.request.userId, "username": self.request.userId, "email": self.request.userId, } # save into patient table of another project save_profile = requests.post('http://127.0.0.1:8000/api/patient/', data=request.POST) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse(r.text) -
How do I customize the ID attributes of login and registration forms?
I have two classes in forms.py: class LoginForm(AuthenticationForm): ''' Form to log in a user ''' error_messages= { "invalid_login": _("Incorrect %(username)s/password combo") } username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"})) password= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password"})) class RegisterForm(UserCreationForm): ''' Form that makes user using just email as username ''' error_messages= { "password_mismatch": _("Passwords do not match."), "duplicate_email": _("Email already exists."), "unique": _("Email already exists"), } username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"})) password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password"})) password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password"})) class Meta: model= User fields= ("username",) I load them both on login_register.html, as is shown in this view: def login_register(request, template="pages/login_register.html"): registration_form= RegisterForm() login_form= LoginForm() return render(request, template, {"registration_form": registration_form, "login_form": login_form}) But when they both load on the page, this causes the page to have two input tags, both with the id attribute id_username. How do I change the id attributes of my forms' input tags? -
Nginx: Permission denied to Gunicorn socket on CentOS 7
I'm working in a Django project deployment. I'm working in a CentOS 7 server provided ma EC2 (AWS). I have tried to fix this bug by many ways but I cant understand what am I missing. I'm using ningx and gunicorn to deploy my project. I have created my /etc/systemd/system/myproject.servicefile with the following content: [Unit] Description=gunicorn daemon After=network.target [Service] User=centos Group=nginx WorkingDirectory=/home/centos/myproject_app ExecStart=/home/centos/myproject_app/django_env/bin/gunicorn --workers 3 --bind unix:/home/centos/myproject_app/django.sock app.wsgi:application [Install] WantedBy=multi-user.target When I run sudo systemctl restart myproject.serviceand sudo systemctl enable myproject.service, the django.sock file is correctly generated into /home/centos/myproject_app/. I have created my nginx conf flie in the folder /etc/nginx/sites-available/ with the following content: server { listen 80; server_name my_ip; charset utf-8; client_max_body_size 10m; client_body_buffer_size 128k; # serve static files location /static/ { alias /home/centos/myproject_app/app/static/; } location / { include proxy_params; proxy_pass http://unix:/home/centos/myproject_app/django.sock; } } After, I restart nginx with the following command: sudo systemctl restart nginx If I run the command sudo nginx -t, the reponse is: nginx: configuration file /etc/nginx/nginx.conf test is successful When I visit my_ip in a web browser, I'm getting a 502 bad gateway response. If I check the nginx error log, I see the following message: 1 connect() to unix:/home/centos/myproject_app/django.sock failed (13: Permission denied) … -
How do I filter only on user data in django?
I am using django-filters to filter my data. The issue is both the available options of the filters and the results are based on all the data, not only on the cuurent user. I used the code below to filter the results only on the current user: filters.py class ProductFilter(django_filters.FilterSet): class Meta: model = Product @property def qs(self): parent = super(ProductFilter, self).qs user = getattr(self.request, "user", None) return parent.filter(user=user).order_by("-timestamp") In my views.py I tried to pass the queryset, but nothing changed: class ProductsFilterView(LoginRequiredMixin, FilterView): model = Product filterset_class = ProductFilter def get_queryset(self, **kwargs): return self.model.objects.filter(user=self.request.user) I am not sure how to limit the available filter options only on the current user's data. -
Is Django's development server enough?
I have a simple Django app that will be used by, at most, a single user on the LAN. It will never be exposed to the Internet. I know the documentation says to never use the development server in production, but seeing that this won't be used by multiple people, should I still use a real webserver (Apache, NGINX etc)? Or would that be overkill? -
Registration form shows too many fields after I make custom register form model
I'm trying to make a custom registration form, but am running into trouble. My forms.py has this: class RegisterForm(UserCreationForm): ''' Form that makes user using just email as username ''' error_messages= { "password_mismatch": _("Passwords do not match."), "duplicate_email": _("Email already exists."), "unique": _("Email already exists"), } register_username= forms.EmailField(label=_("Email"), widget=forms.TextInput(attrs={"placeholder":"Email"})) register_password1= forms.CharField(label=_("Password"), widget=forms.PasswordInput(attrs={"placeholder":"Password"})) register_password2= forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput(attrs={"placeholder":"Confirm password"})) def clean_username(self): username = self.cleaned_data["username"] try: User._default_manager.get(username=username) #if the user exists, then let's raise an error message raise forms.ValidationError(self.error_messages['duplicate_email'], #user my customized error message code='duplicate_email', #set the error message key ) except User.DoesNotExist: return username # great, this user does not exist so we can continue the registration process class Meta: model= User fields= ("username",) My views.py looks like this: def login_register(request, template="pages/login_register.html"): registration_form= RegisterForm() return render(request, template, {"registration_form": registration_form}) Which leads to my registration form in login_register.html rendering like this: <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="CSRF-TOKEN-HERE"> <p><input autofocus="" id="id_username" maxlength="150" name="username" type="text" required=""></p> <p><input id="id_password1" name="password1" type="password" required=""></p> <p><input id="id_password2" name="password2" type="password" required=""></p> <p><input id="id_register_username" name="register_username" placeholder="Email" type="text" required=""></p> <p><input id="id_register_password1" name="register_password1" placeholder="Password" type="password" required=""></p> <p><input id="id_register_password2" name="register_password2" placeholder="Confirm password" type="password" required=""></p> <button class="btn btn-primary" type="submit">Register</button> </form> I only want the last three input tags to be used. My goal is for …