Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-templated-email not connecting to my template file
I am sure that i have set up everything correctly and my template file welcome.email is in right folder but somehow when sending email, it is not showing as my template has been connected. Here is my view for django-template-email: def send(request, pk): if request.method == "POST": data = json.loads(request.body) trainingtitle = data['trainingtitle'] name = data['name'] email = data['email'] send_templated_mail( template_name='welcome', from_email='austin.roose1@gmail.com', recipient_list=['austin.roose1@gmail.com'], context={ 'email': email, 'name': name, 'trainingtitle': trainingtitle, }, ) return redirect('/api/') And i have also in my settings.py file: TEMPLATES = [ { 'DIRS': [os.path.join(BASE_DIR, 'templates')], My welcome.email file looks like: {% block html %} <p>Hi {{name}},</p> <p>You just signed up for my website, using: <dl> <dt>username</dt><dd>{{name}}</dd> <dt>join date</dt><dd>{{email}}</dd> </dl> </p> <p>Thanks, you rock!</p> {% endblock %} But my sent email looks like: As you can see it shows 'username' and 'full name' in there although i don't have them in my template. What should i change? -
Can't create DB on Heroku
I have deployed my Django app on Heroku, in Heroku bash I ran python manage.py migrate, but it still returns error Exception Value:no such table: project_sliderimage. Also checked if db was created with heroku addons and db state is created. -
Starting python django server, with task Schedular
I have a django project, which i want to always start when ever the computer starts. I have created a bach file to run surver, and open the project in a browser. When i click on it, it runs the server and opens the browser. But when i put in task schedular, it only opens the browser but doesn't run server. this is my batch file. @ECHO OFF start cmd.exe /C "python manage.py runserver && cd C:\myproject" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" -
I want to add create bar with add button in Django
I am new to django and kind of confuse why it's not working I making list website where you add something on list and it updates shows the new added element on the same page. I am almost done the only thing left is creating new element where i am facing problem. Thank you models.py:- from django.db import models from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse # Create your models here. class simpleList(models.Model): title = models.CharField(max_length=250) def __str__(self): return self.title views.py:- from django.shortcuts import render, get_object_or_404 from .models import simpleList from django.views.generic import ListView, DeleteView, CreateView from django.urls import reverse_lazy from django.contrib.messages.views import SuccessMessageMixin # Create your views here. class ListListView(ListView): model = simpleList template_name = 'list_list.html' class DeleteList(SuccessMessageMixin, DeleteView): model = simpleList success_url = reverse_lazy('list_list') success_message = "deleted..." def delete(self, request, *args, **kwargs): self.object = self.get_object() title = self.object.title request.session['title'] = title return super(DeleteView, self).delete(request, *args, **kwargs) class CreateList(CreateView): model = simpleList template_name = 'list_list.html' urls.py:- from django.urls import path from .views import ListListView, DeleteList, CreateList from django.conf.urls import url from . import views urlpatterns = [ path('', ListListView.as_view(), name='list_list'), path('<int:pk>/delete/', DeleteList.as_view(), name='delete_view'), path('new/', CreateList.as_view(), name='create_list'), ] list_list.html:- {% extends 'base.html' %} {% block … -
Is it possible to inform Webpack that asset was used in Django template?
I have a project, I use both Django and Webpack for bundling and process assets. My goal is to make Webpack process all assets, e.g. optimize images. If image is used in js / css file there is no problem. Things are going complicated when I use img only in Django template. Is there a way to 'inform' Webpack, that particular img is used, and update path for it in django template after webpack process it ? -
@login_required decorators doesn't wok perfectly though signout is done,we can still go back to index page
Although using @login_required on index page, if Signout is done and redirect to login page, again we can visit the index page by clicking the back arrow in browser. Is there any mistake on code? views.py in expenses from django.contrib.auth.decorators import login_required @login_required(login_url='/authentication/login') def index(request): expenses = Expense.objects.filter(owner=request.user) urls.py from django.views.decorators.csrf import csrf_exempt urlpatterns = [ path('register', RegistrationView.as_view() , name ="register"), path('login', LoginView.as_view(), name="login"), path('logout', LogoutView.as_view(), name="logout"), path('validate_username', csrf_exempt(UsernameValidationView.as_view()), name="validate_username"), path('validate_email', csrf_exempt(EmailValidationView.as_view()), name="validate_email") ] view.py in authentication class LogoutView(View): def post(self,request): logout(request) messages.warning(request, 'You have been Logout!!') return redirect('login') class LoginView(View): def get(self, request): return render(request, 'authentication/login.html') -
Possibly empty Foreign Key in forms.py leads to not null constraint fail
I have a class customer, that holds some information, for example a contact person for this customer. This field can be empty and the model shows simplified as follows: model: class Customer(models.Model): name = models.CharField('Company name', max_length=120) contact_persons = models.ForeignKey(ContactPerson, blank=True, null=True, on_delete=models.CASCADE) The corresponding view: class CustomerCreateView(CreateView): model = Customer template_name ="gap/add_customer.html" form_class = CustomerModelForm success_url = reverse_lazy('customer-list') And the form: class CustomerModelForm(ModelForm): required_css_class = "required" class Meta: model = Customer fields = "__all__" Now, when I enter the data I always end up in a NOT NULL constraint failed: gap_customer.contact_persons_id. How would I solve this? -
What will happen if I migrate django models directly from the mysql databse
Earlier i had this as my model class. class Certificate(models.Model): User = models.AutoField(primary_key=True) but after few months i added "data field" into my model class directly from the sql and without using migrations. Now i am just wordering if i change the code in my models and again make migrations, will it work? class Certificate(models.Model): User = models.AutoField(primary_key=True) data = models.TextField(null=True, blank=True) Can anyone suggest me? -
How to mark a special group from the set of groups to which a user belongs?
I would like to add a field in a custom User model indicating the role, which the user currently holds, i.e. mark the group from the set of groups to which the user belongs. One way to do that is to add to User a FK referring to Group, like this: from django.contrib.auth.models import AbstractUser class User(AbstractUser): current_role = models.ForeignKey(Group, verbose_name="Current role", blank=True, null=True, on_delete=models.SET_NULL) However, this means that the data consistency has to be preserved with some additional coding, e.g. in case the current role of the user is removed from the set of groups (roles) he belongs. In order to avoid this, maybe the foreign key could refer to the intermediate table auth_user_groups, instead of Group. Is this a valid option or is there another smart way to solve this issue? -
how to open a folder got as response from a website
I sent Post data to a server and it returned me something.I stored the response in "responsedata" like this responsedata = requests.post(url,data=payload) to know what has been returned i did print(responsedata,responsedata.content) the output in cmd prompt was <Response 200> b'charts/chart.xyz.png' now it looks like the website returned me an image (.png) but its probably in the "charts/" folder.what should i do to save the image to my database(django).(I dont know what tags to use for this,so I have put the lang and package i am using) -
How to get account confirmation key from django email
I have spent days on this so thanks in advance for anyone that can help! I am testing Django AllAuth and need to test the account confirmation link. It contains a key generated by EmailConfirmationHMAC at the end of a link, a la: "thanks for registering! click here to activate: http:/site/confirm/1093840493 I need to be able to extract the 1093840493 part so that I can test it. This question asked for something similar: How to test email confirmation? But my django.core.mail has no 'outbox'. I'm using Django 2.2 and Python 3.6 I can generate a new confirmation but I hope to be able to capture the confirmation as it is initially sent out upon registration. Thanks again for your help. -
Cannot connect to redis://:**@redis:6379//: AUTH <password> called without any password configured for the default user
I have a Django project that works with Celery. The problem is that when I run celery with supervisor, it cannot connect to redis. The project is built using Docker. This is my code: settings.py : CELERY_BROKER_URL = 'redis://:%s@%s:%s' % \ ('foobared', os.environ.get('redishostname', 'localhost'), os.environ.get('redisport', 6379)) CELERY_RESULT_BACKEND = 'redis://:%s@%s:%s' % \ (os.environ.get('redispassword', 'foobared'), os.environ.get('redishostname', 'localhost'), os.environ.get('redisport', 6379)) CELERY_RESULT_PASSWORD = os.environ.get('redispassword', 'foobared') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE CELERYD_USER = "celery" CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' docker-compose.yml: version: '2' networks: app-tier: driver: bridge services: web: build: ./ command: bash -c "python manage.py makemigrations && python manage.py migrate && tail -f /dev/null" ports: - "${webport}:8000" env_file: - ./.env networks: - app-tier redis: image: 'bitnami/redis:latest' environment: - ALLOW_EMPTY_PASSWORD=yes networks: - app-tier When I open the CLI of web container and run suoervisor, it executes following file celeryd_start.sh: NAME="orion-amr" && cd .. && DJANGO_SETTINGS_MODULE=orion-amr.settings && exec celery -A $NAME worker -l INFO So, Celery doesn't exit but in logs file there are following errors: [2020-07-29 06:32:27,085: ERROR/MainProcess] consumer: Cannot connect to redis://:**@redis:6379//: AUTH <password> called without any password configured for the default user. Are you sure your configuration is correct?. Trying again in 32.00 seconds... -
Heroku-Django: App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz
Enumerating objects: 261, done. Counting objects: 100% (261/261), done. Delta compression using up to 4 threads Compressing objects: 100% (243/243), done. Writing objects: 100% (261/261), 5.48 MiB | 251.00 KiB/s, done. Total 261 (delta 54), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to newtonnation. remote: To https://git.heroku.com/newtonnation.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/newtonnation.git' I don't know why am i getting this error, I've tried adding buildpack (heroku/django) still no change. Please Help me. I am using heroku for first time -
Does django render send data to browser using GET or POST?
I am not quite sure how the Django render and HttpResponse actually works. I am sending information to the django view using ajax GET. But i don't really know how the server responds when using render. My ajax code is below:- function get_form_data(){ var url = $("#id_get_form_data_url").val(); var company = $("#id_supplier").val(); if(company){ $.ajax({ url:url, datatype: 'json', data: { 'company':company }, success: function(data){ // $("#id_get_form_data_url").val(); $("#id_sale_order_form").html(data); $("#id_supplier").prop('required',false); // console.log(data); } }) } } the view function below simply filters values of sale_order form field based on the selection of company form field which i pass to the function in ajax GET request. def GetFormData(request): if request.GET.get('company') == "": data = 0 form = SaleOrderInvoiceForm() return render(request,'saleorderinvoicesapp/_form_saleorderinvoice.html',{'form':form}) company_id = request.GET.get('company') sale_order_list = SaleOrder.objects.filter(supplier__id=company_id) form = SaleOrderInvoiceForm() form.fields['sale_order'].queryset = sale_order_list form.fields['supplier'].initial = company_id print(request.method)# this prints GET return render(request,'saleorderinvoicesapp/_form_saleorderinvoice1.html',{'form':form}) As per my understanding, the same request method is used in the render function which in this example is GET What i need to know is, if it is possible to change this request method to POST in view and then send the data to the client in a POST, and which is a preferred method to use if i need to send back … -
Automatically add order to the right customer in Django
I am trying to learn Django by making a database for a fictional dog kennel. One thing I don't understand is how I can automatically add a animal to a customer. What I mean by this is that when I go to my customer page (dynamic) I made a button to a form called AnimalsForm. In this form I have to select a customer again. I was wondering how I could make the form so that it automatically takes the customer from which page I entered the form. [My forms.py][1] [My models.py][2] [My animal form][3] [The button in the customer page][4] [The createanimal view][5] [My urls.py][6] [1]: https://i.stack.imgur.com/kbwR6.png [2]: https://i.stack.imgur.com/FeoZo.png [3]: https://i.stack.imgur.com/R6vU3.png [4]: https://i.stack.imgur.com/PfC6f.png [5]: https://i.stack.imgur.com/CDsRm.png [6]: https://i.stack.imgur.com/9sIJo.png Thanks for the help in advance! -
Why does the foreignkey show up as a dropdown box?
Hi Just wondering why when I try to include a foreign key in my model it shows up as a dropdown box rather than a textbox? Here is my models.py class VolunteerApplication(models.Model): volunteer_name = models.ForeignKey(VolunteerProfile, on_delete=models.PROTECT) phone_number = models.CharField(max_length=10)` This is what it shows up as on the website https://i.stack.imgur.com/bFd0V.png -
Django forms not validate, clean_data is empty, but queryDict is full, how to fix?
Django forms not accept my passed paramets, trying display clean data it nothing, also form i paste not like {{ form }}, just as is, cause it's imposible to convert to neded form, nut i set id the same as in {{ form }} fields. form <form id="fileRenderForm" class="translate__form" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="from-to-section"> <div class="form-dropdown"> <span class="">From</span> <div class="custom-select"> <span id="id_fromLanguage" data-value="0" class="selected-value">Search...</span> <div class="custom-search-select__wrapper"> <div class="custom-search-select"> <input type="text" class="search-select" id="myInput" onkeyup="searchFilter(this);" placeholder="Search for lang.."> <ul class="custom-select__items"> <li data-value="1">Search...</li> <li data-value="3">English</li> </ul> </div> </div> </div> </div> <button class="switch-text"></button> <div class="form-dropdown"> <span class="">To</span> <div class="custom-select"> <span data-value="0" id="id_toLanguage" class="selected-value">Search...</span> <div class="custom-search-select__wrapper"> <div class="custom-search-select"> <input type="text" class="search-select" id="myInput" onkeyup="searchFilter(this);" placeholder="Search for lang.."> <ul class="custom-select__items"> <li data-value="1">Search...</li> <li data-value="3">English</li> </ul> </div> </div> </div> </div> </div> <div class="additional-wrapper"> <div class="file-worker"> <input type="file" name="uploads" id="id_fileToRender" accept="image/jpeg,image/png,image/jpg,application/msword,application/plain,text/plain,application/excel," class="inputfile"> <label for="id_fileToRender" class="file-label"> <span>Upload file for calculation</span> <span class="file-add-block"> <div class="file-bar"> <span class="choosen_file">doc, docx, xls, pdf, jpeg, png</span> </div> <button class="add-file-notification"></button> </span> </label> </div> <div id="captcha-box" class="captcha-box"></div> <button class="calculate-btn upload-dtn" type="submit">Upload</button> </div> </form> this is view from django.conf import settings from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect # Create your views here. from .forms import renderFileForm from .services.services import * … -
'>' not supported between instances of 'int' and 'NoneType'. form.is_valid
I have error when try to create or update Category model. When I try save or edit with debuger this error does not arise and model saved. views.py def create(request): model = Category() if request.method == 'POST': form = CategoryForm(request.POST, instance=model) if form.is_valid(): form.save() return HttpResponseRedirect('/cabinet/category/') else: form = CategoryForm(instance=model) return render(request, 'cabinet/category/create.html', {'form': form}) form.py class CategoryForm(forms.ModelForm): name = forms.CharField(widget=TextInputCustom()) class Meta: model = Category fields = ['name'] models.py class Category(models.Model): name = models.CharField(unique=True) def __str__(self): return self.name -
Google Flexible App Engine 502 Server Error for Django app
I've hosted my Django app using Google's Flexible app engine custom runtime. It was working fine the last I checked & then I open the website now & I am getting 502 Server Error. It is not showing in the logs also.I'm attaching the screenshots of the HTML error, Logs, App Engine Error Graph, and an app.yaml file. The error on opening the website Logger in GCP showing no error The error graph on the GAE App.yaml file I have no idea why it suddenly started throwing this error. -
Django Model how to order by vote time?
So I have three models, User, Post, and UserVote: User is default django.contrib.auth user Post definition: class Post(models.Model): num_likes = models.IntegerField(default=0) num_dislikes = models.IntegerField(default=0) # when deleting users, we should simply set user.is_active to False, # that way this doesn't break user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=200, default="") UserVote: class Action(models.TextChoices): UP = 'u' DOWN = 'd' class UserVotes(models.Model): voter = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ForeignKey(Post, on_delete=models.CASCADE) type = models.CharField(max_length=2, choices=Action.choices, default=Action.UP) time = models.DateTimeField('time voted on', default=timezone.now) class Meta: unique_together = ('voter', 'item') On a user's profile page, I want to return the posts a user upvoted in descending order of when their vote was cast. I'm kind of lost here. I can return the posts a user voted on that aren't theirs as such: def get_users_liked_defs(user_id): Post.objects.filter(uservotes__voter__id=user_id, uservotes__type=Action.UP).exclude(user_id=user_id) But I'm not sure what to pass to order_by ? It would be something like -uservotes__time but how would I specify that I want to order by a particular user_ids uservotes? I could also retrieve all the uservotes corresponding to a user and order those, but then how would I turn all those into Posts? -
how resolve selenium server error on the chrome browser window?
I am testing django site using selenium but I am getting server error(500) on the chrome window. this is what selenium reports back devTools listening on ws://127.0.0.1:63521/devtools/browser/81f40775-3efc-4c51-a00b-3458fe4cd903 E ====================================================================== ERROR: test_post_list_page (public-site-tests.functional_tests.blog.test_blog_list.BlogPostTests) Lets create some blog posts ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\gouth\PycharmProjects\work\teenstartup\pavan-staging\public-site-tests\functional_tests\blog\test_blog_list.py", line 43, in setUp email_field = self.browser.find_element_by_id('id_username') File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element return self.execute(Command.FIND_ELEMENT, { File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\gouth\.virtualenvs\public-site-tests-ue9jU_Te\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="id_username"]"} (Session info: chrome=84.0.4147.89) the code that is resposible for this here class BlogPostTests(StaticLiveServerTestCase): """All tests related to Post model will be tested here""" def setUp(self): """Lets set up the browser""" self.browser = webdriver.Chrome() # lets set up some live urls login_url = self.live_server_url+reverse('accounts:login') self.browser.get(login_url) self.browser.implicitly_wait(10) email_field = self.browser.find_element_by_id('id_username') -
Django: Use same inmemoryuploadedfile to POST to multiple remote API's
I am trying to use the same inmemoryuploadedfile to multiple remote APIs. The upload form consists of a single FileField. Once the user submits the file, I'm trying to use the same inmemoryuploadedfile to post the file to multiple remote APIs. The first remote API call with the file gets successfully received at the remote API end. However, the second remote API call seems to fail as the remote API cannot read the file properly. To debug, I set the two remote APIs with same exact code but deployed on different VMs. Still getting the same error. It seems like only the first API call receives the file correctly and the second call always fails. def form_valid(self, form): exp = form.save(commit=False) result1 = api_endpoint1(exp.image) # Passes result2 = api_endpoint2(exp.image) # Fails- Doesnt receive file correctly if result1.json() == result2.json(): print('All is Good!') If I swap result1 and result2 line, then result2 passes and result1 fails. Even if I do call same API, the second one fails: result1 = api_endpoint1(exp.image) # Passes result2 = api_endpoint1(exp.image) # Fails- Doesnt receive file correctly I tried reseeking the file with exp.image.seek(0), but it doesn't work. I could save the file and then send the … -
How to specify lookup_field in django
I'm going to use UpdateAPIView in django. When I completed the view and ran the server, the following error occurred. Expected view updateViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. I wonder why I shouldn't designate lookup_field as pk in my code and what I can use instead of pk. Here is my code serializers.py from rest_framework import serializers from .models import arduino class arduinoSerializers (serializers.ModelSerializer) : name = serializers.CharField(source='name.username', read_only=True) class Meta : model = arduino fields = ['name', 'temp', 'humi'] views.py from .models import arduino from .serializers import arduinoSerializers from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.generics import CreateAPIView, UpdateAPIView class arduinoViewSet (ViewSet) : serializer_class = arduinoSerializers def data (self, request) : queryset = arduino.objects.filter(name=self.request.user) serializer = arduinoSerializers(queryset, many=True) return Response(serializer.data) class createViewSet (CreateAPIView) : serializer_class = arduinoSerializers def perform_create (self, serializer) : serializer.save(name=self.request.user) def get_queryset (self) : user = self.request.user return arduino.objects.filter(name=user) def dataReceive (self, request) : queryset = self.get_queryset() serializer = arduinoSerializers(queryset, many=True) if serializer.is_valid() : perform_create(serializer) return Response(serializer.data) class updateViewSet (UpdateAPIView) : serializer_class = arduinoSerializers lookup_field = 'pk' def perform_update (self, serializer) : serializer.update(name=self.request.user) def get_queryset (self) … -
how to update object which has OneToOne relationship in django?
I need to update the integer-field in every time I send the request with post method I tried that with the three ways but I couldn't make it. the problem is that when I send a request the request is sent successfully but the data doesn't save. I asked this question before but I didn't get the answer so I hope if anyone can help me I will be thanks match_statics/views.py from django.shortcuts import render, redirect from match.models import Main from .models import Statistics from .forms import StaticForm from django.db.models import F def player_statics(request, pk): form = StaticForm() statics = Statistics.objects.filter(main_id=pk) main_pk = Main.objects.get(pk=pk) if request.method == 'POST': if 'short_pos' in request.POST: form = StaticForm(request.POST, instance=Main.objects.get(pk=pk)) if form.is_valid(): # static = Statistics.objects.filter(main_id=pk).update(short_pass=form.cleaned_data['short_pass'] + 1) # static = Statistics.objects.filter(main_id=pk).update(short_pass=F('short_pass') + 1) form.short_pass = form.cleaned_data['short_pass'] form.short_pass += 1 form.save() context = {'form': form, 'statics': statics, 'main_pk': main_pk} return render(request, 'match_statics/player_statics.html', context) match_statics/player_statics.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Player Statics</title> </head> <body> <div class="match-statics"> <div class="container"> <form method="post" action="{% url 'match_statics:player_statics' main_pk.pk %}"> {% csrf_token %} <div class="buttons"> <h2>Pass Position</h2> {% for field in form %} {{ field.as_hidden }} {% endfor %} <div>{{ statics }}</div> <input type="submit" name="short_pos"> <input type="submit" name="long_pos"> … -
Form Validation - Signup & Login error handling in Django
I am having troubles handling errors in my signup form particularly with password1 & 2 validation, existing username & email handling. Here is my form: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django import forms from .models import UserProfile from .models import Follow class RegisterForm(UserCreationForm): class Meta(): model = User fields = ('username', 'email', 'password1', 'password2') widgets = { 'username': forms.TextInput(attrs={'class': 'form-control', 'name':'username' }), 'email': forms.EmailInput(attrs={'class': 'form-control' }), # 'password1': forms.PasswordInput(attrs={'class': 'form-control' }), # 'password2': forms.PasswordInput(attrs={'class': 'form-control' }), } def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['password1'].widget = forms.PasswordInput(attrs={'class': 'form-control', 'name':'password'}) self.fields['password2'].widget = forms.PasswordInput(attrs={'class': 'form-control'}) def clean_password(self, *args, **kwargs): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password1 != password2: raise forms.ValidationError("Passwords don't match") return self.cleaned_data class UserProfileForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('location', 'favourite_activity') widgets = { 'favourite_team': forms.TextInput(attrs={'class': 'form-control' }), } Here is my views.py: def registerView(request): regForm = RegisterForm() proForm = UserProfileForm() if request.method == 'POST': regForm = RegisterForm(request.POST) proForm = UserProfileForm(request.POST) if regForm.is_valid() and proForm.is_valid(): user = regForm.save(commit=True) profile = proForm.save(commit=False) profile.user = user profile.save() username = request.POST.get('username') password = request.POST.get('password1') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return redirect ('timeline') else: return HttpResponse("There was a problem signing …