Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's the best practice for requests.session sharing between requests in a Django Rest Framework web application?
Is it safe to use a global, static session to communicate with external APIs? Is there a reasonable indicator for when a session should be refreshed, or is using a session a bad idea? Background: I'm currently working through optimizing a Django Rest Framework application that is taking too long (>1.2 seconds) to get responses from a remote API. Based on their timings, and comparing it to a few run-throughs on Postman, the longest running components seem to be a combination of TCP and SSL handshake when they weren't cached (running django_cprofile_middleware against the endpoint showed a similar theme, with hundreds of milliseconds being spent on those aforementioned handshakes). I was able to get those interactions down to about the same in the application as in Postman after the first request by using a shared requests.session instead of a basic requests.get (closer to 200 ms per request). -
Django Admin can't display attributes in a model with multiple Foreign Keys to another model
Basically I have two models, one for Icons and another for Types which have 3 icons (business rule). In my models.py file I have the following: class Icon(models.Model): name = models.CharField(max_length=60) image_URL = models.CharField(max_length=255) modified_date = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Type(models.Model): name = models.CharField(max_length=60) modified_date = models.DateTimeField(auto_now=True) creation_date = models.DateTimeField(auto_now_add=True) icon1 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon1") icon2 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon2") icon3 = models.ForeignKey(Icon, null=True, blank=True, on_delete=models.SET_NULL, related_name="icon3") def __str__(self): return self.name In my admin.py file I have the following: class TypeAdmin(admin.ModelAdmin): list_display = ( 'name', 'icon1__name', 'modified_date', 'creation_date', 'id' ) ... admin.site.register(models.Type, TypeAdmin) Everything works fine but I can't get it to display the icon's name. This works for other classes which have a single Foreign Key attribute of the same model, however here since there's three Foreign Key attributes of the same model, I get an error: <class 'app.admin.TypeAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'icon1__name', which is not a callable, an attribute of 'TypeAdmin', or an attribute or method on 'app.Type'. What is causing this error? How may I fix it? The FK is allowed to be null (or blank) because some types are allowed to not have … -
Django Admin: Model Foreignkey has null & blank = True, but using formfield_for_foreignkey in Admin makes it required
My model has a ForeignKey with null=True / blank=True, but when I try to alter an object in Django Admin I am using def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'parent_locale': return ParentLocaleChoiceField(queryset=models.Locale.objects.all().order_by('display')) return super().formfield_for_foreignkey(db_field, request, **kwargs) to alter how the data displays there. But doing this now throws an error when submitting saying the field is required. How to do I make this field not required when using formfield_for_foreignkey to alter the choice field display? -
How to plot data in a Jupyter Notebook when the Python kernel is executed remotely?
I have a Django application running on a remote machine and I would like to plot some data in my local browser in a Jupyter Notebook. I can work locally with the models in a Notebook but for some reason I'm unable to display chart. What could be the reason ? Basic code example to display chart (source) : import matplotlib.pyplot as plt time = [0, 1, 2, 3] position = [0, 100, 200, 300] plt.plot(time, position) plt.xlabel('Time (hr)') plt.ylabel('Position (km)') My problem is that output is only string but no chart : Text(0, 0.5, 'Position (km)') This is how I execute the notebook using the shell_plus Django extension (source). First I connect to the remote machine with: local_machine:~$ ssh -L 8888:localhost:8888 username@194.123.456.123 Then in the remote machine I start the Notebook : remot_machine:~$ python manage.py shell_plus --notebook --no-browser [I 16:30:24.804 NotebookApp] Serving notebooks from local directory: /var/www/myapp [I 16:30:24.804 NotebookApp] The Jupyter Notebook is running at: [I 16:30:24.804 NotebookApp] http://localhost:8888/?token=21addee513e29c1d890bed70320d613b39d1441e12419490 [I 16:30:24.804 NotebookApp] or http://127.0.0.1:8888/?token=21addee513e29c1d890bed70320d613b39d1441e12419490 [I 16:30:24.804 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [C 16:30:24.808 NotebookApp] To access the notebook, open this file in a browser: file:///home/user/.local/share/jupyter/runtime/nbserver-23578-open.html Or copy … -
How to conditionally apply a template filter in Django?
Suppose I have a Django template with <div><b>{{some.long.expression.with.stuff|filter1}}</b></div> and I only wish to apply filter1 if my_condition is True. What is the best way? Here is a verbose way with repetition: {% if my_condition %} <div><b>{{some.long.expression.with.stuff|filter1}}</b></div> {% else %} <div><b>{{some.long.expression.with.stuff}}</b></div> {% endif %} Here is slightly less verbose, harder to read, still with some repetition: <div><b>{% if my_condition %}{{some.long.expression.with.stuff|filter1}}{% else %}{{some.long.expression.with.stuff}}{% endif %}</b></div> Suggestions? -
Create django model instances from dataframe without server timeout
I am uploading a zipped file that contains a single CSV file. I then unzip it on the server and load it into a dataframe. Then I am creating django objects from it. This works fine until my dataframe becomes too large. When the dataset is getting too large the django server shuts down. I am assuming that this happens because every iteration in my loop increases memory and when there is no memory space left it shuts down. I am working with big datasets and want to make my code work no matter how big the dataframe. Imagine I have a df like this: cola fanta sprite libella 2018-01-01 00:00:00 0 12 12 34 2018-01-01 01:00:00 1 34 23 23 2018-01-01 02:00:00 2 4 2 4 2018-01-01 03:00:00 3 24 2 4 2018-01-01 04:00:00 4 2 2 5 Imagine that the columns could be up to 1000 brands and the rows could be more than half a Million rows. Further imagine I have a model that saves this data in a JSONB field. Thus every column is a django object, the column name being the name. The time-stamp combined with the data in the column is the JSONB field. … -
Signals for a database view in Django
I have a model in django that has the meta option Managed=False set. This model is a postgres view that get data from another schema. I would like to detect whenever the view changes (add/update/delete an object). I have tried using post_save from django.db.models.signals, but it doesn't seem to work. Is there some other way to achieve this? -
How do you add a third-party app inside your django app?
I'm currently working on a personal project. I'm working with Django but I'm not very experienced yet. I wanted to know how do you add a third party application inside you app ? Example: You have a small web-app with few pages and in one of them you want to load and use some external program e.g. Microsoft Paint. What do you need to do to add it (in general) ? Can you theoretically add any program you want or there are limits ? I would also appreciate if you could kindly show me where I can find useful documentation on this topic. Thank you ! -
modelManager get_by_natural key method change the USERNAME_FIELD affecting my authentication?
I have a custom User model that inherits from AbstractBaseUser which defines the username_field = email so that users will login using emails. class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email", unique=True) username = models.CharField(max_length=100, unique=True) last_name = models.CharField(max_length=100, blank=True, null=True) first_name = models.CharField(max_length=100, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_site_administrator = models.BooleanField(default=False) is_developer = models.BooleanField(default=False) is_project_manager = models.BooleanField(default=False) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) create_on = models.DateTimeField(verbose_name="Date Created", default=timezone.now) # So that we will be working primarily with email and not username USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username"] objects = UserManager() As the objects = UserManager() and this one contains a get_by_natural_key method as follows: def get_by_natural_key(self, username): return self.get(username=username) Now rather using the email to login it uses the username to login. Note that the userManager inherits from BaseUserManager like this class UserManager(BaseUserManager): Can somebody explain to me what is going on here. Is the problem coming from the inheritance or the get_by_natural_key() itself ? -
auth_permission table is empty after migrate on new database
I configured a django project to use a new database. After run migrations, all tables are there, custom migrations to insert some data are ok, but the auth_permission table is empty. My project uses the permissions everywhere and is now returning Permissions.DoNotExist exception. I couldn't find if there's something in the new version of Django (updated last week), but I've done the same procedure two months ago, and the permissions were created. Now, with the Django updated, it wasn't. -
Assigning a queryset to a M2M field in Django results in "field id expected a number, but got Foo"
# View @require_POST def update_category_filter(request): """ Updates the Category filter """ # User logged in? if request.user.is_authenticated: # Get the form instance filter_form = SelectCategoryForm(request.POST) # Form validation if filter_form.is_valid(): # Check if user already has a filter instance instance_exists = UserCategoryFilter.objects.filter(user=request.user) # Get the cleaned data selection = filter_form.clean() print(selection) # If not create, else update if not instance_exists: filter_instance = UserCategoryFilter.objects.create(user=request.user) # Add each selected filter of queryset to model instance for member in selection: filter_instance.categories_selected.add(member) # breaks here The selection is a clean queryset, which I want to populate the many-to-many field with. However, this results in ValueError at /update-category-filter/ Field 'id' expected a number but got 'choices'. # Model class UserCategoryFilter(models.Model): """ Saves the selected category filter by a user """ user = models.ForeignKey(Account, on_delete=models.CASCADE) categories_selected = models.ManyToManyField(Category) # Form class SelectCategoryForm(forms.Form): """ A form to update category filters for logged in users """ choices = forms.ModelMultipleChoiceField(queryset=Category.objects.all().order_by('category'), widget=forms.CheckboxSelectMultiple) -
django Product delete
I am trying to delete Prodcut specific id. After pressing YES nothing happened. def product_delete_view(request, id): obj = Product.objects.get(id=id) #also did try obj = Product.objects.get(id=id).delete() # also did try obj = get_object_or_404(Product, id=id) if request.method == 'Post': obj.delete() context = { 'object': obj } return render(request, 'products/products_delete.html', context) uls: path('del/<int:id>/delete/', product_delete_view, name='product_delete'), template: <form action='.' method='POST'>{% csrf_token %} <h1>Do you want to delete the prodcut "{{ object.title }}"?</h1> <p><input type='submit' value='YES' /> <a href = '../'>Cancel</a></p> </form> Screen: Do you want to delete the product "second product"? YES Cancel -
How to make a asynchronous thread in python that does not return control
I have a django server built for a mobile app i.e. using JSON response. The app has a simple social media feed. The admins of the app have the ability to use push notifications (through firebase) on posting a new post to the feed. At the movement the code is 'synchronous' and goes something like def post(View): # validate post ect... # store it in database # ! Send push notifications ! # return response The issue is if firebase lags or is slow (which it sometimes seems to be) this can slow down the response. What I would like to do is make an asynchronous function that I can call to handle the push notification and forget about it and return the response to the user and the push notification can take as long as it needs. [Meta] Help in wording the title would be appreciated. -
Django Ckeditor works on localhost does not on the server
Error output on browser console: GET http://{ip}/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) GET http://{ip}/static/ckeditor/ckeditor-init.js net::ERR_ABORTED 404 (Not Found) GET http://{ip}/static/ckeditor/ckeditor/ckeditor.js net::ERR_ABORTED 404 (Not Found) I don't understand what would be the problem here. I import ckeditor.RichTextField and use it in my form. I installed: pip install whitenoise pip install django-ckeditor I use it in localhost with toolbars, and without a bug but when i deploy it to the server the toolbar gets removed. Any helpful answer is appreciated. Thanks. -
Djano value has an invalid format. It must be in YYYY-MM-DD HH:MM
for example when I use auto_now_add=True "Jan. 1, 2021, 5:05 a.m." format, but when I want to update the date, I get the error "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']", I don't have a problem when I update it by entering in YYYY-MM-DD HH:MM format, but how can I bring this date automatically in this format? models.py; class problemduyuru(models.Model): olusturulmatarihi = models.DateTimeField(auto_now_add=True, blank=True) duyurutipi = models.TextField(max_length=100, null=True) incidentno = models.TextField(max_length=100, null=True) baslangiczamani = models.TextField(max_length=100, null=True) aciklama = models.TextField(max_length=100, null=True) views.py create and update; update; def problemduyurusuupdate(request, id): problemmember = problemduyuru.objects.get(id=id) problemmember.duyurutipi = request.POST['duyurutipi'] problemmember.incidentno = request.POST['incidentno'] problemmember.baslangiczamani = request.POST['baslangiczamani'] problemmember.aciklama = request.POST['aciklama'] problemmember.olusturulmatarihi = request.POST['olusturulmatarihi'] problemmember.save() messages.success(request, 'Alarmlar was updated successfully!') return redirect('/problemduyurusu') create; def problemduyurusucreate(request): if request.method == 'POST': problemmember = problemduyuru( duyurutipi=request.POST['dduyurutipi'], incidentno=request.POST['dincidentno'], baslangiczamani=request.POST['dbaslangiczamani'], aciklama=request.POST['daciklama'], olusturulmatarihi=request.POST['dolusturulmatarihi'], ) try: problemmember.full_clean() except ValidationError as e: pass problemmember.save() messages.success(request, 'Alarmlar was created successfully!') return redirect('/problemduyurusu') else: return render(request, 'problemduyurusucreate.html') -
How to query jsonb column in PostgreSQL with Python and Django
I've looked at many of the solutions here and elsewhere but I'm not getting my code to work no matter what I try. So I've got a PostgreSQL database with a Django application, and one of the columns in one of my tables, employee_schedules, is a jsonb data type. In the Django model it's of type JSONField: day1_actual_punches = models.JSONField(null=False, default=dict) day2_actual_punches = models.JSONField(null=False, default=dict) day3_actual_punches = models.JSONField(null=False, default=dict) day4_actual_punches = models.JSONField(null=False, default=dict) day5_actual_punches = models.JSONField(null=False, default=dict) day6_actual_punches = models.JSONField(null=False, default=dict) day7_actual_punches = models.JSONField(null=False, default=dict) In the PostgreSQL database the day1_actual_punches is stored like this: "{\"EmpCode\":\"A00X\",\"FullName\":\"ABBY SENSENBAUGH\",\"InPunchTime\":\"2021-09-26 16:57:00\",\"OutPunchTime\":\"2021-09-26 22:48:00\",\"PayRate\":\"6.00\",\"OvertimePayRate\":\"9.00\",\"PayType\":\"HOURLY\",\"ScheduleType\":\"Food and Beverage\",\"EmpPosition\":\"Server PM\",\"DateTimeIn1\":\"2021-09-26 4:57 PM\",\"DayNumber\":1,\"WeekStartDate\":\"2021-09-26 16:57:00\",\"PunchDayIndex\":6,\"HoursWorked\":\"5.85\"}" I'm using the following to test getting a record from the database, using the python console, like this, following the Django documentation for querying jsonb data. results = EmployeeSchedule.objects.filter(day1_actual_punches__EmpCode='A00X') But the Queryset is always returning empty, even though I see the record in the table. Is this because of how I'm saving the python dict to the database, which is causing the slashes or something? Here's a code sample of saving the record to the database: empschedule_new = EmployeeSchedule() if self.day_number == 1: empschedule_new.day1_actual_punches = json.dumps(dict_time_punches, separators=(',', ':')) The data inside dict_time_punches looks like this … -
How to create drag and drop and forward to some function in django?
I have a django website, and I would like to implement drag&drop to my form. This part is looking very old compare to the rest of site. Problem is that I don't know javascript, I have tried to make if from tutorials but did not make any sense. Can you help me to get simple solution for this. Any ideas how to do this with zero knowledge of js? cal.py def OnlyCAL(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] #pandas calculations response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = DocumentForm() return render(request, 'cal.html', { 'form': form, 'page_title':page_title }) cal.html {% extends "base.html" %} {% load static %} {% block content %} <form action="{% url "cal" %}" method="post" enctype="multipart/form-data" class="dropzone"> {% csrf_token %} {{ message }} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload and Download!"/></p> </form> {% endblock content %} urls.py urlpatterns = [ path('', views.home, name='home'), path('cal/', cal.OnlyCAL, name='cal'), ] -
How to add additional data to form.serialize() in django ajax Call when using a model form?
I have a django view that uses ajax to check if the form is valid and create new object if so, but I would like also some additional data with the form.serialize() to know which fields are complete by the user so I will know what to pass to the create method. Here is the view: def createIssue(request): form = CreateIssueForm(request.POST or None) if request.is_ajax() and form.is_valid(): kwargs = request.POST.get("kwargs") print(kwargs) # if kwargs is present #model.objects.create(**kwargs) context = {""} return JsonResponse({}) return render(request, "tracking/base.html") Here is the ajax call: function CreateIssueAjax(e) { e.preventDefault(); const role = this.getAttribute('role'); const _form = $("#CreateIssueForm"); var formString = _form.serializeArray(); console.log(formString) function sendKwargs(arr) { let kwargs = {} arr.forEach(el => { if (!(el.value === "") | (!el.name === 'csrfmiddlewaretoken')) { kwargs[el.name] = el.value } }); return kwargs; } var myData = _form.serialize(); console.log(myData); myData['kwargs'] = JSON.stringify(sendKwargs(formString)); $.ajax({ url: "/create-issue/", type: "post", data: myData, datatype: 'json', success: function (data) { console.log("success"); // add to ui function after success // alert the user(alertify.js) }, }); } Now as I am using a modelform, adding the kwargs key to form dict will prevent the form from being valid. Is there any other way to pass another key … -
EmptyPage error on final page of paginated Wagtail site
I've searched the site and none of the answers are different from what I've tried: Example | Example | Example | Example My aim is to display 5 posts per paginated page on my Wagtail site. It works except for the fact I am getting a persistent EmptyPage error on the last page. I currently have 25 live posts, so there should be exactly 5 on each of the 5 pages. It's just page 5 (currently last page) that comes up empty. I am pretty sure the problem is with the template and not with the queryset/model itself, but everything I've seen online looks identical to what I have. Here is my model: class BlogIndexPage(Page): body = RichTextField(blank=True) def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) blog_pages = BlogPage.objects.live().public().order_by("-date") page = request.GET.get("page") paginator = Paginator(blog_pages, 5) try: blog_pages = paginator.page(page) except PageNotAnInteger: blog_pages = paginator.page(1) except EmptyPage: blog_pages = paginator.page(paginator.num_pages) context["blog_pages"] = blog_pages return context Here is my template: {% if blog_pages.paginator.num_pages > 1 %} {% if blog_pages.has_previous %} <li class="page-item"> <a href="?page={{ blog_pages.previous_page_number }}" class="page-link"> <span>&laquo;</span> </a> </li> {% endif %} {% for page_num in blog_pages.paginator.page_range %} <li class="page-item {% if page_num == blog_pages.number %} active{% endif … -
Why Django doesn't update an image field
I want to build a view that allows the user to update his profile picture. Now in my view the cleaned data returns the current profile image path which then overwrites the existing one one by one. I'm not sure where the issue is. Also since I use a default image within the model manager, I only want to delete the current imagefield if it isn't the default one. # View @require_POST def update_profile_image(request, username): """ Updates the user profile """ form = ImageUpdateForm(request.POST) if form.is_valid(): image = form.cleaned_data['profile_image'] print('image ' + str(image)) user = Account.objects.get(username=request.user.username) user.profile_image = image user.save() return redirect('pollboard') # Model class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60, unique=True) username = models.CharField(max_length=40, unique=True) profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image()) # Custom Manager class MyAccountManager(BaseUserManager): def get_profile_image_filepath(self, filename): return f'profile_image/{self.pk}/{"profile_image.png"}' def get_default_profile_image(): return "profile_image/Logo_large.png" # Form class ImageUpdateForm(forms.ModelForm): class Meta: model = Account fields = ['profile_image'] # Template <div class="profile-image-modal"> <form method="post" action="update_profile_image/"> {% csrf_token %} {{ profile_image_form }} <button type="submit">Save Image</button> </form> </div> -
Django rest framework viewset does it needs locks for multiple requests
I'm new to django and django restful framework and currently learning. Upon reading about viewsets from this link https://www.django-rest-framework.org/api-guide/viewsets/. I wonder for some of the methods like update and destroy that modifies a row in the database. Does one need to put locks or the build in method takes care of it? In addition, if the method takes care of it and one needs to modify or override it then you add locks? Thanks in advance and appreciate any answers. -
Unittest with mock for django login
I am writing Unittests for the Login on Django. And I have serious problems with the get_user(). I just can't figure out how to get through this function in test. I can't make a mock, and I can't substitute values. I think I'm wrong do it. But I don't know how do it right! Please, I need help! def user_login(request): if request.method == 'POST': form = UserLoginForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return redirect('/') I need unittest for this simply function. -
Switching Django languages with flags and urls
I am currently having a language switcher in Django based on flags, but where the URL for all languages are the same. I would now like to change the language switcher so that selecting a flag also redirects the user to a URL prefix (like /en, /es, /fr, etc.) so I easily can send the page in different default languages to different users. Linking to the URL prefix works fine, but how do I easiest redirect the users there when they select flags in the code below? <div class="navbar-btns ml-3"> <div class="navbar-btns-inner"> <div id="language-switcher" class="navbar-btn collapsed"> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="/" /> <select name="language" onchange="this.form.submit()"> {% for language in request|get_language_info_list_ex %} <option value="{{ language.code }}" {% if language.is_current %} selected="selected"{% endif %}> <span class="flag">{{ language.flag }}</span> {# {{ language.code }} #} </option> {% endfor %} </select> </form> </div> </div> </div> -
Change Date Format in Django Models when retrieving Data from PostgreSQL showing in form
I'm using django to submit data in postgresql database. Submission work fine and datastapm on database is correct and match with timezone. I'm useing bellow code to crate time and use in database. created_at = models.DateTimeField(auto_now_add=True) format of time in database: 2021-10-05 20:18:41.773503+03:30 Issue is here that when getting data from database and show it on table, time zone not correct and data format changing to Oct. 5, 2021, 4:48 p.m. without timezone How can I make this correct on view form and show it like 2021-10-05 20:18:41 -
Why I had error todo.views.signupuser didn't return an HttpResponse object
I write a site in django. And for some reason as a result I get an error The view todo.views.signupuser didn't return an HttpResponse object. It returned None instead.. How can I fix this error? Below I will attach my code. My html code: signupupser.html <h1>Sign Up</h1> <h2>{{ error }}</h2> <form method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Sign Up</button> </form> My urls.py: urls.py from django.contrib import admin from django.urls import path from todo import views urlpatterns = [ path('admin/', admin.site.urls), path('signup/', views.signupuser, name='signupuser') ] My views.py views.py from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.db import IntegrityError def signupuser(request): if request.method == 'GET': return render(request, 'todo/signupuser.html', {'form': UserCreationForm()}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() except IntegrityError: return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'That Username has already been taken. Please choose a new username'}) else: return render(request, 'todo/signupuser.html', {'form': UserCreationForm(), 'error': 'Passwords did not match'})