Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
New Relic on AWS lambda not reading its config file
I'm using zappa to deploy a python/django wsgi app to AWS API Gateway and Lambda. I have all of these in my environment: NEW_RELIC_CONFIG_FILE: /var/task/newrelic.ini NEW_RELIC_LICENSE_KEY: redacted NEW_RELIC_ENVIRONMENT: dev-zappa NEW_RELIC_STARTUP_DEBUG: "on" NEW_RELIC_ENABLED: "on" I'm doing "manual agent start" in my wsgi.py as documented: import newrelic.agent # Will collect NEW_RELIC_CONFIG_FILE and NEW_RELIC_ENVIRONMENT from the environment # Dear god why??!?! # NB: Looks like this IS what makes it go newrelic.agent.global_settings().enabled = True newrelic.agent.initialize('/var/task/newrelic.ini', 'dev-zappa', log_file='stderr', log_level=logging.DEBBUG) I'm not using @newrelic.agent.wsgi_application since django should be auto-magically detected I've added a middleware to shutdown the agent before the lambda gets frozen, but the logging suggests that only the first request is being sent to New Relic. Without the shutdown, I get no logging from the New Relic agent, and there are no events in APM. class NewRelicShutdownMiddleware(MiddlewareMixin): """Simple middleware that shutsdown the NR agent at the end of a request""" def process_request(self, request): pass # really wait for the agent to register with collector # Enabling this causes more log messages about starting data samplers, but only on the first request # newrelic.agent.register_application(timeout=10) def process_response(self, request, response): newrelic.agent.shutdown_agent(timeout=2.5) return response def process_exception(self, request, exception): pass newrelic.agent.shutdown_agent(timeout=2.5) In my newrelic.ini I have the following, … -
Django with apache wsgi
I am facing a weired scenerio. I have some initialize api in which i create some data and assign that to some variable and keep persist through all request. So that every request use that data and return some result. In simple django app it's working fine but when i configure it to wsgi apache then the value not persist in-memory for that variable for the subsequent requests. Please help for that that. Thanks -
Rendering templates with Django REST Framework
Right now I'm helping a friend out with his site that's built with Django REST Framework. I'm not really familiar with it so when I opened the module that contained the views I was confused as to where I need to load the template for the view: class ProfileView(APIView): permission_classes = [IsAuthenticated] def get(self, request): serialized = UserProfileSer(instance=request.user) return Response(serialized.data) def post(self, request): serialized = UserProfileSer(instance=request.user, data=request.data, partial=True) if serialized.is_valid(): serialized.save() return Response(serialized.data) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) I'm used to doing return render(request, 'some_template.html', context) I know what serializing does basically but I don't know how to use it to load a template or if I'm supposed to. Sorry -
ImportError: Import by filename is not supported. in urls
When I runserver, I get error, and the traceback is bellow: Unhandled exception in thread started by <function wrapper at 0x106a75050> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) ...... File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/luowensheng/Desktop/demo_project/Python/website/website/urls.py", line 26, in <module> url(r'^api/companies/', include("companies/api/urls")), File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: Import by filename is not supported. And my settings.py's urlpatterns: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^test/', music_view.test), url(r'^musics/(?P<album_id>\d+)/', music_view.DetailView.as_view(), name="detail"), url(r'^musics/', music_view.IndexView.as_view()), url(r'^api/companies/', include("companies/api/urls")), ] My companies app's api urls.py: from django.conf.urls import url from django.conf.urls import include from .views import ( StockListView, ) urlpatterns = [ url(r'^stocks/', StockListView.as_view(), name='stock_list'), ] The project directories: -
Pivot query set by variable in Django
I get a result set of objects in a given relationship. I would like to regroup them by another parameter. Is there an easy way to do this? I fe Structure: class Domain(models.Model): name = models.CharField(max_length=250) class MetaObject(models.Model): name = models.CharField(max_length=250) object_type = models.ForeignKey('Type') domain = models.ForeignKey('Domain', models.DO_NOTHING, blank=True, null=True) class Type(models.Model): name = models.CharField(max_length=250) Pseudocode sample: for dom in Domain.objects.all(): for mo in dom.metaobject_set.all(): print mo + ' ' + mo.object_type What I would like is to pivot my data so instead of getting Domain 1 object 1, type 1 object 2, type 1 object 3, type 2 I instead would like a result set I can work with in a template that looks like the following Domain 1 Type 1 object 1 object 2 Type 2 object 3 I feel like what I otherwise need to do is get all the distinct types for a set of objects in a specified domain and then iterate through those. I can't start with Types at the top as I want them to be per domain. -
How to understand 'context' in Django?
Django documentation define 'context' as: Context:A dict to be used as the template’s context for rendering. MB defines it as: the parts of a discourse that surround a word or passage and can throw light on its meaning They contradict to each other. Take an instance to explain my question : In views.py context = {key:value} render(request, template_name, context) in template <p> The parts of a discourse that surround a word {{ key }} and can throw lights on its meaning.<\p> Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in. Now, django's context is the part within bracket. How to perceive the definition of context in Django? -
How to protect Django's views functions from directly calling through browser url
I want to protect my functions from directly calling through browser url. May be it is possible through CSRF. But I am not able to do it. In front end side I am using ajax to call this function. So, the call should only be possible through ajax but not directly from browser url. My javascript code is function getData(table,id){ data = [] $.ajax({ type: "POST", url: "getData", dataType:'json', data:{'tableName':table}, success: function(result) { for(var i=0;i<result.length;i++){ for (var key in result[i]){ val = result[i][key] if (data.indexOf(val)==-1){ data.push(val) } } } $( "#"+id ).autocomplete({ source: data }); } }); } so I am calling this function in javascript. In urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^getData', views.getData, name='getData'), ] In Views.py def getData(request): tableName = request.POST.get('tableName') tableName = 'colleges' cursor = connection.cursor() query = "select * from "+tableName cursor.execute(query) columnDesc = cursor.description result=[dict(zip([col[0] for col in columnDesc], row)) for row in cursor.fetchall()] return HttpResponse(json.dumps(result), content_type="application/json") So, when i am calling through web browser url directly like... http://localhost/shikshapp/getData I am getting response from my views and i am able to see the data.. So, how can i protect this kind of call.. when the token is not … -
Django : How to pre-populate one model when other model data is saved to it?
I have 3 model which is known as supplier, supplierBankAccount and supplier address both are connected by foreign key is there any way to enter the data into these 3 at the same time or how to pre populate the oter two models while entering data into supplier model supplier model class Supplier(models.Model): name = models.CharField(max_length=500, blank=False) merchant = models.CharField(max_length=300, blank=True, null=False) phone = models.CharField(max_length=25, blank=False, null=False) alternate_phone = models.CharField(max_length=25, blank=True, null=True, default='') website = models.URLField(blank=True, null=True, default='') email = models.EmailField(blank=False, max_length=500) tin_number = models.CharField(max_length=100, blank=True, null=True) slug = AutoSlugField(populate_from='name') def __str__(self): return str(self.name) Supplier Address Model class SupplierAddress(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE) street_address_1 = models.CharField(max_length=50, blank=False) street_address_2 = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=False) state = models.CharField(max_length=50, blank=False) pin_code = models.IntegerField() country = CountryField() def __str__(self): return str(self.supplier) Supplier Bank Details class SupplierBankAccount(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.CASCADE,default='') bank_name = models.CharField(max_length=500,blank=False, null=False) branch_address = models.TextField(max_length=2000, blank=False, null=True) account_holder_name = models.CharField(max_length=500,blank=False, null=False) ifsc = models.CharField(max_length=200, blank=False, null=False) account_number = models.CharField(max_length=200, blank=False, null=False) bank_code = models.CharField(max_length=200, blank=False, null=False) branch_code = models.CharField(max_length=200, blank=False, null=False) location = CountryField() additional_info = models.TextField(max_length=1000, blank=True, null=True) def __str__(self): return str(self.supplier) -
I Deleted all migrations and re created database but "Import Error : No module named 'django.db.migrations"
I am currently using Django 1.10.7 and Python 3.5. I think I seriously screwed everything up in my django project. I wanted to wipe my MySQL database, so I created another db but I was reading that I need to delete all migrations in my database(so I deleted the db and created another with a different name) and deleted the migration files in my app. I followed a guide with said to run in terminal: find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete After this, when I try to run makemigrations, I get error: "ImportError: no module named 'django.db.migrations.exceptions'. I couldn't find anyone else with this problem and honestly am about to literally create an entirely new virtualenv and set up everything again from scratch. -
Django 3 or more levels of Dropdown Menu Filter
**Hi, I am trying to make a webpage where I can register a pre-defined(in Admin area) Product and associate it to Category and Subcategory, using a dropdown menu, that in each iteration filters the subsequent and show only the items associated with the previous. Example: I want to register a Product called "Tablet" associated with Subcategory "Mobile Devices" and this subcategory is associated with Category "Electronic". So, in order to do this, the webpage will show Category to be selected, then after selecting it as electronic, will only show as subcategory "Mobile Devices" and any other under the same category. After selecting the Subcategory, it will filter the next menu Product, to show only Product under subcategory "Mobile Devices" such as Tablet, Cellphone etc. Here is my model.py** class Category(models.Model): company_name = models.CharField(max_length=100) def __str__(self): return self.company_name class Subcategory(models.Model): category = models.ForeignKey(Category) name = models.CharField(max_length=100) def category_name(self): return self.category.company_name def __str__(self): return self.name class Product(models.Model): subcategory = models.ForeignKey(Subcategory) description = models.CharField(max_length=100) def subcategory_name(self): return self.subcategory.name def category(self): return self.subcategory.category.company_name def __str__(self): return self.description **Here is my view.py** def regsubcategory(request): if request.method == 'POST': subcategory_form = RegSubcategoryForm(data=request.POST) if subcategory_form.is_valid(): cdata = subcategory_form.cleaned_data.get ddata = subcategory_form.cleaned_data.get subcategory_selected = Subcategory.objects.filter(name=cdata('subcategory_select')) product_selected = Product.objects.filter(name=ddata('product_select')) … -
The definition of `context` contradicts to its original meaning
I am confused with definition of 'context' in Django for months. In Django documentation: Context:A dict to be used as the template’s context for rendering. Oxford definition: The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning. the data from a view's dict is filled to blank of template which contradict to context's original meaning. Take an instance to explain my question : In views.py context = {key:value} render(request, template_name, context) in template <p> The parts of a discourse that surround a word {{ key }} and can throw lights on its meaning.<\p> Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in. Now,in django,context is the part within bracket. Or, that's it, just accept it for granted. How to perceive the definition of context in Django? -
How to toggle readonly_fields in Django admin?
Need to add button to django admin page, if you want to edit Model, you push Edit then edit what you need, and save it. When you open it after saving, it must be uneditable again. So, how to do that? I have simple admin.py code: from django.contrib import admin from .models import Order class OrderAdmin(admin.ModelAdmin): list_display = ['__str__', 'email', 'project_type', 'price'] list_filter = ['email', 'first_name', 'project_type', 'price'] readonly_fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'price') fields = ('first_name', 'last_name', 'email', 'phone', 'project_type', 'services', 'price', 'slug') def has_add_permission(self, request): return False admin.site.register(Order, OrderAdmin) -
Correctly handling Django migrations conflicts
I'm currently working on a dev branch and I will need to merge it to master one day. I have up to 20 migrations files on my dev branch and about the same number on master at the moment. I needed to make migrations on both branches which will result in migrations having the same prefix, (ex 0003_auto) Now, there are other threads out there about this topic but I never found a relevant one. Basically, I want to know how to correctly handle migrations conflicts but for a general case. In other words, not considering my particular case, if you have migrations files generated by makemigrations with the same prefix, what is the best/secure way of handling this. Here are two ways I have figured myself (maybe entirely wrong): Deleting all migrations files, merge the code and then running a fresh makemigrations and migrate which will result in only one migration file. Using the flag --merge flag: makemigrations –merge I know there are multiple other ways (see this). Now, knowing all this I'd like to know what is the best way of handling this. In general, what should I use that will correctly merge conflicts and get me a … -
Unable to access attributes of the JSON data - django
I have this view def view_involved_people(request): schedule = request.POST['schedule'] query = Schedule.objects.get(pk=schedule).involved_people.all() serialized = serializers.serialize('json', query) data = {'data': serialized} return JsonResponse(data) I have this script $.ajax({ url: "/schedule/ajax/view_people", data: { 'schedule': JSON.parse(id) }, dataType: "json", success: function(data) { console.log(data); }, error: function(data) { console.log(data.responseText); }, type: "post" }); When I do console.log(data), it return this: How can I access the values of the returned data. Do I have an error with my JSON? -
Modify default form for a model in the admin site to accept Postgres arrays
I'm new in Django and I've followed the tutorial. I know that when I do: from .models import Question admin.site.register(Question) I make the administrator capable to create and edit questions from a form that is created from the definition of the model. The problem that I have is that this is a model I made for my project: class Catalog(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=500) creation_date = models.DateTimeField('creation date') creators = ArrayField(models.CharField(max_length=35, blank=True), size=10) subjects = ArrayField(models.CharField(max_length=35, blank=True), size=5) instrument = models.CharField(max_length=50) facility = models.CharField(max_length=50) ... And creators and subjects seems to act like normal CharFields. So my questions are: How can I edit the form that is displayed by default? How can I treat creators and subjects like arrays in the form? Thank you. -
possible to return list of dict instead of a list when using for in? django
I have a code which returns a list, which looks something like this [user.name for user in Model.field.filter()] I know this would return me a list of user name but I am wondering if it would be possible to return list of dict? such as [ {'name': 'name1', 'email': 'email1', {'name': 'name2', 'email': 'email2', ] -
Django, JWT, Angular 4, how to redirect after success login
class CreateUserView(CreateAPIView): serializer_class = UserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) user = self.model.get(username=serializer.data['username']) payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) return Response( token, status=status.HTTP_201_CREATED, headers=headers ) else: return Response( status=status.HTTP_400_BAD_REQUEST ) how to add that to DB? class LoginUserView(APIView): def post(self, request, *args, **kwargs): username = request.data.get('username') password = request.data.get('password') user = authenticate(username=username, password=password) if user: payload = jwt_payload_handler(user) token = { 'token': jwt.encode(payload, SECRET_KEY), 'status': 'success' } return Response(token) else: return Response( {'error': 'Invalid credentials', 'status': 'failed'}, ) And how redirect after success login to url in angular -
Select2 overdrive option value
Hi i have select2 script witch Django i need save in DB text not value. I think best way to do this is use jquery and detect change event and replace val to option text. Please help me make jquery script. my html: <div class="col-lg-4"> <select name="depositvalues_set-0-name" data-placeholder="Wybierz oponę" data-width="100%" class="form-control m-select2 django-select2 django-select2-heavy select2-hidden-accessible" maxlength="100" id="id_depositvalues_set-0-name" data-allow-clear="true" data-minimum-input-length="0" data-field_id="MTQwMTE3Nzg3OTU1OTQ0:1eAPuS:iiIjCRFFWJ-hM1k153lOvcNLLDs" data-ajax--url="/select2/fields/auto.json" data-ajax--cache="true" data-ajax--type="GET" tabindex="-1" aria-hidden="true"> <option value="" selected=""></option> <option value="1">Opona Kumho 195/75R16 C KC-11 Dostawcza Zimowa</option> </select> Select name is dynamic -
What is the 'instance' created from class 'ListView'?
I follow a tutorial and define class ListView: class RestaurantListView(LoginRequiredMixin, ListView): def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) I attempt to figure out what's the instance created from the class To accomplish it, I add print for debugging. class RestaurantListView(LoginRequiredMixin, ListView): print(self) # intend to print the objects created def get_queryset(self): return RestaurantLocation.objects.filter(owner=self.request.user) Error reports then NameError: name 'self' is not defined -
Django Model choices based off another model
Sorry if this is confusing, I'm still a bit green with Django. So basically I have two models and I want a selection from one to have all the choices from another model. So basically: class Show(models.Model): venue = models.CharField(max_length=100, choices = VENUE NAME) class Venues(models.Model): Name = models.CharField(max_length=100) Essentially I want the venue to have a list of the venue names that were input into that model. Is this possible? -
The map in head to traverse Django files
There are multiple files in Django: urls.py views.py models.py templates and forms.py to create data. The diagram of it enables you to understand the functions and principles. take a popular vertical map for instance. MTV diagram It's frustrating if you traverse the fils vertically in mind when shift from file to file in editor. What's is a good structure to picture and see them in mind simultaneously when working. -
Import Django Models Into PyCharm's Python Console
I am following the Django tutorial and using PyCharm. I am trying to import Question and Choice from models.py INTO the PyCharm "Python Console". I have __init__.py files located in top-level mysite, lower-level mysite, and in polls directory. I am using a virtual environment and it is activated in the PyCharm Python Console. C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\Scripts\python.exe "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\pydevconsole.py" 51164 51165 PyDev console: starting. import sys; print('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial', 'C:/Users/Jarad/PycharmProjects/OfficialDjangoTutorial']) Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 >>> import sys >>> import os >>> import django >>> os.getcwd() 'C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial' sys.path.append('C:\\Users\\Jarad\\PycharmProjects\\OfficialDjangoTutorial\mysite') >>> os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.mysite.settings' >>> django.setup() >>> from mysite.polls.models import Question, Choice Traceback (most recent call last): File "<input>", line 1, in <module> File "C:\Program Files\JetBrains\PyCharm 2017.1.5\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\mysite\polls\models.py", line 8, in <module> class Question(models.Model): File "C:\Users\Jarad\PycharmProjects\OfficialDjangoTutorial\venv\lib\site-packages\django\db\models\base.py", line 118, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class mysite.polls.models.Question doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. apps.py from django.apps import AppConfig class PollsConfig(AppConfig): name = 'polls' Restate my goal: import the Question and Choice models in PyCharm's "Python Console" because the code hints and inspection of … -
Forms and views in Django: How to clean data, especially data re. mptt models, in formtools.wizard?
I’m trying to write a form using python2.7, django1.11.5, crispy_forms, formtools’ wizardview and djnango-mptt. Sadly, I’m having problems with outputing a cleaned data from the form. Here are some examples of the form fields that I’m using. Forms: from dal import autocomplete class StandardModelForm(forms.Form): first_field = forms.ModelChoiceField( queryset=StandardDjangoModel.objects.all(), widget=autocomplete.ModelSelect2( url='/standard-model-autocomplete/', ) ) helper = FormHelper() helper.form_method = 'POST' class Meta: model = StandardDjangoModel class MPTTModel1Form(forms.Form): second_field = TreeNodeChoiceField( queryset=MyMPTTModel.objects.all(), widget=autocomplete.ModelSelect2( url='/mptt-model-autocomplete/', ) ) class MPTTModel2Form(forms.Form): third_field = TreeNodeMultipleChoiceField( queryset=MyMPTTModel.objects.filter( level=2, contribution_type=1, ), widget=forms.CheckboxSelectMultiple() ) Models: class StandardDjangoModel(models.Model): name = models.CharField( max_length=50) def __unicode__(self): return self.name class MyMPTTModel(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) field = models.CharField( max_length=200) CONTRIBUTION_TYPES = ( (1, 'One'), (2, 'Two'), (3, 'Three'), ) contribution_type = models.IntegerField( choices=CONTRIBUTION_TYPES, blank=True, null=True) @property def root(self): return self.get_root().field def __repr__(self): return self.field def __unicode__(self): return self.field The views are as simple as can be: from formtools.wizard.views import SessionWizardView class FormularView(SessionWizardView): def done(self, form_list, **kwargs): user_form_input = self.get_all_cleaned_data() return render(self.request, 'summary.html', { 'form_data': user_form_input }) However, if the user inputs a non-ascii character, the following exception is raised (for clarity I've posted only the last lines): File "C:\PYTHON27\lib\site-packages\django\utils\encoding.py", line 80, in force_text s = six.text_type(bytes(s), encoding, errors) UnicodeEncodeError: 'ascii' codec … -
SyntaxError: unexpected EOF while parsing Django
I have this code and I have no idea why this happen.. I'm starting at django so please someone could help me? from django.conf.urls import url from django.contrib import admin from controlinv import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^Login/$', views.login, name='index-login'), url(r'^Inicio/$', views.index, name='indexF') At the end in the console says File "C:\intercamiones\mercedes\src\mercedesapp\urls.py", line 23 url(r'^Inicio/$', views.index, name='indexF') ^ SyntaxError: unexpected EOF while parsing -
Django contact form sending email
I created a contact form to send me an email when the user fills it out. Everything appears to be working, but I'm not getting an email. Here's my console output: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Michael Plemmons From: mplemmons1982@gmail.com To: californiamikegreen@yahoo.com Date: Thu, 02 Nov 2017 22:40:50 -0000 Message-ID: <20171102224050.12741.24539@ubuntu> hello this is a test ------------------------------------------------------------------------------- [02/Nov/2017 22:40:50] "POST /contact/ HTTP/1.1" 302 0 [02/Nov/2017 22:40:50] "GET /success/ HTTP/1.1" 200 36 This is views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse, HttpResponseRedirect from .models import * from .forms import contact_form from django.core.mail import send_mail, BadHeaderError from django.shortcuts import redirect def contact(request): if request.method == 'GET': form = contact_form() else: form = contact_form(request.POST) if form.is_valid(): contact_name = form.cleaned_data['contact_name'] contact_email = form.cleaned_data['contact_email'] contact_message = form.cleaned_data['contact_message'] try: send_mail(contact_name, contact_message, contact_email, ['californiamikegreen@yahoo.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "contact.html", {'form': form}) def success(request): return HttpResponse('Success! Thank you for your message.') This is urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'contact/$',views.contact, name='contact'), url(r'^success/$', views.success, name='success'), ] this is forms.py from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User class contact_form(forms.Form): contact_name = forms.CharField(label='Contact Name', max_length=255) contact_email = …