Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin won't find uploaded files
I have a Django 3.0 Model with a FileField: # models.py class Profile(models.Model): ... photo = models.FileField( upload_to='photos/', help_text='Select photo to upload' ) My settings.py file defines MEDIA_ROOT in terms of BASE_DIR as BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) MEDIA_ROOT = os.path.join(BASE_DIR, 'myApp/static/myApp/') and I've confirmed that MEDIA_ROOT = ~me/ProjectRoot/myProject/myApp/static/myApp/ exactly as I intend. When I upload a photo file through the Profile Admin "add" page, that photo appears in the folder ~me/ProjectRoot/myProject/myApp/static/myApp/photos/ exactly as intended. When I revisit that Profile's Admin "change" page, the upload widget displays as Currently: photos/uploaded_photo.png [ ] clear Change: [Browse] No file selected. showing a link that's ostensibly to the file I've already uploaded. The link itself is to http://127.0.0.1:8000/admin/myApp/profiles/9/change/photos/uploaded_photo.png (here, '9' is the primary key id of the Profile in question in the database). When I select the link, instead of viewing the uploaded photo, the Admin home page loads with a warning banner at the top that says "Profile with ID “9/change/photos/uploaded_photo.png” doesn’t exist. Perhaps it was deleted?" If I go to the database itself, I can clearly see that the Profile exists there: mysql> SELECT * FROM myApp_profile; +----+----------------------------------+ | id | photo | +----+----------------------------------+ ... | 9 | photos/uploaded_photo.png | I also double-checked … -
Django and nginx - docker - problem with adding add worker_connections. nginx - directive is not allowed here
I'm having trouble adding nginx worker connections to the config this is my config nginx worker_processes 1; events { worker_connections 10240; # increase if you have lots of clients } http { upstream my-app { server web-prod: 8000; } server { listen 80; server_name my-app.com; client_max_body_size 4G; access_log off; gzip on; gzip_min_length 10240; gzip_comp_level 1; gzip_vary on; gzip_proxied expired no-cache no-store private auth; gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml application/atom+xml font/truetype font/opentype application/vnd.ms-fontobject image/svg+xml; # allow the server to close connection on non responding client, this will free up memory reset_timedout_connection on; # request timed out -- default 60 client_body_timeout 10; # if client stop responding, free up memory -- default 60 send_timeout 2; # server will close connection after this time -- default 75 keepalive_timeout 30; # number of requests client can make over keep-alive -- for testing environment keepalive_requests 100000; location / { proxy_pass http://my-app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /usr/src/app/my-app/staticfiles/; expires 365d; } location /mediafiles/ { alias /home/app/web/mediafiles/; } } } my dockerfile nginx FROM nginx:stable RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d error nginx nginx: [emerg] "worker_processes" directive is not allowed here in /etc/nginx/conf.d/nginx.conf:1 … -
Getting Error While Creating the superuser in Terminal
AttributeError: 'UserManager' object has no attribute 'create_superuser' -
How do I perform query in django templates
I have Two Modeks, Employee Type and Employees: class EmployeeType(models.Model): type = models.CharField(max_length=500) enable = models.BooleanField(default=True) class Employee(models.Model): date = models.DateTimeField(default=timezone.now) emptype = models.ForeignKey(EmployeeType, on_delete=models.CASCADE, verbose_name='Type') male = models.IntegerField(verbose_name='Male', default=0) female = models.IntegerField(verbose_name='Female', default=0) others = models.IntegerField(verbose_name='Others', default=0) This is the relevant view from my forms.py class EmployeeForm(forms.ModelForm): class Meta: model=Employee exclude = ('date',) def __init__(self, *args, **kwargs): super(EmployeeForm, self).__init__(*args, **kwargs) self.fields['emptype'].widget.attrs = {'class':'form-control'} self.fields['male'].widget.attrs = {'class':'form-control','placeholder':'Male'} self.fields['female'].widget.attrs = {'class':'form-control','placeholder':'Female'} self.fields['others'].widget.attrs = {'class':'form-control','placeholder':'Others'} and here is views.py: def addEmployee(request): employee = EmployeeForm(request.POST or None) context = { 'employees':employee, } return render(request,'add_employee.html',context) and here is my add_employee.html <div class="form-group"> <table class="table"> <thead> <tr> <th scope="col">Type</th> <th scope="col">Male</th> <th scope="col">Female</th> <th scope="col">Others</th> </tr> </thead> <tbody> {% for em in employees.emptype %} <tr> <td>{{em}}</td> <td><input type="number" name="male_{{em.id}}" step="any" required="" id="id_male" class="form-control" value="0" ></td> <td><input type="number" name="female_{{em.id}}" step="any" required="" id="id_female" class="form-control" value="0" ></td> <td><input type="number" name="others_{{em.id}}" step="any" required="" id="id_others" class="form-control" value="0"></td> </tr> {% endfor %} </tbody> </table> </div> Now I am facing problem in getting EmployeeType ID in name field i.e. {{em.id}}. How I can fix this? -
login to testcase in graphene django - any method doesn't work
I'm trying to test my mutation according to graphene django documentation. the mutation works with @login_required decorator and there's a problem because any method of login to test doesn't work. I tried with self.client.login, self.client.force_login. I've even made a tokenAuth mutation, and hardcoded some credentials there and it also doesn't work; the user is still Anonymous. def test_create_member_mutation(self): response = self.query( ''' mutation createMember($firstName: String) { createMember(firstName: $firstName) { member { id } } } ''', op_name='createMember', variables={'firstName': 'Foo'} ) self.assertResponseNoErrors(response) -
Django - Filter by related name twice causes duplication of objects in queryset
I am facing issues with filtering using related_name. Here is my code: Basically I am first getting the department and using that to filter the LeadSources that have a One To Many relations to the Customer Information model. However, when I run the second filter, the number of Lead Sources would suddenly turn from 2 to 4, or 3 to 9 (essentially i think it squares itself im not sure why though) department = UserProfile.objects.get(user=self.request.user).department d = department.all()[0] qs = LeadSource.objects.filter(customers__salesDepartment = d) print(qs) qs = qs.filter(customers__created_date__range=(start, end)) # filtering error is from here print(qs) Here is my models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) salesDepartment = models.ForeignKey(SalesDepartment, blank=True, null=True, on_delete=models.CASCADE) source = models.ForeignKey('LeadSource', related_name='customers', on_delete=models.CASCADE, null=True, blank=True) created_date = models.DateField(default=timezone.localdate) class LeadSource(models.Model): source_id = models.AutoField(primary_key=True) source = models.CharField(max_length=500) def __str__(self): return self.source Here is the output from the two prints above First print: <QuerySet [<LeadSource: Facebook>, <LeadSource: Twitter>, <LeadSource: Facebook>, <LeadSource: Instagram>, <LeadSource: Twitter>]> Second print: <QuerySet [<LeadSource: Facebook>, <LeadSource: Facebook>, <LeadSource: Twitter>, <LeadSource: Twitter>, <LeadSource: Facebook>, <LeadSource: Facebook>, <LeadSource: Twitter>, <LeadSource: Twitter>]> All help is appreciated, thanks all! I really do not know what is causing this error, but could it be due to me using … -
Django Comments User Form
I'm new to the forum. Hope everyone's well I started learning Django about a month ago and just finished Django for Beginners by William S. Vincent. The book ends with Chapter 15: Comments and shows how the admin can add comments to posts. Q: Can someone, please, show me or point me in the right direction as to how to create a User Form so that registered users can also add comments to the Blog posts? Is there perhaps a 3rd party app for that? What I have so far: Models: class Article(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='images/', null=True, blank=True, height_field=None, width_field=None) upload = models.FileField(upload_to='files/', null=True, blank=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.title def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comment') comment = models.CharField(max_length=140) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse('article_list') forms.py class PostForm(forms.ModelForm): class Meta: model = Article fields = ('title', 'body', 'image', 'upload') class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment', 'author') Views: class ArticleListView(LoginRequiredMixin, ListView): model = Article template_name = 'article_list.html' comment_form = CommentForm login_url = 'login' class ArticleDetailView(LoginRequiredMixin, DetailView): … -
Check permission for each item in Django InlineModelAdmin
In django InlineModelAdmin methods, the obj parameter is parent object being edited or None when adding a new parent. I want to override has_change_permission method of InlineModelAdmin to check permission for each item. so i need current item object, not parent object. for example, i have an InlineModelAdmin for comments of an article. and just owner of comment must has permission to edit his comment. but i can't implement this logic with only parent object. -
ModuleNotFoundError in heroku
The following is the part of log i retrieved. 2020-06-13T12:45:56.559432+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load 2020-06-13T12:45:56.559432+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked 2020-06-13T12:45:56.559433+00:00 app[web.1]: ModuleNotFoundError: No module named 'berncodes_project.wsgi' 2020-06-13T12:45:56.559522+00:00 app[web.1]: [2020-06-13 12:45:56 +0000] [10] [INFO] Worker exiting (pid: 10) 2020-06-13T12:45:56.584694+00:00 app[web.1]: [2020-06-13 12:45:56 +0000] [11] [INFO] Booting worker with pid: 11 2020-06-13T12:45:56.592976+00:00 app[web.1]: [2020-06-13 12:45:56 +0000] [11] [ERROR] Exception in worker process 2020-06-13T12:45:56.592978+00:00 app[web.1]: Traceback (most recent call last): 2020-06-13T12:45:56.592979+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-06-13T12:45:56.592979+00:00 app[web.1]: worker.init_process() 2020-06-13T12:45:56.592980+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-06-13T12:45:56.592980+00:00 app[web.1]: self.load_wsgi() 2020-06-13T12:45:56.592981+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-06-13T12:45:56.592981+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-06-13T12:45:56.592982+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-06-13T12:45:56.592983+00:00 app[web.1]: self.callable = self.load() 2020-06-13T12:45:56.592983+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-06-13T12:45:56.592983+00:00 app[web.1]: return self.load_wsgiapp() 2020-06-13T12:45:56.592984+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-06-13T12:45:56.592984+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-06-13T12:45:56.592985+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/gunicorn/util.py", line 358, in import_app 2020-06-13T12:45:56.592985+00:00 app[web.1]: mod = importlib.import_module(module) 2020-06-13T12:45:56.592990+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module 2020-06-13T12:45:56.592991+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-06-13T12:45:56.592991+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1006, in _gcd_import 2020-06-13T12:45:56.592992+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 983, in _find_and_load 2020-06-13T12:45:56.592992+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 965, in … -
Can I change the secret key in django
I thought the secret key was just something like a password, so I changed it. Now I found out that it is used to make hashes and that kind of stuff. So can I just type anything I want in the secret key field, or is a special algorythm needed? Thx for your help and stay healthy! -
python manage.py collectstatic - 0 static files copied
Good day, I`m trying to run the command on the bash of pythonanywhere: python manage.py collectstatic below I paste the output. Any suggestion? (science.pythonanywhere.com) 12:36 ~/science.pythonanywhere.com (master)$ python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /home/science/science.pythonanywhere.com/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes 0 static files copied to '/home/science/science.pythonanywhere.com/sta tic', 130 unmodified. -
When django load data to memory?
Lets have simple model: class NewModel(models.Model): json_data = models.JSONField(default=dict) Then lets get it: model = NewModel.objects.get(pk=1) # 1 data = model.json_data # 2 value = data.get("key") # 3 Because json_data is pretty big (about 1-2MB per value, and min. 20 values) question is, when django load data to memory? If I understand correctly then 1 only return point to model but not load it. So it load on attribute call? Or when .get is called? I want to understand how it works and optimise loading, so I will not load values that are unnecessary. -
Integrity error, field _id empty upon form submission
I have a form where logged-in users can add new profiles. I'd like to track who created what, so I thought I'd just add a created field to the Profile model and pass the current use to the form. It should pretty straight-forward. Nevertheless I keep getting an integrity error, as if the current user is always empty. Why is that? Is it because I have another key to the user model? models.py: class User(AbstractBaseUser): name etc. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile', null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='submitter') forms: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = [[...] 'created_by'] views: def profile_add_view(request): form_profile = ProfileForm(initial={'created_by': request.user}) #or request.user.id, that doesn't change the output of the error. [...] I get: IntegrityError at /private/profile-add/ (1048, "Column 'created_by_id' cannot be null") -
Django authenticate() not working from HTML post
The authenticate() is not working, but I can't specify the error its just not working. everytime I click login. its just refresh the page and nothing happens. please help, thanks! @views.py def loginUser(request): if request.user.is_authenticated: return redirect('home') else: if request.POST == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) redirect('home') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context) @login.html <form method="POST" action=""> {% csrf_token %} <label class="label">Username</label> <input type="text" class="form-control" placeholder="Username"> <label class="label">Password</label> <input type="password" class="form-control" placeholder="Password"> <button class="btn btn-primary submit-btn btn-block">Login</button> </form> @urls.py urlpatterns = [ path('login/', loginUser, name='login'), path('logout/', logoutUser, name='logout') ] -
Python generate tets image file in memory
i have been trying a few solutions that i found here but non of the is able to pass validation by https://docs.python.org/3.8/library/imghdr.html IMGHDR built-in python module via imghdr.what() method. Question is - is it possible generate in-memory image file in a such a way that it would pass validation by imghdr.what()??? Needed for Django tests. Thanks. -
no such table: auth_user
i was trying to login but is is showing this error after entering username and password but it is showing following error no such table: auth_user my forms.py from django import forms class login_form(forms.Form): username=forms.CharField(max_length=64) password=forms.CharField(widget=forms.PasswordInput()) my views.py from django.shortcuts import render from .forms import login_form from django.contrib.auth import authenticate,login,logout def login_view(request): if request.method=="POST": form=login_form(request.POST) if form.is_valid(): u_name= form.cleaned_data['username'] passwrd= form.cleaned_data['password'] user=authenticate(username='u_name',password='passwrd') if user is not None: if user.is_active: login(request, user) else: print('the account has been disabled') else: print ("the username or password is incorrect" ) else: form=login_form() return render(request,'users/login.html',{'form' :form}) my settings.py INSTALLED_APPS = [ 'memeroom.apps.MemeroomConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] what should i do now -
Django - timestamp fields in model
Found this answer to the same question here Timestamp fields in django but I think I'm missing something - shouldn't saving timestamps in django models be easier than having to create your own timestamp field? I have a model that has a DateTimeField field. To feed that field, I am using a datetime object. But I have just realized that datetime object doesn't actually include timezone, so I would be better off just directly storing the timestamp, as originally I'm getting this data from an API in timestamps anyway. Any more straightforward way to do this than in the answer above? -
How do I use Django queryset in jQuery/javascript
I am trying to implement Django queryset in jQuery/javascript. I was able to get the list of all users but i could not get the users profile picture. Username display, but users image do not display as an image, it display as a text ( John). How do i get the users profile picture for each user? This is what i tried: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True) def home(request): all_img = Profile.objects.all() context = { 'all_img': all_img, } $(function() { var availableTags = [ {% for user in all_img %}{% if user.profile_pic %} "<img src='{{ user.profile_pic.url }}'>" + "{{user|safe}}", {% endif %}{% endfor %} ]; $(".autocomplete").autocomplete({ source: availableTags, }) }); -
Code Reference for Django in PyCharm Professional not working
In a urls.py file like this: urlpatterns = [ path('', include('myapp.urls')) ] Or, views.py like this: template_name = 'myapp/index.html' When I press Ctrl key and hover over 'myapp.url' or 'myapp/index.html', I should be able to go to these files after clicking on these both strings. This is also known as "Code Referencing" as most of the people know. But, in my PyCharm Professional Edition, I am not able to do so. I cannot do as described here. -
Cannot resolve keyword 'ti' into field. Choices are: author, author_id, categories, comment_count, featured, id, overview, thumbnail
I am beginner to django, I am following youtube to create simple from a template while implementing get_absolute_url() I am getting error : Cannot resolve keyword 'ti' into field. Choices are: author, author_id, categories, comment_count, featured, id, overview, thumbnail, timestamp, title, view_count models.py # Create your models here. class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) comment_count = models.IntegerField(default =0) view_count = models.IntegerField(default =0) author = models.ForeignKey(Author, on_delete = models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) view.py def blog(request): most_recent = Post.objects.order_by('-timestamp'[0:3]) post_list = Post.objects.all() paginator = Paginator(post_list, 4) page_request_var ='page' page = request.GET.get(page_request_var) try: paginated_queryset = paginator.page(page) except PageNotAnInteger: paginated_queryset = paginator.page(1) except EmptyPage: paginated_queryset = paginator.page(paginator.num_pages) context = { 'queryset' : paginated_queryset, 'most_recent' : most_recent, 'page_request_var': page_request_var } return render(request, 'blog.html', context) def post(request, id): return render(request, 'post.html', {}) Like where am I going wrong I am not understanding. I also nearly same error on stack but still not so clear regarding this topic please help understand and provide the solution. -
HTTPError: 500 while trying to post data using requests.post() in Django framework (python program)
Somebody Kindly help me out here. I'm trying to process few text files in a directory and convert them into dictionary. Then I'm trying to upload through the DJANGO REST API using requests.post() but I'm getting requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: http://34.72.26.221/feedback. My code is as follows: #!/usr/bin/env python3 import os import requests import glob dirloc = r"/data/feedback/" d = {} for file in glob.iglob(dirloc+ '*'): if not file.startswith('.'): with open(file,'r') as f: d["title"] = f.readline().strip("\n") d["name"] = f.readline().strip("\n") d["date"] = f.readline().strip("\n") d["feedback"] = f.readline().strip("\n") print(d) #used for troubleshooting only# r = requests.put("http://34.72.26.221/feedback", data = d) print(r.status_code) I'm new to coding and still figuring out things. So this post may be missing some needed info. Please let me know if I need to add anything. -
Django Password hiding on admin page from model
I am working on my User model on my models.py page. I added a password (even after importing the User). The issue is that when i log in into the 127.0.0.1:8000/admin page and want to add a profile/user, the password isnt hidden and it shows what im typing. I thought i encrypted it but i dont think i did anything of that sort. I have read all the documentation but i cant seem to find my answer. heres my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=80) REQUIRED_FIELDS = [] USERNAME_FIELD = 'username' -
django server is showing no result
I started working on django ( read the django documentation and several youtube tutorials ) I dont understand what is wrong , the editor is not showing any errors ( VSCode ). When I start the server it is showing me the default rocket icon ....I have tried reinstalling django but it also didnt help....also restarted the server several times. I am stuck right now. main url file from django.contrib import admin from django.urls import path, include urlpatterns = [ path('calc/',include('calc.urls')), path('admin/', admin.site.urls), ] url file for the app (calc) from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index') ] views file for the app from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return HttpResponse("Hello World") -
the local server isn't opening after joining templates
well i wanted to access template file in django I also gave directory through settings.py specified my path in urls.py but it didn't worked when opened local server since i was using visual studio 2019 it had some files default so I tried putting two files in render was this causing the problem -
Invalid Form in the View with Multiple Forms
I am trying to put 2fa in a single page on the registeration View. I was following this advice to put forms inside a single View answer. Code below: Actually I have two questions: While i'm checking the validity of my form rform.is_valid() -> False it returns false, even though I had seperate the two forms. While I submit the first form 'rform' I just want it to send an SMS so I don't want to refresh the page because it erases the password field which already filled. Is there anyway to do this? the return statment return self.render_to_response({'rform': rform, 'tform': tform}) returns everything filled except the password. Thank you for the answers form class RegisterForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Konfirmasi Password', widget=forms.PasswordInput) class Meta: model = Account fields = ('phone_number', ) widgets = { 'phone_number': PhoneNumberPrefixWidget(initial='+62'), } labels = { 'phone_number': 'Phone Number', } def clean_password2(self): # Check that two passwords match password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Password don't match") validate_password(password2) return password2 def save(self, commit=True): #saved provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user class TokenForm(forms.Form): token = forms.CharField( …