Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
opening the last page raises "That page contains no resuls" error when a second "next-page" button is added in django
The django pagination works well. Main html for pagination: <div class="pagination"> {% if entries.has_previous %} <a class=left-holder href="?page={{ entries.previous_page_number }}"> <img class=left-arrow src="{% static 'icons\leftarrow.png' %}" alt="leftarrow"></a> {% endif %} {% if not request.user_agent.is_mobile %} <div class="dropdown"> <button onclick="dropdown()" class="dropbtn">{{entries.number}}<span class=arrow-down><span class=spanito>&#9660;</span></button> <div id="myDropdown" class="dropdown-content"> {% for i in page_list %} <a href="?page={{i}}"><span {% if i == entries.number %} class=exception {% endif %}>{{i}}</span></a> {% endfor %} </div> </div> {% else %} <div class="dropdown"> <button onclick="phone_select()" class="dropbtn">{{entries.number}}<span class=arrow-down><span class=spanito>&#9660;</span></button> {% endif %} {% if entries.has_next %} <a class=next href="?page={{ entries.next_page_number }}"> <img class=right-arrow src="{% static 'icons\rightarrow.png' %}" alt="rightarrow"></a> {% endif %} <a href="?page={{ entries.paginator.num_pages }}"><button class=last-page>{{entries.paginator.num_pages}}</button></a> <b>-</b> </div> </div> I added a pop-up selection feature for mobile only and for practicality I also added another "next-page" button to the pop-up menu. Pop-up html from base.html: <div class="overlay6" id="overlay6"> <div id=fullscrean3> <div class=scrollable-div id=scrollable-div> {% for i in page_list %} {% if i == entries.number %} <a class=scroll-select id=exception2 href="?page={{i}}"><span id=exception>{{i}}</span></a> {% else %} <a class=scroll-select href="?page={{i}}">{{i}}</a> {% endif %} {% endfor %} </div> <button class=button-prevp onclick="kapat('overlay3') ">prev page</button> <a href="?page={{ entries.next_page_number }}"><button class=button-nextp></button>next page</button></a> </div> </div> When the second next page button is included the last page becomes inaccessible and raises … -
Can't run migrations for sorl-thumbnail
I'm trying to install sorl-thumbnail but when I run makemigrations I get "no changes detected". I upgraded the package to the latest version (12.6.3). When I try to continue using sorl-thumbnail in my html templates I get the expected error no such table: thumbnail_kvstore because I can't run mirations. I also tried manage.py makemigrations thumbnail. Here's my models.py: from sorl.thumbnail import ImageField class Profile(models.Model): user = models.OneToOneField(User, on_delete= models.CASCADE) slug = AutoSlugField(populate_from='user', unique_with='user') profile_image = models.ImageField(default='image.png', upload_to='profile_images', blank=True, null=True, validators=[validate_image]) -
Is this a good way to stream data through django channels?
I have a database where new data is being inserted every second. When the websockets connection is first established, I want to send all the data using django channels. Then, I want the new data data that goes every second into the database to be sent through the same websocket. I have the following consumers.py class DataConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) obj = ... send the whole db await self.send({ 'type': 'websocket.send', 'text': obj }) while True: await asyncio.sleep(1) obj = ... send only new records await self.send({ 'type': 'websocket.send', 'text': obj }) async def websocket_receive(self, event): print("receive", event) async def websocket_disconnect(self, event): print("disconnected", event) Here Django Channels - constantly send data to client from server they mention that the loop will never exit if the user disconnects. They present a potential fix, but I don't understand it well. How could I fix it? -
how to send a some data from a class that has foreignkey to another class through DRF?
I have a Certificate model as below: class Certificate(models.Model): """Certificates for users who passed specific tests""" user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='certificates', on_delete=models.CASCADE, null=True) name = models.CharField(verbose_name='نام', max_length=255) image = models.ImageField(null=True, upload_to=certificate_image_file_path) thumbnail = models.ImageField(null=True, upload_to=certificate_image_file_path) grade = models.IntegerField(verbose_name='نمره', null=True) minimum_grade = models.IntegerField(verbose_name='حداقل نمره') def __str__(self): return self.name and as you can see it has a foreigkey to my custom user model. I want to send the Certificate object that is assigned to a user alongside the properties of the user. the user's serializer.py: class UserSerializer(serializers.ModelSerializer): """Serializer for the user object""" # TODO # certificates # videos = serializers.PrimaryKeyRelatedField( # many=True, # queryset=Tag.objects.all() # ) class Meta: model = get_user_model() # TODO add certificates and videos fields = ('id', 'email', 'password', 'first_name', 'last_name', 'phone_number', 'credit', 'points') extra_kwargs = {'password': {'write_only': True, 'label': 'گذرواژه', 'min_length': 5}} def create(self, validated_data): """Create a new user and return it""" return get_user_model().objects.create_user(**validated_data) def update(self, instance, validated_data): """Update a user and return it""" password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user and view.py: class ManageUserView(generics.RetrieveUpdateAPIView): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): """Retrieve and return authenticated user""" return self.request.user what should I add to … -
Serving two Django apps with Nginx
I have a Django app running with Nginx and Gunicorn on mysite.com. I would like to deploy a second Django app to be reachable under mysite.com/secondapp while my first app still just by mysite.com. I followed the tutorial from DigitalOcean and my current config for App 1 is: /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application /etc/nginx/sites-available/myproject server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } My question is: do I need to create 2 separate .socket and .service file for my App 2 and how do I make App 2 accessible by mysite.com/secondapp ? -
Django - Embed python inside HTML to trigger two form actions
All I want to do is to have a condition in order when the user clicks FOR SALE button to be redirected to url 'salesearch' or when clicks TO RENT to be redirected to url 'rentsearch'. Here's the code: <div class="search"> <form action="{% url 'salesearch' %}"> <div class="form-row"> <div class="col-md-4 mb-3"> <label class="sr-only">Keywords</label> <input type="text" name="keywords" class="form-control" placeholder="Keyword (Pool, Garage, etc)"> </div> <div class="col-md-4 mb-3"> <label class="sr-only">City</label> <input type="text" name="city" class="form-control" placeholder="City"> </div> <div class="form-row"> <div class ="col-md-6 mb-3"><button class="btn btn-secondary btn-block mt-4" type="submit" name ='For Sale'>For Sale</button> </div> <div class ="col-md-6 mb-3"><button class="btn btn-secondary btn-block mt-4" type="submit" name = 'To Rent'>To Rent</button> </div> </div> </form> With the above example I am redirected always at url 'salesearch path. Is there any way to have a conditional to determine the url's path? -
I'm trying to login with django. but always fail. why?
i'm doing my own project. the project is signup, signin in django. i make my own model. not django model. i use AbstractBaseUser, and create my own model. this model get name, id, companyname, companycode. i succeed signup. get name, id, companyname, companycode. and save mysql. but when i login with this information, always fail. i think authentication function is error. but i don't know where is the error. could you help me? models.py class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, userid, company, companycode, password=None): if not username: raise ValueError(_('Users must have an name!')) user = self.model( username=username, userid = userid, company= company, companycode = companycode, ) user.save() return user def create_superuser(self, username, userid, company, companycode, password): user = self.create_user( username=username, userid = userid, company = company, companycode = companycode, password=password, ) user.set_password(password) user.is_superuser = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=10, unique=True, verbose_name="이름") userid = models.CharField(max_length=100, unique=True, verbose_name="아이디") company = models.CharField(max_length=10, verbose_name="회사") companycode = models.CharField(max_length=100, verbose_name="회사코드") created_date = models.DateTimeField(auto_now_add=True, verbose_name="생성날짜") is_admin = models.BooleanField(default=False) #is_active = models.BooleanField(default=True) class Meta: db_table = 'user' objects = UserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['userid', 'company', 'companycode'] def __str__(self): return self.username def get_full_name(self): return self.username def get_short_name(self): return self.username @property … -
Django / nested Inlineformset with class based view -> inlineformset not rendered?
I want to use nested inlineformset See below my ER diagram: Administration AdministrationSuivi adm_ide 1 ____ adm_sui_ide adm_nom |___ * adm_ide adm_sui_dem So, I have created my forms. forms.py: TREATMENT = Thesaurus.options_list(1,'fr') AdministrationSuiviFormset = inlineformset_factory( Administration, AdministrationSuivi, fields=('adm_sui_dem',), widgets={ 'adm_sui_dem': forms.Select(choices=TREATMENT), }, extra=1, can_delete=True, ) class AdministrationCreateForm(forms.ModelForm): def __init__(self, *args, **kwargs): # self.request = kwargs.pop("request") super(AdministrationCreateForm, self).__init__(*args, **kwargs) self.fields["adm_nom"] = forms.CharField(label = "Nom d'utilisateur pour l'application", widget = forms.TextInput) class Meta: model = Administration fields = ('adm_nom',) And i my view, I render my forms. Views.py class AdministrationSuiviCreateView(FormView): template_name = 'project/administrationsuivi_edit.html' form_class = AdministrationCreateForm def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data["utilisateur"] = self.request.user.username # nom de l'utilisateur connecté data["administration"] = AdministrationSuiviFormset(self.request.POST) else: data["administration"] = AdministrationSuiviFormset() return data def form_valid(self, form): context = self.get_context_data() administrationsuivi = context["administration"] self.object = form.save() if administrationsuivi.is_valid(): administrationsuivi.instance = self.object # instance Administration administrationsuivi.save() return super().form_valid(form) def get_success_url(self): return reverse("project:index_administration") But field adm_nom of AdministrationCreateForm is well render but not field adm_sui_dem of AdministrationSuiviFormset. What is wrong? -
I want to add all the images stored in a folder to a website in django
How can I loop through images in a folder and add them to the website? -
Django - allow user to run custom python code
Simple question that I can't seem to find an answer to: Is there a way in django to allow user to write their own custom code inside a textbox and to execute the code later on or on button-click? With this i mean the same it is implemented in w3scools: https://www.w3schools.com/python/trypython.asp?filename=demo_default I don't need to be able to visualize the result in a second screen or anything. The goal is to allow the user to write some basic but custom functionality! Imagine having access to a dictionary, and the user wants to transform the value of one of the keys: e.g. _dict = {'key1': 'xxx yyy', 'key2': 'yyy zzz'} and the user can create a custom key3 which is a concatenation of the two other keys. _dict['key3'] = _dict['key!'] + _dict['key2'] So here I have to expose the variable containing the dictionary and allow the user to write a custom python code to do whatever they want with it. OR embed the custom code into the actual code on run-time. Security for now is not a concern (but interesting to know how this could be handled). -
Create query if not existing with get_or_create not working
I am builing a Q/A where users can vote. I have two models, Topic which deal with the votes and question and VoteUser that set a boolean to True when a user vote. def upvote(request, qa_id): qa = get_object_or_404(Topic, pk=qa_id) vote = VoteUser.objects.get_or_create(author=request.user, topic=qa_id) vote = get_object_or_404(VoteUser, author=request.user, topic=qa_id) if vote.vote_status == False: qa.votes += 1 qa.save() vote.vote_status = True vote.save() But when I tried the request it gives me an error : vote = VoteUser.objects.get_or_create(author=request.user, topic=qa_id) -
Django Channels - Error during WebSocket handshake: net::ERR_CONNECTION_RESET
Trying to set up a simple websocket example with Django channels: Project structure: dashboard dashboard settings.py routing.py consumers.py urls.py chart urls.py views.py templates chart.html The relevant parts of each file: # dashboard/settings.py ASGI_APPLICATION = 'dashboard.routing.application' # dashboard/routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from .consumers import DataConsumer application = ProtocolTypeRouter({ # WebSocket chat handler "websocket": AuthMiddlewareStack( URLRouter([ url("websockets/", DataConsumer), ]) ), }) #dashboard/consumers.py from channels.consumer import AsyncConsumer from datetime import datetime class DataConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) async def websocket_receive(self, event): # when a message is received from the websocket print("connected", event) async def websocket_disconnect(self, event): # when the socket disconnects print("disconnected", event) #dashboard/urls.py from django.contrib import admin from django.urls import include from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('chart/', include("chart.urls")), ] #chart/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.chart) ] #chart/views.py from django.shortcuts import render def chart(request): return render(request, 'chart.html') #templates/chart.html <script> var loc = window.location var wsStart = "ws://" if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + "/websockets/" console.log(endpoint) socket = new WebSocket(endpoint); socket.onopen = function(message) { console.log("open", message); } socket.onmessage = function(message) { … -
Django. autocomplete... It doesn't look up the search
I'm new to Django with autocomplete. I'm trying to use autocomplete search. I'm following this tutorial: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.rst Django doesn't give me any mistakes. All works except it doesn't actually looking for results in the search. Instead it gives me this phrase: "the results could not be loaded" In html, in developer section it gives me following mistakes: When first get to the page - GET http://dal-yourlabs.rhcloud.com/static/collected/admin/js/vendor/jquery/jquery.js net::ERR_NAME_NOT_RESOLVED When typing into the search field: jquery.min.js:2 GET http://127.0.0.1:8000/scrap_site/raildict-autocomplete/?q=ghj 500 (Internal Server Error) I don't use get method, since I am posting searches into database... I am using post method. Also I tried to set this code: into the template - <script type="text/javascript" src="http://dal-yourlabs.rhcloud.com/static/collected/admin/js/vendor/jquery/jquery.js"></script> and into the base.html-<link src="/static/collected/autocomplete_light/vendor/select2/dist/css/select2.css" type="text/css" media="all" rel="stylesheet" /> <link src="/static/collected/autocomplete_light/select2.css" type="text/css" media="all" rel="stylesheet" /> <script type="text/javascript" src="/static/collected/autocomplete_light/autocomplete.init.js"></script> <script type="text/javascript" src="/static/collected/autocomplete_light/select2.js"></script> Like it was advised in this post: Django: django-autocomplete-light does not work properly But it doesn't really help. What am I doing wrong? Thank you! -
Django - Send email with multiple dynamic images inline base64
I am building a system for sending bulk emails using django. on the frontend template: I have a div with quill where the user can customize his email with text , insert images etc`. also, an option to attach a file. in django views I have a function for sending the email. views.py: the relevant part: backend = EmailBackend(host="smtp.example.com", port=2525, username="example@eample.com", password="***", use_tls=True, fail_silently=False) email = EmailMultiAlternatives(subject, message, from_email, [], bcc=recepients, connection=backend) if request.FILES: uploaded_file = request.FILES['document'] email.attach(uploaded_file.name, uploaded_file.read(), uploaded_file.content_type) email.content_subtype = 'html' email.mixed_subtype = 'related' email.send() form.save() the problem is when a user inserting images into quilljs editor - it is converted to base64 data and email clients can read the images. I have found solutions when I know what images files are being send. for example: img_data = request.POST['image'] img = MIMEImage(img_data[img_data.find(",")+1:].decode('base64'), 'jpeg') img.add_header('Content-Id', '<file>') img.add_header("Content-Disposition", "inline", filename="file.jpg") msg.attach(img) but in my case , the user can insert several imagess, I do not have file names and do not know how to convert them to attached images. any solutions? options? thanks. -
django import export error in import xlsx
I don't understand why i'm getting this error. invoiceNumber is my primary key. -
Django & SQLite: how to prefetch when there is a limit on the number of variables
SQLite has a SQLITE_MAX_VARIABLE_NUMBER constant that controls the maximum number of variables that a SQL query can use. To illustrate, let's say I have these models: from django.db import models class A: name = models.CharField(max_length=20) class B: a = models.ForeignKey(A, on_delete=models.PROTECT) key = models.CharField(max_length=20) class C: b = models.ForeignKey(B, on_delete=models.PROTECT) value = models.CharField(max_length=20) Now, I have a bunch of A instances, for which I want to prefetch data transitively. A simple solution would be some_a_instances = A.objects.filter(name__in=search_input).unique() models.prefetch_related_objects( some_a_instances, 'b_set', 'b_set__c_set', ) But, depending on the cardinality of a <--> b and b <--> c, this may generate SQL queries with more variables than allowed by SQLITE_MAX_VARIABLE_NUMBER. So far, I've used a simple workaround - split the input in smaller chunks and prefetch each chunk sequentially. def chunks(items, chunk_size=100): return [items[i:i + chunk_size] for i in range(0, len(items), chunk_size)] for a_chunk in chunks(some_a_instances): models.prefetch_related_objects( a_chunk, 'b_set', 'b_set__c_set', ) But that doesn't work in every situation (for example, if one A instance is linked to a large number of Bs, or one B linked to a large number of Cs). Is there any way to tell django to prefetch (transitively), with at most N variables in each query ? Notes Let's … -
Django Rest Framework - Register user with email verification
I'm working on DRF project. I use email as a unique username in my own user model and using jwt as authentication. I made everything but cannot implement email verification when create user model. I was thinking of making token of user and use it to make user activate after first logged in. So I tried to override every single methods in generics.createAPIView and django.contrib.auth.tokens.PasswordResetTokenGenerator. And now it seems like impossible. I coulnd't find any information who made it with DRF. I want to do email verification before user model is actually written in database, and if it succeed, then write in database. I'm using vue as front-end so what I want is [ vue(register page) --> drf(check if it's validate) --> send mail to request.data['email'] --> click the link in email and finish registration --> drf(finish register and write in database) ] Is there any possible way to make it with override on methods of CreateAPIView? -
Use Django Rest Framework Tokens to authorise someone [closed]
I can't think of a more descriptive title, but what I mean is, when I am writing a Python script that scrapes from the API, how can I authorise myself in the Python file as if I was a real user wanting to utilise the API? So if I were to be using the requests library, how would I add authorisation to it, so I could access the API? -
Django | prefetch_related() exclude parent object without child/children object/s
Taken from Django's documentation, suppose that you have the following models: from django.db import models class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) def __str__(self): return "%s (%s)" % ( self.name, ", ".join(topping.name for topping in self.toppings.all()), ) Running the code below will return all Pizza objects and its related Toppings object/s. Pizza.objects.all().prefetch_related('toppings') Question, what if you would like to look for all Pizza's with specific Topping/s. Will filter on prefetch_related work like the code below? Won't it return all Pizza objects even without the Toppings specified? If so, will it be possible to return only those Pizza's with the filtered Toppings? toppings_q = Q(name='Pepperoni') & Q(name='Ham') & Q(name='Bacon') Pizza.objects.all().prefetch_related( Prefetch( 'toppings', queryset = Toppings.objects.filter(toppings_q) ) ) Thank you. -
How to get user and associated group permissions in Django Rest Framework?
I want to serialize the user and associated group permissions and make them available via an API endpoint. However, I can only retrieve the permissions that are directly assigned to the user, not those that come from the parent group. API Call containg user and group permissions: "user": { "id": 35, "username": "HII", "email": "asdsa@test.de", "user_permissions": [ 9, // Example User Permission Currently Retrieved 11, // Example User Permission Currently Retrieved 6, // Example Group Permission Currently Not Retrieved 8 // Example Group Permission Currently Not Retrieved ] } User API View # Get User API class UserAPI(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user User Serializer # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: user_permissions = serializers.SerializerMethodField('get_user_permissions') model = User fields = ('id', 'username', 'email', 'user_permissions') def get_user_permissions(user): if user.is_superuser: return Permission.objects.all() return user.user_permissions.all() | Permission.objects.filter(group__user=user) The standard django user model is used. How is it possible to retrieve the group permissions associated with a user. I am happy about every hint. -
Django app with real-time script output console
I have a Django app which executes a script. Now I want to display the out put of the script in real-time. I have some questions regarding the implementation of the same. I suppose I can use channels to push each line as they get generated into the front end and display them. But if another user opens the same page he will only be seeing latest lines and not the initial lines pushed. I can use a generator function to simulate kind of a tailf on the filename to get the lines. But where would this code reside and how to trigger it when someone visits the log pages(there would be multiple jobs running at the same time) What would be the best and simple way to achieve this. -
systemd service for Gunicorn for Django
I am using a vps with ubuntu 18.04 and I have created below systemd service for Gunicorn for my Django application with postgres as database : [Unit] Description=Gunicorn After=network.target [Service] Type=simple User=django ExecStart=/bin/bash /home/django/bin/start-server.sh Restart=on-failure [Install] WantedBy=multi-user.target but after enabling gunicorn I have Server Error (500). And the error says: OperationalError at / FATAL: Peer authentication failed for user "root" what I have to do to make it right? -
The view formApp.views.formRegister didn't return an HttpResponse object
Views.py from django.shortcuts import render from . models import Registerform # Create your views here. def formRegister(request): if request.method == 'POST': if request.POST.get('firstN') and request.POST.get('lastN') and request.POST.get('Email') and request.POST.get('pass'): Registerform = Post() Registerform.firstName = request.POST.get('firstN') Registerform.lastName = request.POST.get('lastN') Registerform.email = request.POST.get('Email') Registerform.password = request.POST.get('pass') Registerform.save() return render(request, 'formApp/formreg.html', context_instance=RequestContext(request)) Error Screenshort As you can see in the above error image, my code is not functioning properly. I have added my models.py and views.py code. Please help me to resolve the issue. -
django rest JSON API results as list by key
I have a very basic API made with Django Rest Framework with an output as follows: [ { "name": "John", "city": "chicago", "age": "22" }, { "name": "Gary", "city": "florida", "age": "35" }, { "name": "Selena", "city": "vegas", "age": "18" } ] I want to convert it to the following format to simplify the usage of its data in charts. { "name": ["John", "Gary", "Selena"] "city": ["chicago", "vegas", "florida"] "age": ["22", "35", "18"] } Is there a simple way this can be done in Javascript (and Python just for curiosity)? Can this be proactively solved by adjusting the Serializer or the ViewSet in DRF? -
Django form.cleaned_data.get('field') has no attribute str
I search but didnt find any solution views.py code: def register(request): form = RegisterForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') newUser = User(username = username) newUser.set_password(password) newUser.save() login(request, newUser ) messages.success(request, 'Registering Succeed') return redirect('index') else: return render(request, "register.html", {'form':form}) forms.py code: class RegisterForm(forms.Form): username = forms.CharField(max_length=20, min_length=6, required=True, label="Username") password = forms.CharField(max_length=18, min_length=6, widget=forms.PasswordInput, label="Password", required=True) confirm = forms.CharField(max_length=18, min_length=6, widget=forms.PasswordInput, label="Password Confirmaation", required=True) def clean(self): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') confirm = self.cleaned_data.get('confirm') if password != confirm: raise forms.ValidationError("Passwords are not same") else: return I get an error that 'str' object has not attribute 'get'