Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Graphene writing mutations with multiple layers of nested foreign keys
How do you write the schema and query for nested foreign keys? I checked the docs and found no examples of how to do this. So here was my attempt based on github and stackoverflow answers lets say I have these models: class Address(models.Model): name = models.CharField() class Person(models.Model): name = models.CharField() address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False) class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() I tried writing a schema like this: class AddressInput(graphene.InputObjectType): name = graphene.String(required=True) class PersonInput(graphene.InputObjectType): name = graphene.String(required=True) address =graphene.Field(AddressInput) class CreateNewBlog(graphene.Mutation): address = graphene.Field(AddressType) person=graphene.Field(PersonType) blog=graphene.Field(BlogType) class Arguments: address_data = AddressInput() person_data = PersonInput() text = graphene.String() @staticmethod def mutate(root, info, person_data=None, address_data=None, **input): address = Address.objects.create(name=address_data.name) person = Person.objects.create(address=address, name=person_data.name) blog = Blog.objects.create(person =person, text=input['text']) blog.save() return CreateNewBlog(blog=blog) and I used a query like this: mutation { CreateNewBlog(person: { address: {name: "aaa"}, name: "First Last" }, text: "hi hi") { Blog { person{ name address{ name } }, text } } } I got this error message: { "errors": [ { "message": "'NoneType' object has no attribute 'name'", "locations": [ { "line": 32, "column": 9 } ], "path": [ "CreateNewBlog" ] } ], "data": { "CreateNewBlog": null } } I … -
After learning Python- what?
After learning Python on beginner level, and practicing what would you recommend to go with, I am so keen to learn Django, but, I would like to know is it possible to understand Django 3.x with knowledge of Python 3.x and how if you can refer me to some good place to learn more and get more resources about these two, as all I am getting - respectfully, but, I don't understand - are Indian-based tutorials. Thank you! -
Django + Ajax + Cors = empty responses
I'm using jquery ajax in addition to django-cors-headers on my site in order to allow a form to be displayed as an iframe on another site that I don't own/control. While the form can be submitted, any time there is an ajax call from the page to a view in my project, the ajax POST being sent from the page (i.e. iframe) to the django view doesn't contain any data. Similarly, on the response, there is no data being sent from the view to the ajax function (i.e. the JSON is empty). Should CORS + Ajax work without using DRF? I've got the following settings in my settings file CORS_ORIGIN_ALLOW_ALL = True CSRF_COOKIE_SAMESITE = None In my ajax call, I'm passing the following headers: headers: { 'X-CSRFToken': '{{ csrf_token }}', 'X-Requested-With': 'XMLHttpRequest' }, Can you think of what else might be causing this? Thanks! -
Error when adding application in django proyect
I am a total begginer with django and I am having troubles when i try to run the proyect. I created a virtual environment, install django and django rest, start a django proyect and then i created my application. After that, i code a very simple model, serializer and view, to test all this new features, but when i tried to run it i got the following error: ModuleNotFoundError: No module named 'myapi' This is my proyect structure: My problem is when i try to add my application to the INSTALLED_APPS array in settings.py. I will show the code so far: setting.py of the proyect app_tv_movies/urls.py myapi/urls.py I dont understand why why django doesnt recognize my app! -
Bad Request Check all data table Django
I'm having a trouble why it keeps telling the console bad request after I check all the data, but if I manually check each item on table it works fine, but when I use check all - bad request I think the problem it has "on" data on my table but don't know why see the image below. Is there any expert can know about this? thanks in advance Bad Request using check all Check manually table.html <button type="submit" id="delete_btn" class="btn btn-secondary round btn-min-width mr-1 mb-1" >Mark as Paid</button> <table class="table" name="table" id="table"> <thead> <tr > <th >No</th> <th><input type="checkbox" onClick="toggle(this)" /></th> <th>ID Number</th> <th >Name</th> <th >Barangay</th> <th >Sex</th> <th >Sector</th> <th Amount</th> <th >Signature/Thumb Marks</th> <th >ID Presented/ Date & Issuance</th> <th>Date Received</th> <th >Remarks</th> </tr> </thead> <tbody class="report-content"> {% csrf_token %} {% for user_information in benefeciaries %} <tr id="{{user_information.id}}"> <td></td> <td><input type="checkbox" name="product_id[]" value="{{user_information.id}}" id="delete_product"></td> <td>{{user_information.covid_id}} </td> <td>{{user_information.lastname}}, {{user_information.firstname}} {{user_information.middle}}</td> <td width="5%">{{user_information.barangay}}</td> <td></td> <td ></td> <td>{{user_information.amount|floatformat:2|intcomma}}</td> <td></td> <td ></td> <td ></td> <td></td> </tr> {% endfor %} </tbody> </table> javascript //js checkall function toggle(source) { checkboxes = document.getElementsByName('product_id[]'); for(var i=0, n=checkboxes.length;i<n;i++) { checkboxes[i].checked = source.checked; } } //js mark as paid button $(document).ready(function(){ $('#delete_btn').click(function(){ if(confirm("Are you sure ?")){ … -
django upload multiple file without plugin
I'm trying to upload multiple file using django but my code is uploadign only one image not all images, I'm trying to upload multiple images without using any pluging or javascript just a simple way to do a foreach because I want to use only one input field has multiple attribute like in PHP codes My model is : from django.db import models from django.contrib.auth.models import User from album.models import Album from django.core.files import File class Images(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE) album = models.ForeignKey(Album, on_delete= models.CASCADE) image_value = models.FileField(upload_to='galleries/images', max_length=350, blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) class Meta: db_table = 'album_images' def __str__(self): return self.album Form is : from django import forms from django.forms import ClearableFileInput from .models import * class ImagesUploadClass(forms.ModelForm): class Meta: model = Images exclude = ['user'] fields = ('image_value') View is : from django.shortcuts import render, redirect from .forms import ImagesUploadClass from .models import Images from django.http import HttpResponseRedirect def uploadMultiPleImagesFunction(request): upload_image = ImagesUploadClass() if request.method == "POST": form_add_data = ImagesUploadClass(request.POST, request.FILES) if (form_add_data.is_valid()): form_add_data.save.save() return HttpResponseRedirect('/album') else: print(form_add_data.errors) return render(request, 'images/upload_images.html', { 'upload_image' : upload_image, }) And my template html is : {% extends "base.html" %} {% block maincontent %} <form method="POST" action="" enctype="multipart/form-data"> {% … -
Can I create a SALESFORCE case using simple salesforce python library?
I am working on an app that uses the Django framework. The app has an issue reporting or request form that used to create a support ticket on Hubspot. The support system recently switched to Salesforce and now I need to find a way to create tickets/cases in there. I have found that the simple-salesforce python library is very popular to communicate with Salesforce API. The doc shows all the ways to connect/authenticate with the API, but I cannot find any function that can help me to create a case. Once you get the security token, you can get the resource object by simply doing the following: from simple_salesforce import Salesforce sf = Salesforce(username='myemail@example.com', password='password', security_token='token') How can I use the sf object to create a case or maybe get the necessary info to send some types of a POST request to do so? -
how do I make custom filters work in django_filters?
So I've made this custom filter in filters.py with Django-filters and when I'm submitting the "YEAR CHOICE" from templates, the page refreshes but it doesn't work. I think I'm having a problem with my "year_filter_method" also I want my pagination and filter system to work together. Any help would be really appreciated. Cheers! models.py from django.db import models import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year + 1)): YEAR_CHOICES.append((r, r)) class Music(models.Model): Song = models.CharField(max_length=100, blank=False) Year = models.IntegerField(('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.Song filters.py import django_filters import datetime class MusicFilter(django_filters.FilterSet): YEARCHOICES = [] for r in range(2010, (datetime.datetime.now().year + 1)): YEARCHOICES.append((r, r)) year_filter = django_filters.ChoiceFilter(label="Year", choices=YEARCHOICES, method="year_filter_method") def year_filter_method(self, queryset): expression = YEARCHOICES return queryset.filter(expression) views.py def music_page(request): #pagination & filter music = Music.objects.all().order_by('-id') music_filter = MusicFilter(request.GET, queryset=music) paginator = Paginator(music, 6) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) try: music = paginator.page(page_number) except PageNotAnInteger: music = paginator.page(1) except EmptyPage: music.paginator.page(paginator.num_pages) return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter}) filters.py {% load static %} <link rel="stylesheet" href="{% static 'main/filter.css' %}" type="text/css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <div class="container"> <form method="get"> <span class="label">{{filter.form}}</span> <span class="btn-search-handler"><button id="search_btn_id" type="submit">Search</button></span> </form> </div> music.html {% include 'main/includes/navbar.html' %} {% include 'main/includes/filter.html' %} … -
Django Jet Dashboard does not show/activate the updated model and view
I have been inheriting this project where the developer of which is not available to answer question anymore. Thus I have been struggling to figure out a way to help my admin add new items called "icon". I updated the models.py in 'api' app and migrated, and checked to make sure the new model table turns up in the database. However, I have been struggling to add this model onto the Django Jet Dashboard. Even after I press the reset button, the row for 'icon' model does not show up. Let me show you the dashboard.py from django.utils.translation import ugettext_lazy as _ from jet.dashboard import modules from jet.dashboard.dashboard import Dashboard, AppIndexDashboard from jet.utils import get_admin_site_name class CustomIndexDashboard(Dashboard): columns = 3 modules.DashboardModule.draggable = False modules.DashboardModule.style = True modules.DashboardModule def init_with_context(self, context): self.children.append(modules.ModelList( _('Data'), models=( 'api.Category', 'api.Company', 'api.User', 'api.Holiday', 'api.Config', 'api.Pattern', 'api.WorkType', 'api.ChangeWorkSchedule', 'api.UserWorkSchedule', 'api.Icon', ############# <- this is the 'icon' ), column=1, order=0 )) picture of Django JET interface that's missing 'icon' Also, since my admin wants to have a convenient functionality where he can directly upload images onto the database, I created a file named "dashboard_modules_views.py", following along and improvising from Django Jet documentation. Below is the dashboard_moduels_views.py import boto3 … -
Django app: can I run management command that is defined in a dependency?
My Django application called my_app pulls in a dependency called my_dependency. my_dependency declares a management command called useful_thing Is there a way I can run useful_thing directly from my_app's start.sh? I've tried calling it directly but it's not found, but maybe there's a way I can point to it. I'm new to Django and suspect this is not a sensible thing to try and do. -
How can I create a ModelViewSet for my Customer and Order Models in Django?
So I have a Customer Model. class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('-created',) and a OrderItem Model. class OrderItem(models.Model): order = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1) quantity = models.PositiveIntegerField(default=1) ready = 1 on_its_way = 2 delivered = 3 STATUS_CHOICES = ( (ready, 'ready'), (on_its_way, 'on its way'), (delivered, 'delivered'), ) status = models.SmallIntegerField(choices=STATUS_CHOICES) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) I created another model ByCustomer Model class ByCustomer(models.Model): name = models.ForeignKey(Customer, on_delete=models.CASCADE) orders = models.ForeignKey(OrderItem, on_delete=models.CASCADE) I want to turn it into a ModelViewSet where it only shows the orders of the selected Customer. class By_Customer_View(viewsets.ModelViewSet): # code let's you select only one customer # and returns all the Orders that customer has I've seen something like this for @api_view @api_view(['GET']) def by_customer(request, pk): tasks = ByCustomer.objects.get(name=pk) serializer = ByCustomerSerializer(tasks, many=False) return Response(serializer.data) How would this work with ModelViewSet? I can't add extra parameters on (viewsets.ModelViewSet, pk). What other fields should I add and what am I missing? Still new to ModelViewSets so I don't know its limitations. If ModelViewSet doesn't have … -
How to use templates to display fields from two tables (using FK)
In my template, I would like to show 'challenges' grouped by 'category' e.g. Category 1 Challenge 1 Challenge 2 Category 2 Challenge 3 Challenge 4 Here is my models.py: class Category(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=400) class Challenge(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) question_text = models.CharField(max_length=200) answer_text = models.CharField(max_length=200) In my template file I want to do something like this: {% for category in category_list %} {{ category.title }} <ul> {% for challenge in Challenge.objects.get(category_id=category.id) %} <li>{{ challenge.question_text }}</li> {% endfor %} </ul> {% endfor %} But I understand you cannot call functions in templates. How else can I display data from two sets in a relationship? -
All access attempts share the same IP Address Django-Axes
I'm having an issue where all access logs/attempts recorded to the server via the Django-axes module are under the same IP address. These two logs seen below were made under two different IP addresses, yet they are recorded as if they are the same. Any ideas on what could be causing this issue? Documentation if necessary: https://django-axes.readthedocs.io/en/latest/ -
Accessing different domain via jQuery $ajax()?
How do you let jQuery access a different domain via its $ajax() method? I have a Django site running at https://example.com:4567/somepage and I want a page to access an Flask-based API running on https://example.com:5678/path/to/rest/api. The only difference in the domain is the port. However, the browser is giving me the error: Access to XMLHttpRequest at 'https://example.com:5678/path/to/rest/api' from origin 'https://example.com:4567' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Some similar questions recommended adding these CORS headers to the $ajax() call like: $.ajax({ url: '//example.com:5678/path/to/rest/api', headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type':'application/json' }, dataType: 'jsonp', success: function(data, textStatus, jqXHR){ do_stuff } }); but this doesn't seem to have any effect. What else do I need to do to allow Javascript on my page to access a different domain? -
Render html-content from remote html-file (AWS bucket) into django-template
I am running a django app and I am building a newsletter. I have a newsletter-model that has a file-field where I attach a html-document (which is the content of the newsletter). This file gets automatically uploaded to an AWS bucket. I also want to display the newsletter on my website. So I am trying to find a solution how I could render the HTML-content from the HTML-file as my django-template. My model: class Newsletter(models.Model): subject = models.CharField(max_length=150) content = models.TextField(null=True, blank=True) attachment = models.FileField(null=True, blank=True, storage=MediaStoragePrivate()) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I tried various things: I tried getting the attachments content, saving it into a variable and rendering it to the template def list_newsletter(request): newsletter = Newsletter.objects.last() attachment = self.attachment.read().decode("utf-8") return render( request, "newsletter_list.html", {"newsletter": attachment} ) This gives me the text but with the html-tags included (<h1> ladadilada </h1>), but I want the interpreted html not raw text. I tried this with beautiful soup htmltxt = Newsletter.objects.last().attachment soup = BeautifulSoup(htmltxt, 'html.parser') But also this prints the html-tags. I can print it with .text, but this does not interpret the html-tages but just prints raw text. Tried rendering the URL but it gives me the URL. Is it … -
Heroku Django SendGrid sends email on development server but doesnt send emails in production
I am struggling to find the issue with my current password_reset functionality in my Django app in production settings. In my development settings, reset password emails are successfully sent by SendGrid to Gmail accounts. However, when it comes to sending them to Gmail accounts on my production the password_reset email is not being sent successfully. I do not know why this is happening as when I use the send_mail in the Heroku python shell the emails are sent to Gmail successfully, and this issue only seems to be for Gmail users. I have tested this with @hotmail.com accounts and it seems to run smoothly. My website email is on Microsoftoutlook but again on development, the emails are sent successfully but on Heroku they aren't. I was wondering why is this happening as I cannot find this issue anywhere? Or am I just better off switching to mailgun? -
Getting two database models to show on one html page
Currently working on a web page and I want to show two different tables of information one is for individual foods and the other is for recipes, however when I can only get the first class to pull up any information I've tested to see if the first class can pull up the recipe database and it, in fact, currently out of ideas on what to try next. class SearchFoodResultsView(ListView): model = Food template_name = 'nutrihacker/search.html' context_object_name = 'food_list' # overrides ListView get_queryset to find names containing search term and pass them to template def get_queryset(self): query = self.request.GET.get('term') if (query == None): return Food.objects.all() else: # If there are any foods containing the query, they will be in the resulting object_list which is used by search.html in a for loop food_list = Food.objects.filter( Q(name__icontains = query) ) return food_list class SearchRecipeResultsView(ListView): model = RecipePreset template_name = 'nutrihacker/search.html' context_object_name = 'recipe_list' # overrides ListView get_queryset to find names containing search term and pass them to template def get_queryset(self): query = self.request.GET.get('term') if (query == None): return RecipePreset.objects.all() else: # If there are any recipes containing the query, they will be in the resulting object_list which is used by search.html in … -
ERR_ABORTED 404 (Not Found) error in VueJS
I deployed a Django+VueJS application to a Digital Ocean droplet using Nginx, the Django app is working but i can't see the VueJS components loaded by Webpack (i'm using Django-Webpack-Loader). In my console, i keep seing these errors: GET http://MYURL/static/vue/js/stopwatch.js net::ERR_ABORTED 404 (Not Found) GET http://MYURL/static/vue/js/index.js net::ERR_ABORTED 404 (Not Found) Which means that the static folder was not found. I made sure to use npm run build and manage.py collectstatic and i can see that the static folder is there, even though the app doesn't see it. Here is the path: django-vue-mpa |-vue_frontend |-django_vue_mpa |-static The full code of the application is here (i just cloned that repository and tried to deploy it). Here is my vue.config.js (i think the problem might be here): const BundleTracker = require("webpack-bundle-tracker"); const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const pages = { "stopwatch": { entry: "./src/stopwatch.js", chunks: ["chunk-moment", "chunk-vendors"], }, "index": { entry: "./src/index.js", chunks: ["chunk-vendors"], }, 'vue_app_01': { entry: './src/main.js', chunks: ['chunk-vendors'] }, 'vue_app_02': { entry: './src/newhampshir.js', chunks: ['chunk-vendors'] }, } module.exports = { pages: pages, filenameHashing: false, productionSourceMap: false, publicPath: process.env.NODE_ENV === 'production' ? '/static/vue' : 'http://localhost:8080/', outputDir: '/django-vue-mpa/django_vue_mpa/static/vue/', chainWebpack: config => { config.optimization .splitChunks({ cacheGroups: { moment: { test: /[\\/]node_modules[\\/]moment/, name: "chunk-moment", chunks: … -
uwsgi can't be installed
i'm stuck trying to install uWSGI for the purpose of deploying my django application using pip install uwsgi, but encounter this error : enter image description here i've found several answers that unfortunately didn't work for me, like update dev tool ,install cywin or modify uwsgiconfig.py (wich does'nt exist since it's not installed ), or maybe i'm missing something. Thanks a lot for your help. -
how to add placeholder to modelform fields with over-riding form
I am trying to add placeholder to the fields of a modelform. I found this answer very insightful and used the method of the second answer: How to add a placeholder attribute in Django Form however, I want to improve the code snippet but I have some problems. First showing my code: class SampleModelForm(ModelForm): field_attrs = { 'email': {'placeholder': 'email placeholder', }, 'first_name': {'placeholder': 'first_name placeholder', }, 'middle_name': {'placeholder': 'middle_name placeholder', }, 'last_name': {'placeholder': 'last_name placeholder', } } class Meta: model = SampleModelForm fields = [K for K in self.field_attrs.keys()] def __init__(self, *args, **kwargs): super(ConsultantAddStudentAccountForm, self).__init__(*args, **kwargs) for k, v in self.field_attrs.items(): self.fields['k'].widget.attrs['placeholder'] = v['placeholder'] I have two problems: I cannot do this: fields = [K for K in self.field_attrs.keys()] I cannot do this: for k, v in self.field_attrs.items(): self.fields['k'].widget.attrs['placeholder'] = v['placeholder'] Please let me know how I can do what I am trying to achieve. Thank you -
How to use "for" statement in Django template
Here is Django template code. I tried to put out images to template. amount of image put out to template is depending on {{object.image_amount}} However since {{object.image_amount}} is an integer I can not iterate like this {% for i in object.image_amount %} So I tried this but does not work as well. {% for i in range object.image_amount %} What should I do? -
Cannot find Chrome binary when using selenium and Django on server
I used selenium with Django in local machine.All thing was good. Then, I want to deploy project on server. When I run page that selenium work on that, I got this error: WebDriverException at /panel/data/page Message: unknown error: cannot find Chrome binary I placed chromedriver on my project directory and get full path to executable_path. Also I set options with --headless for that. These are my codes: from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless") self.driver = webdriver.Chrome(executable_path='/full/path/to/chromedriver', chrome_options=chrome_options) How can I fix that? Also I have another question: Is it best practice and safe way(security) to use chromedriver on server? -
Adding new posts in production in React
I want to deploy react application, but the problem is I want to make like a blog application, where I can add new posts daily. I can make something like this using React combined with Django-rest-framework, but It's tricky for me to deploy the server also. Can I somehow deploy react application which will get the posts data from a rented server, or from somewhere on the Internet? -
staticfiles at django + nginx + gunicorn + vps
I have django project. I can't deploy it on vps. staticfiles not load... in Google Chrome Console panel: Status code at "Network": 403 Forbidden to my staticfiles /etc/nginx/sites-enabled/default server { listen 80; server_name <site_domain>; access_log /var/log/nginx/example.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/code/3p_site_new/; } location /media/ { root /root/code/3p_site_new/static/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } /root/code/3p_site_new/gunicorn_config.py command = '/root/code/3p_site_new' pythonpath = '/root/code/3p_site_new/3p_site_new' bind = '127.0.0.1:8001' workers = 3 user = 'root' limit_request_fields = 32000 limit_request_field_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=Site.settings' I am trying to start project with gunicorn -c "/root/code/3p_site_new/gunicorn_config.py" Site.wsgi tree: /root/code/3p_site_new/* |-- Main | |-- __init__.py | |-- admin.py | |-- apps.py | |-- creds.json | |-- forms.py | |-- migrations | | |-- <files> | |-- models.py | |-- my_config.py | |-- static | | |-- css | | | |-- <files> | | |-- js | | | |-- <files> | | `-- media | | `-- img | | |-- <files> | |-- templates | | |-- <files> | |-- tests.py | |-- urls.py | `-- views.py |-- Site | |-- __init__.py | |-- settings.py | |-- … -
Django: Verify email before creating a user
I have a Django project. I would like to verify email before creating a user account. What's the best way to do so? I decided to create an independent model first but I'm confused now. I decided not to use allauth model because it's too complex. Instead, I'm generating a random number and sending it over email. Once the activation code is confirmed, a user should type a password. After obtaining a verified email and password, I need to create a User model. Email will be used as a username. EmailVerifyModel class EmailVerifyModel(models.Model): email = models.EmailField(help_text=_('A valid email address please')) isVerified = models.BooleanField(default=False) activation_code = models.IntegerField(blank=True) EmailVerifyForm class EmailVerifyForm(forms.ModelForm): email = forms.EmailField(widget = forms.TextInput(attrs={ "type": "email", "name": "email", "id": "email", "placeholder": _("Email"), "class": "form-control form-control-md", "required": "" }), label = "") class Meta: model = EmailVerifyModel fields = ('email', 'activation_code') widgets = { 'activation_code': NumberInput(attrs={'class': 'form-control','placeholder': 'Verification code'}), } View def signup_view(request): form = EmailVerifyForm(request.POST or None) email_verified = False if form.is_valid(): new_email = form.save(commit=False) pin = randint(1000,9999) new_email.activation_code = pin new_email.save() cd = form.cleaned_data if not cd['activation_code']: current_site = get_current_site(request) subject = _('Verify Your Email') email_body = render_to_string('email/verify-email.html', { 'domain': current_site.domain, 'token': pin, }) msg = EmailMessage(subject, email_body, 'no-reply@test.com', …