Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django accessing CHOICES = () from Model
Just wondering, I have the following model schema: class Location(models.Model): SERVICE_CHOICES = ( ('bus_station', 'Bus Station'), ('cafe', 'Café'), ('cinema', 'Cinema'), ('gardens', 'Public Gardens'), ('library', 'Library'), ('public_services', 'Public Services'), ('railway_station', 'Railway Station'), ('restaurant', 'Restaurant'), ('school', 'School'), ('shop', 'Shop'), ('supermarket', 'Supermarket'), ('tourist_attractions', 'Tourist Attractions'), ('transit_station', 'Transit Station'), ('walks', 'Walks'), ('woodland', 'Woodland'), ) title = models.CharField("Title", max_length=60, default='') description = models.TextField("Description") service_type = models.CharField("Service Type", max_length=80, choices=SERVICE_CHOICES, default='public_service') I'm just wondering how I would loop over the SERVICE_CHOICES tuple list on the frontend template? {% for service_choice in location.SERVICE_CHOICES %} ? -
create OleFile type file from uploaded file
So I am using Message class from this repo to parse .msg file. I have a test file that works with that class. I am trying to use that class in custom parser I am writing for my Django rest framework app. But when I read stream.body, it additionally adds the following content ----------------------------488071469102781097692083 Content-Disposition: form-data; name="file"; filename="email_test.msg" Content-Type: application/vnd.ms-outlook < actual content here > ----------------------------488071469102781097692083-- and I have a doubt that, because of this additional content, Message class is throwing following error. not an OLE2 structured storage file Is my doubt right? How do I solve this? -
Dynamically set the attributes of a class in python [duplicate]
This question already has an answer here: How do you programmatically set an attribute? 3 answers I have a Django model defined as follows: class Customer(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128, blank=False, null=False) address = models.CharField(max_length=256, blank=False, null=False) Can I dynamically set the attributes of the class using a dictionary like this? # cleaned_data is a dictionary for key, value in cleaned_data.items(): if customer.get(key) != value: # how do I check this? customer.set(key) = value # how do I set the attribute here? I've tried the following: >>> customer = Customer() >>> key = 'first_name' >>> value = 'Aby' >>> eval('customer.' + eval('key') + '=' + "'" +eval('value')+ "'") Traceback (most recent call last): File "<console>", line 1, in <module> File "<string>", line 1 customer.first_name='Aby' ^ SyntaxError: invalid syntax -
Django Import Excel Endpoint
I'm trying to create an endpoint for loading an excel file into server and importing the data in it. To do it I'm using django-import-export package. This is the view code: def create(self, request, *args, **kwargs): file_serializer = self.get_serializer(data=request.data) file_serializer.is_valid(raise_exception=True) if file_serializer.is_valid(): from tablib import Dataset from workflows.submittals.admin import ItemImportResource item_model_resource = ItemImportResource() file_serializer.save() dataset = Dataset() file_obj = request.FILES['file'] imported_data = Dataset().load(open(file_obj).read()) result = item_model_resource.import_data(dataset, dry_run=True) if not result.has_errors(): item_model_resource.import_data(dataset, dry_run=False) return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) When loading the file into the (tablib) Dataset, I'm getting this error: 'invalid file: <InMemoryUploadedFile: Import_Sample_test1.xls (application/vnd.ms-excel)>' I tried reffering the name of the file, so replaced imported_data = Dataset().load(open(file_obj).read()) with imported_data = Dataset().load(open(file_obj.name).read()) Then it seems like the Dataset does loads the file, because in the response I see some byte representation of the file, but I also get this error message: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) Any idea? -
How do I render a Django template when there are many models?
I have this hierarchical order of models: courses, study programmes, departments and faculties. I have 2 columns in bootstrap. First column lists all faculties, with their specific departments and the study programmes of each department. Second column lists all courses. I want that when someone clicks on a faculty,to display the specific courses for that faculty in the second column by replacing all courses, same for departments or study programmes. Now, I tried something, but I don't know how to achieve this result. I don't know how to list courses for each faculty, as you can notice, I put faculties.0 as a test. <script> $('#btnClick').on('click', function () { if ($('#1').css('display') != 'none') { $('#2').show().siblings('div').hide(); } else if ($('#2').css('display') != 'none') { $('#1').show().siblings('div').hide(); } }); </script> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Search courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li id="btnClick">{{ faculty.name }}</li> <ul> {% for department in departments %} {% if department.faculty == faculty %} <li>{{ department.name }}</li> <ul> {% for study in studies %} {% if study.department == department %} <li>{{ study.name }}</li> {% endif %} {% endfor %} </ul> {% endif %} {% endfor %} </ul> {% endfor %} </ul> </div> </div> <div class="col-md-9"> … -
Confused about how TimedRotatingFileHandler rollover works
I have an issue about how rollover occurs in a TimedRotatingFileHandler logging setup in a remote Django server. I have log files setup in this configuration, to rotate itself to a new log file and date stamp the old file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'deals.vip_session': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': 'sessions.log', 'when': 'midnight', 'interval': 1, 'backupCount': 7, }, ... What I am confused about is how the date rollover is handled. According to the documentation: If delay is true, then file opening is deferred until the first call to emit(). This implies that the default setting of delay=False would automatically create the new file at midnight exactly on the web server. In practice, I am seeing that the new log file is not created until the first write operation past midnight is executed. If I am mis-understanding how this function works, then the documentation is not being very clear here. I would prefer a file being created at midnight exactly over waiting for a write operation that may never come. (I have some log files set aside for specific events that may not occur within a 24 hour cycle). I=Can someone clarify my mis-understanding … -
Django: How to detect inactivity session time out?
I am using django.auth.db connection and have created a table which contains username of a user who is logged in and when the user logged out manually (by clicking logout button) I am removing his/her username from that table. The problem arises when a user logged out due to session out and I am not able to remove his/her username from that table. So I wanted to know that is there any way to detect when the users' session/cookies out so that I can remove his/her username from that table? -
Django How in inline Foreign key data can not add can only see
Django How in inline Foreign key data can not add can only see -
Cycle thru a ModelForm fields and indetify FileField and ImageField
I'm creating a generic save method for a form. In the save I want to iterate over the field and if the field is an instance of FileField to to some operations def save(self, commit=True): obj = super().save(commit=False) for field in self.fields: if isinstance(field, forms.FileField) and obj: This is not working because, if I check the type of field is str. How can I get the real model type ? -
Django:datepicker is not a function error in modal but works fine on normal template
I get this error in Chrome console. I have been working for hours to fix it but couldn't. I am new to all of this. My first website: VM86540:37 Uncaught TypeError: $(...).datepicker is not a function at HTMLDocument.eval (eval at <anonymous> (jquery-1.11.3.min.js:2), <anonymous>:37:21) at j (jquery-1.11.3.min.js:2) at Object.add [as done] (jquery-1.11.3.min.js:2) at m.fn.init.m.fn.ready (jquery-1.11.3.min.js:2) at new m.fn.init (jquery-1.11.3.min.js:2) at m (jquery-1.11.3.min.js:2) at eval (eval at <anonymous> (jquery-1.11.3.min.js:2), <anonymous>:30:3) at eval (<anonymous>) at jquery-1.11.3.min.js:2 at Function.globalEval (jquery-1.11.3.min.js:2) My modal code: {% load staticfiles %} <!doctype html> <html lang="en"> <head> <link rel="stylesheet" href="{% static 'flatly.css' %}"> <link rel="stylesheet" href="{% static 'main.css' %}"> <link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> <script> $(function() { var date1 = new Date; date1.setHours(0, 0, 0, 0); date1.setDate(10); var date2 = new Date; date2.setHours(0, 0, 0, 0); date2.setDate(23); $("#datepicker").datepicker({ beforeShowDay: function(date) { return [date < date1 || date > date2, ""]; } }); }); </script> </head> <body> <div class="row"> <form action="" method="post" accept-charset="utf-8" class="form" role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="title-doc">Add a Patient</h4> </div> <div class="modal-body"> {% csrf_token %} <div class="row"> <input id="datepicker" type="text"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button class="btn btn-primary " type="submit">Add</button> </div> </form> </div> </body> … -
Django 1.11 - Static files not served - PythonAnywhere
I am deploying a django 1.11 app to a PythonAnywhere enviroment. The settings file has 'django.contrib.staticfiles' added to the INSTALLED_APPS and the static config STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_col') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] Folder structure of static folder: ├── css ├── fonts ├── img ├── jquery.templates └── js └── jquery When developing the app locally I was using "/static/jquery.templates/jquery.templates.js" without problems when doing manage.py runserver, but it doesn't work in deployment where I got no static files served whatsoever. I executed manage.py collectstatic which worked without errors, but it moved the folder "jquery.templates" to js one: static_col/ ├── admin ... ├── css ├── fonts ├── img └── js ├── jquery └── jquery.templates Problem The other static files are served, apparently, but the problem is that the link /static/js/jquery.templates/jquery.templates.js is not found. Obviously neither the /static/jquery.templates/jquery.templates.js link does not work. I have not idea how to approach this. Serving static files is a pain with Django and I haven't found yet a working guide for this. Thank you -
django admin 2 stacked inline
I have 3 models: Book, Chapter (with FK to Book) and Sentence (with FK to Book and Chapter). Is there a way to show in the admin site of a book, all the chapters it has (I know it is with inlines) BUT also the Sentences each Chapter has? Of course I want it all to be in the view of each book, so only the model Book would be registered in the admin. It would be great to show all chapters, and once you click, all sentenes are shown, is that even possible? -
Abstract user django migration error
I am trying to add two fields to user model of Django. Migrations and models are: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_prostudent = models.BooleanField( default=False ) is_teacher = models.BooleanField( default=False) My migration looks like this: # -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-02-11 11:07 from __future__ import unicode_literals import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('students', '0005_auto_20180118_1508'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=30, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=30, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('is_prostudent', models.BooleanField(default=False)), ('is_teacher', models.BooleanField(default=False)), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions … -
Django 2 + PostgreSQL FullText search not matching what it should
I am experiencing a problem I hope someone can enlighten me about. I need to perform a full-text search on a table with multiple columns and sorting the results by rank, using Django 2 and PostgreSQL 10.1. So far this is my code: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector # other unrelated stuff here vector = SearchVector("very_important_field", weight="A") + \ SearchVector("tags", weight="A") + \ SearchVector("also_important_field", weight="B") + \ SearchVector("not_so_important_field", weight="C") + \ SearchVector("not_important_field", weight="D") query = SearchQuery(search_string, config="italian") rank = SearchRank(vector, query, weights=[0.4, 0.6, 0.8, 1.0]). # D, C, B, A full_text_search_qs = MyEntry.objects.annotate(rank=rank).filter(rank__gte=0.4).order_by("-rank") The strange fact is that some search_string return nothing as a result, while if I perform a simple query such as SELECT * FROM my_entry WHERE very_important_field LIKE '%search_string%' OR tags LIKE '%search_string%' OR ... I get tons of results, also if I limit the search just to the important fields. I already tried to play with filter(rank_gte=0.4) and also removing it. Still same result. As of now I am not using GIN o GIST indexing, since I am just experimenting. Any clues about what am I missing? Thanks in advance -
multiple values for keyword argument when using **kwargs
The arguements of _mget_search function are - def _mget_search(query, with_scores=False, count=False, record_term=True, **kwargs): I am calling this function in this way - _mget_search(**search_kwargs) I printed the search_kwargs and it contains this - {'count': False, 'min_score': 20, 'end': 49, 'with_scores': False, 'start': 0, 'query': u'ouuuuu', 'max_score': inf, 'record_term': True} I am getting this error - _mget_search() got multiple values for keyword argument 'query' I am unable to understand why it is happening and how to correct it. -
operational error: no such table django Every Time I create models
I am using Django 2.0, Python Every Time I am creating new Model when I do python3 manage.py makemigrations it shows no changes detected and on migrate no migrations to apply Even I tried python3 manage.py makemigrations home shows Migrations for 'home': home/migrations/0001_initial.py - Create model FAQ - Create model Topic and then on python3 manage.py migrate home It still shows Operations to perform: Apply all migrations: home Running migrations: No migrations to apply. and when I try to open that table in admin. it shows OperationalError at /admin/home/faq/ no such table: home_faq however it'd worked when I'd deleted migrations and database and re migrated everything. But I can't delete everything Every Time. my models.py from django.db import models # Create your models here. class Topic(models.Model): topic_title = models.CharField(max_length=200,unique=True) topic_discription = models.TextField() no_of_posts = models.IntegerField() def __str__(self): return self.topic_title class FAQ(models.Model): question = models.CharField(max_length=800,unique=True) answer = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) author = models.CharField(max_length=100) author_info = models.TextField() def __str__(self): return self.question I've registered it on admin.py from django.contrib import admin from .models import Topic,FAQ # Register your models here. admin.site.register(Topic) admin.site.register(FAQ) -
redirect() can't seem to working properly
redirect function can't seem to be working though the data entered seemed to be saved to the database. Already tried putting in absolute url from django.shortcuts import render,redirect from django.contrib.auth import authenticate,login from django.views.generic import View from .forms import UserForm from .models import Album class UserFormView(View): form_class = UserForm template_name = 'music/registration_form.html' title = "Register" def get(self,request): form = self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self,request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit = False) #normalized data username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() #returns user objects user = authenticate(username = username ,password = password) if user is None: if user.is_active: login(request,user) return redirect('index') #This line though return render(request,self.template_name,{'form':form}) -
The urlpatterns generated by Django vs their official page
In the official documentations of Django, the urlpatters have an incipit of "path" The Django generated urls.py, it has an incipit of "url". This makes it hard for me to follow tutorials, could you tell me how this is possible? I'm having problems making urlpatters. Thank you in advance! -
Get corresponding time and value from json using Djangon (python2)
The following is a sample of the JSON that I'm fetching from the source. I need to get certain values from it such as time, value, value type. The time and value are in different arrays and on different depth. So, my aim is to get the time and value like for value 1, I should get the timestamp 1515831588000, 2 for 1515838788000 and 3 for 1515845987000. Please mind that this is just a sample JSON so ignore any mistakes that I may have made while writing this array. { "feed":{ "component":[ { "stream":[ { "statistic":[ { "type":"DOUBLE", "data":[ 1, 2, 3 ] } ], "time":[ 1515831588000, 1515838788000, 1515845987000 ] } ] } ] }, "message":"", "success":true } Here is a function, that I have written to get the values but the timestamp that I'm getting on the final step is incorrect. Please help to resolve this issue. get_feed_data() is the function that is giving the above JSON. # Fetch the component UIDs from the database component_uids = ComponentDetail.objects.values('uid') # Make sure we have component UIDs to begin with if component_uids: for component_uid in component_uids: # Fetch stream UIDs for each component from the database stream_uids = StreamDetail.objects.values('uid').filter(comp_id=ComponentDetail.objects.get(uid=component_uid['uid'])) for stream_uid … -
Using Sql and MongoDb with Django rest framework for apis
I am new to django and it to use sql db as default but also connect it to mongoldb. In my models.py i from mongoengine import Document, EmbeddedDocument, fields class ToolInput(EmbeddedDocument): name = fields.StringField(required=True) value = fields.DynamicField(required=True) class Tool(Document): label = fields.StringField(required=True) description = fields.StringField(required=True, null=True) inputs = fields.ListField(fields.EmbeddedDocumentField(ToolInput)) In my serializers.py I have :- from .models import Tool from rest_framework_mongoengine import serializers as mongoSerializers from .models import Tool class ToolSerializer(mongoSerializers.DocumentSerializer): class Meta: model = Tool fields = '__all__' In my api.py I have :- from .serializers import ListSerializer, CardSerializer, ToolSerializer from rest_framework.generics import ListAPIView from rest_framework_mongoengine import viewsets as mongoViewsets from .models import List, Card, Tool class ToolApi(mongoViewsets.ModelViewSet): #lookup_field = 'id' queryset = Tool.objects.all() serializer_class = ToolSerializer In my urls.py I have :- from django.conf.urls import include, url from .api importToolApi urlpatterns = [ url(r'Tool', ToolApi.as_view({'get': 'Tool'})), ] When I hit this api, error says :- 'ToolApi' object has no attribute 'Tool' Earlier I was using ListAPIView class from rest_framework.generics to create api to acess data from sql. Is the error because I have used ModelViewSet for ToolApi? PS - Please refer me to some git project using both mongoldb and sql -
Django rest Framework : Behavior of a PrimaryKeyRelatedField with a nested representation
I have an API built with django rest framework. Here is the code : models.py class Ingredient(models.Model): barcode = models.CharField(max_length=13, primary_key=True) name = models.CharField(max_length=255) image = models.CharField(max_length=255) class Recipe(models.Model): name = models.CharField(max_length=255) favorite = models.BooleanField() owner = models.ForeignKey( 'auth.User', related_name="recipes", on_delete=models.CASCADE) class Component(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey( Recipe, related_name='components', on_delete=models.CASCADE) quantity = models.FloatField() serializers.py class IngredientSerializer(serializers.ModelSerializer): name = serializers.CharField(read_only=True) image = serializers.CharField(read_only=True) class Meta: model = Ingredient fields = '__all__' class ComponentSerializer(serializers.ModelSerializer): ingredient = serializers.PrimaryKeyRelatedField(queryset=Ingredient.objects.all()) # ingredient = IngredientSerializer() class Meta: model = Component fields='__all__' class RecipeSerializer(serializers.ModelSerializer): components = ComponentSerializer(many=True) owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Recipe fields = '__all__' With the code in this state, I can create a new component by selecting a existing ingredient, an existing recipe and entering a quantity. However, the serialization of the components is not nested : { "id": 8, "quantity": 123.0, "ingredient": "3218930313023" }, When I change the code to ingredient = IngredientSerializer() in the ComponentSerializer class, the representation is nested as intended : { "id": 9, "ingredient": { "barcode": "3218930313023", "name": "Crêpes L'Authentique", "image": "https://static.openfoodfacts.org/images/products/321/893/031/3023/front_fr.16.400.jpg", }, "quantity": 123.0 } But when I try to add a component with an existing recipe and an existing ingredient, I get … -
Django Rest Framework not filtering all filter_fields
i have this viewset: class CompanyViewSet(OwnerMixin, viewsets.ModelViewSet): queryset = company_models.Company.objects.all().order_by('-id') serializer_class = company_serializers.CompanySerializer mini_serializer_class = company_serializers.CompanyMiniSerializer # filtering search_fields = ('name', 'id', 'business_sector__business_sector', ) ordering_fields = ('name', 'id', 'business_sector__business_sector', ) filter_fields = ('follower', 'name', 'business_sector__business_sector', 'candidate__primary_skill__skill', 'candidate__business_sector__business_sector', 'client__primary_skill__skill', 'client__business_sector__business_sector') def get_serializer_class(self): try: obj = self.get_object() if obj: return self.serializer_class except: pass return self.mini_serializer_class def get_queryset(self): queryset = company_models.Company.objects.all().order_by('-id') name = self.request.query_params.get('name', None) if name is not None: queryset = company_models.Company.objects.filter(name__icontains=name) return queryset when i go to api/companies?follower=2 the filter works. for all the other query params it does not work. -
Unable to connect to the localhost/phpmyadmin database through my django project
I am trying to connect to the localhost/phpmyadmin through xampp server for my django project, and getting this error django.db.utils.OperationalError: (1044, "Access denied for user ''@'localhost' to database 'djangoproject'") When i type python manage.py runserver on my command prompt, im getting the above mentioned error. There is no password set on my phpmyadmin, it is just by default user 'root' and password [null] I have written the given below code in my manage.py file to connect to the database page. DATABASES = { 'default' : { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'djangoproject', 'USER': ' root ', 'PASSWORD': '', 'HOST': 'localhost', 'PORT':'' } } There is also this written in my phpmyadmin page on the top A user account allowing any user from localhost to connect is present. This will prevent other users from connecting if the host part of their account allows a connection from any (%) host. I do not understand what is wrong. kindly help. I am a beginner in django framework. -
Design Decision Django Rest Framework - Django as Frontend
I am currently developing my first more complex Web Application and want to ask for directions from more experienced Developers. First I want to explain the most important requirements. I want to develop a Web App (no mobile apps or desktop apps) and want to use as much django as possible. Because I am comfortable with the ecosystem right now and don't have that much time to learn something new that is too complex. I am inexperienced in the Javascript World, but I am able to do a little bit of jQuery. The idea is to have one database and many different Frontends that are branded differently and have different users and administrators. So my current approach is to develop a Backend with Django and use Django Rest Framework to give the specific data to the Frontends via REST. Because I have not that much time to learn a Frontend-Framework I wanted to use another Django instance to use as a Frontend, as I really like the Django Template language. This would mean one Django instance one Frontend, where there would be mainly TemplateViews. The Frontends will be served on different subdomains, while the backend exposes the API Endpoints on … -
NoReverseMatch errors during Django forgot password email system
I am trying to create a system for resetting forgotten passwords through email but am getting some errors. My urls are: from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), ## more irrelevant urls here ## url(r'^password/reset/done/$', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^password/reset/$', auth_views.PasswordResetView.as_view(), name='password_reset'), url(r'^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^password/reset/complete/$', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] When the email address is submitted at password_reset, the email sends but I get this error: Internal Server Error: /password/reset/ Traceback (most recent call last): File "C:\python\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\python\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\python\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper return bound_func(*args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\python\lib\site-packages\django\utils\decorators.py", line 63, in bound_func return func.__get__(self, type(self))(*args2, **kwargs2) File "C:\python\lib\site-packages\django\contrib\auth\views.py", line 439, in dispatch return super(PasswordResetView, self).dispatch(*args, **kwargs) File "C:\python\lib\site-packages\django\views\generic\base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 183, in post return self.form_valid(form) File "C:\python\lib\site-packages\django\contrib\auth\views.py", line 453, in form_valid return super(PasswordResetView, self).form_valid(form) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 79, in form_valid return HttpResponseRedirect(self.get_success_url()) File "C:\python\lib\site-packages\django\views\generic\edit.py", line 67, in …