Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What triggers these Django urls tag?
Programmers in the house, I want to know what triggers both of these types of django urls {% url '$name' %} {% url 'appname:$name' %} is there a setting that helps you to choose either of them? -
WaveSurfer.js audio is muted on the Django site (MediaElementAudioSource outputs zeroes due to CORS access restrictions...)?
For some reason, the audio file is muted on the site on the production server. The files are located on the Selectel container and and downloading from the Selectel CDN. When loading the page, this error appears in the console MediaElementAudioSource outputs zeroes due to CORS access restrictions for https://cdn.x.fullfocus.uz/media/audio/2021/12/20/news_audio-20211222-110648.mp3 On NGINX and CDN/Container setting there is the header Access-Control-Allow-Origin = '*' NGINX settings server { server_name xabardor.uz; client_max_body_size 500M; access_log /var/log/nginx/xabardor.log; root /var/www/html; index index.html index.html index.nginx-debian.html; location ~* \.(eot|ttf|woff|woff2|mp3|wav|ogg|wob)$ { add_header Access-Control-Allow-Origin *; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Host $http_host; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header 'Accept-Encoding' 'gzip, deflate'; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' '*'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-CustomHeader,Keep-Alive,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; } location = /favicon.ico { root /home/www/xabardoruz-django/xabardor/news/static/news/images/favicon.png; } location /static/ { root /home/www/xabardoruz-django/xabardor/static_files; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/xabardor.uz/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/xabardor.uz/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } Screenshot of CDN settings Screenshot of container settings Screenshot browser's Network Has anyone faced a similar problem? But all working fine without WaveSurfer.js with simple … -
NoReverseMatch at /courses/detail/modules/create_content
I want to create a quiz app for my e learning project and when i tray to add a new quiz in the modules content is says "Reverse for 'new-quiz' with arguments '('', '')' not found. 1 pattern(s) tried: ['courses/(?P<courses_id>[^/]+)/modules/(?P<modules_id>[^/]+)/quiz/newquiz\Z']" here is my code in quiz models from django.db import models from django.contrib.auth.models import User from courses.models import Modules,Courses class Answer(models.Model): answer_text = models.CharField(max_length=900) is_correct = models.BooleanField(default=False) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.answer_text class Question(models.Model): question_text = models.CharField(max_length=900) answers = models.ManyToManyField(Answer) points = models.PositiveIntegerField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.question_text class Quizzes(models.Model): module=models.ForeignKey(Modules,related_name='Quizzes',on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.CharField(max_length=200) date = models.DateTimeField(auto_now_add=True) due = models.DateField() allowed_attempts = models.PositiveIntegerField() time_limit_mins = models.PositiveIntegerField() questions = models.ManyToManyField(Question) def __str__(self): return self.title class Attempter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) score = models.PositiveIntegerField() completed = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username class Attempt(models.Model): quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE) attempter = models.ForeignKey(Attempter, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) def __str__(self): return self.attempter.user.username + ' - ' + self.answer.answer_text class Completion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course = models.ForeignKey(Courses, on_delete=models.CASCADE) completed = models.DateTimeField(auto_now_add=True) quiz = models.ForeignKey(Quizzes, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.user.username class Completion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) course … -
Can we fetch real time data with rest api in DRF if yes please tell me what steps we need to perform?
I want to build a listing API that returns the most recent data without reloading the page. -
Django update from 3.2 -> 4.0 and DRF Paths
I wanted to try and upgrade my django app that runs just fine on django 3.2.6 to the next release, but even in testing I came across the deprecated url (https://docs.djangoproject.com/en/4.0/ref/urls/). So I replaced the last lines in the urls.py: router = routers.DefaultRouter() router.register(r'products', views.ProductViewSet, basename = "products") urlpatterns = [ ..., url('api/', include(router.urls)), ] to: urlpatterns = [ ..., path('api/', include(router.urls)), ] but on a site that has the url http://127.0.0.1:8003/productspage/ I now get the error message: The current path, productspage/api/products/, didn’t match any of these. The path for the api in the ajax calls with django 3.26 was working: async function doAjax ( ) { let result = await $.ajax({url: "api/products/"}); } so I totally see why this would not work - but how (and where?) do I fix it? I thought about handing an absolute path (like ${window.location.hostname}/api/products/) to ajax, or providing a basename for the template? Can I fix it in Django? -
How to run celery task only once amongst multiple replicas?
I have a bunch of fargate instances on AWS, and they have celery running on them locally with Elasticache for redis. Due to Auto Scaling policies instances keep spawning and de-spawning, the issue is, the celery tasks that I have run as many times as there are replicas of my server. Can anyone suggest a way to prevent this behaviour? The celery beat tasks takes a bunch of rows in the database and performs certain operations on them, I tried adding a "processed" flag on the rows to indicate that they've been processed, but since all the replicas start the task at the exact same time, this solution fails. Currently the scheduler for celery beat is set to DatabaseScheduler. Here's the config that I have right now. CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL', 'redis://127.0.0.1:6379/0') CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'redis://127.0.0.1:6379/0') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'US/Central' CELERY_BEAT_SCHEDULE = { 'withdraw_money_daily': { 'task': 'app_name.tasks.perform_the_task', 'schedule': crontab(minute=0, hour=0), } } REDIS_HOST = os.environ.get('REDIS_HOST', 'localhost') CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [(REDIS_HOST, 6379)], }, }, } Command that starts the celery celery -A app worker -l info -E celery -A app beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler -
Django render image created with PIL
I know there are similare questions but they are 9 - 11 years old. I need to create an image dynamically with PIL in the view and then show it in the html. This is the code: views.py def certificate_preview(request, cert_id): template = "courses/certificate_preview.html" certificate_image = Image.new(mode="RGB", size=(400, 400), color=(209, 123, 193)) context = {"certificate_image": certificate_image} return render(request, template, context) certificate_preview.html ... <img src="{{ certificate_image }}" alt="No Image"> It doesn't work. What am I missing? -
Django Optimal Way of Getting a List of Model Attributes
Let's say this is my models.py file: class Paper(models.Model): title = models.CharField(max_length=20, null=False, blank=False) class Author(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) papers = models.ManyToManyField(Paper, null=False, blank=False) An author can have multiple papers and a paper can have multiple authors. I need to get all the papers titles for a given author. In my views.py, once I have an author object, I need to get a list with all the titles of his papers. I'm doing this: user = User.objects.get(username=request.user) author = Author.objects.get(user=user) papers = [paper.title for paper in author.papers.all()] Is there a way in Django to make this query without having to iterate over the author papers? Maybe there is a built-in function or something that I'm missing, any suggestions? -
NoReverseMatch at / Reverse for 'comment' with no arguments not found. 1 pattern(s) tried: ['comment/(?P<forum_id>[0-9]+)/$']Problem in Django 3:
The pages work together if I don't add the <int:forum_id> tag in the urls.py. When I do that the homepage stops working and give me the error message in the title. Home.hmtl <a href="{% url 'base:comment'%}"> <div class="card-header"> <div class="media flex-wrap w-100 align-items-center"> <div class="media-body ml-3"> <a href="javascript:void(0)" data-abc="true">{{ forum.user }}</a> <div class="text-muted small">{{ forum.date_created }}</div> </div> <div class="text-muted small ml-3"> <div><p>{{ forum.user}}</p></div> </div> </div> </div> <div class="scrollable"> <h3>{{ forum.title }} {{ forum.id}}</h3> <p>{{ forum.description }}</p> </div> <div class="card-body" style="border-color=red;"> {% for comment in comments%} {% if forum.id == comment.forum.id %} <div class="card-header"> <h6>{{ comment.user}}</h6> <p>{{ comment.discuss }}</p> </div> {% endif %} {% endfor %} </div> <div class="px-4 pt-3"> {% if user.is_authenticated %} {% comment %} <a href="{% url 'base:comment' forum.id %}"><button type="button" class="btn btn-primary" ></i>&nbsp; Reply</button></a> {% endcomment %} {% else %} <a href="{% url 'login' %}"><p>Please log in first to reply to messages</p></a> {% endif %} </div> {% endfor %} views.py from django.contrib.auth.forms import UserCreationForm from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth.models import User from .models import * from .forms import * # from .models import forum def about(request): return render(request, 'about.html') def home(request): forums=forum.objects.all() count=forums.count() discussions=[] for i … -
How to use datetime filter in django just for day and month?
I need to filter objects of users in a viewset whose birthday is today. Here, I will just need to check it with today's day and month irrespective of year. How do I do that? -
Using "%" as a modulo operator in Django template
I have color swatches being displayed under some ecommerce items in a Django 3.6 template. I would like to add a line break after every 5 swatches. To implement this I used this HTML. {% if forloop.counter % 5 == 0 %} <br> {% endif %} but when I render the page I get this error. Could not parse the remainder: '%' from '%' How can I use this operator inside of a template? -
NoReverseMatch at /details/The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f
I am trying to add comments in my blogs of my project. When I post a comment it shows NoReverseMatch at /details/The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f Here's is blog details page {% extends 'base.html' %} {% block content %} <div class="container jumbotron"> <div class="row"> <div class="col-sm-6"> <h2><i>{{blog.blog_title}}</i></h2> <h4>Posted By: @ {{blog.author}}</h4> <i><h6>Published On : {{blog.publish_date}}</h6></i> </div> <div class="col-sm-6"> <img src="/media/{{blog.blog_image}}" alt="{{blog.blog_title}}" title="{{blog.blog_title}}" width="500px" height="200px"> </div><hr> <p>{{blog.blog_content|capfirst}} </div> <div class="row"> <div class="col-sm-6"> <hr> <h5>Comments*</h5> </div> <div class="col-sm-6"> <form method="post"> {{comment_form.as_p}} {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm">Comment</button> </form> </div> </div> </div> {% endblock content %} views.py of blog details page- def blog_details(request, slug): blog= Blog.objects.get(slug=slug) commet_form=CommentForm() if request.method=='POST': commet_form=CommentForm(request.POST) if commet_form.is_valid(): comment=commet_form.save(commit=False) comment.user=request.user comment.blog=blog comment.save() return redirect('blog_details',kwargs={'slug':slug}) return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form}) urls.py mapping for blog details page urlpatterns = [ path('details/<slug:slug>',views.blog_details,name="blog_details"), ] servel url http://localhost:8000/details/The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f But in server site I get this NoReverseMatch at /details/The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f Reverse for 'blog_details' with keyword arguments '{'kwargs': {'slug': 'The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f'}}' not found. 1 pattern(s) tried: ['details/(?P<slug>[-a-zA-Z0-9_]+)$'] Request Method: POST Request URL: http://localhost:8000/details/The-Shortest-Scientific-Papers-Ever-Published-fa9c94fc-626a-446a-8b34-e6aeddcc086f Django Version: 3.2.8 Exception Type: NoReverseMatch Is there any problem with slug? models.py of the slug class Blog(models.Model): slug= models.SlugField(max_length=264,unique=True) help me out please. -
Posting data via cURL throws an APPEND_SLASH error
I'd like to post data to an endpoint hosted by Django. I am using cURL in my terminal to do this: curl -X POST -H "Content-Type: application/json" http://127.0.0.1:8000/bucket/create/ --data '{"name":"test2", "description":"hey"}' But this throws the following error: RuntimeError at /bucket/create You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/bucket/create/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. As you can see I've added a slash to the URL in my request and am not sure why this is happening. -
Not able to create multipe modal in django template
i am using django to create a website before deleting a product I want to ask "are you sure to delete" in modal form but modal is not opening in django template Here all Blogs are showing the Modal of the first one. I cannot create multiple modals for each Blog. {% for o in info %} <div class="job-right"> <div class="job-right-jobs"> <div class="jobs-main"> <div class="text-jobs"> <h5>{{o.0.name}}</h5> </div> </div> <p class="job-para"> phone :{{o.0.phone}} {% if o.1 %} Shipment :Assigned<br> {% for a in o.1 %} truck:{{a.transport}} pickup: {{a.job_id.picking_Address}}<br> drop: {{a.job_id.droping_Address}}<br> Job description:<br> {{a.job_id.job_description}}{% endfor %} {% else %}Shipment :Not Assigned{% endif %} </p> <div class="share"> <button type="button" id= "modalToggle" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#modal-blog-{{o.0.pk}}">Remove Driver</button> </div> <div class="modal fade" id="modal-blog-{{o.0.pk}}" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{o.0.name}}</h4> </div> <div class="modal-body"> <p>Are you sure you want to remove the driver?</p> </div> <div class="modal-footer"> <a type="button" href="{% url 'partner_company:RemoveDriver' o.0.pk %}" class="btn btn-danger">Yes</a> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div> {% endfor %} -
how we can show users in admin panel in django in m2m field without list comprehension
class Page(models.Model): user = models.ManyToManyField(User) post = models.TextField() post_date = models.DateField() def get_user(self): return ", ".join([str(p) for p in self.user.all()]) how we can do without list comprehension https://i.stack.imgur.com/PPnYj.png -
Django custom field has no attribute 'set_attributes_from_name'
I have a custom field to convert the input date to a timedelta in years, rounded up: class CustomField(models.Model): start_date = models.DateField() def days_to_years(self, date: timedelta): return math.ceil(date.days / 365) def save(self, *args, **kwargs): delta = datetime.today() - self.start_date self.start_date = math.ceil(delta.days / 365) super(CustomField, self).save(*args, **kwargs) Which I use in models like: from django.contrib.postgres.fields import ArrayField class Component(ComponentBase): years = ArrayField( CustomField() ) When I try to make migrations, the error AttributeError: 'CustomField' object has no attribute 'set_attributes_from_name is raised, which I can't seem to debug because I'm still quite fresh to Django. Any suggestions would be very welcoming :). -
django forms is_valid() method always returning true if all the form field's required is false
models.py created a model registerForm.my database is mysql. from django.db import models class registerForm(models.Model): name = models.CharField(max_length=50 ) username = models.CharField( max_length=50) email = models.EmailField(max_length=50) password = models.CharField(max_length=50) class Meta: db_table = 'userForm' def __str__(self): return self.name forms.py from django import forms from django.forms import widgets from login_and_logout.models import registerForm class regForm(forms.ModelForm): def __init__(self, *args, **kwargs): # first call parent's constructor super(regForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['name'].required = False self.fields['username'].required = False self.fields['email'].required = False self.fields['password'].required = False class Meta: model = registerForm fields = "__all__" views.py check form is valid using is_valid() method . i printed def signup(request): if request.method == 'POST': form = regForm(request.POST) print(form.is_valid()) if form.is_valid(): return HttpResponse('success') else: return HttpResponse('fail') form = regForm() return render(request, 'signup.html', {'form': form}) i trying to implement form validation using javascript in client side and serverside validation in dajngo . in order to acheive form validation without required attribute i give required false in dajngo forms.py. but after the is_valid() method always returning true. but if i remove the init funtion i used to remove requied field in forms.py the is_valid() works. i want to remove the required field and also i want to work the is_valid() … -
Filter queryset only where the user is added to ManyToManyFIeld
I want to return all leads that contain a current user. How to do it? Models.py class CustomUser(AbstractUser): def __str__(self): return self.email class Lead(models.Model): budget = models.IntegerField() buyer = models.ManyToManyField(CustomUser) What queryset is expected Lead.objects.filter(buyer__have=request.user) -
What is latest(>9.6) postgres version compatible with Django 1.11.20?
Postgres 9.6 is deprecated, we need to upgrade to a version which is compatible with Django 1.11.20. I have already checked django docs but it mentions any postgres version>9.3 but how do i verify it? Thanks for the support in advance:) -
Django/React/Firebase - CORS error when uploading big files
I have a website with React hosted on Firebase, with Django for backend running on a server with nginx. On this website I have a form where the user can upload up to 3 images. On my local PC it works fine, but on the production environment I get this error when I try to upload big files (more than 5mb): A server/network error occurred. Looks like CORS might be the problem. Sorry about this - we will get it fixed shortly. Now the thing is that the images get uploaded normally, I can see them when I check the submitted form on the website admin area, but on the frontend, after submitting the form, instead of the success message I get that error. I have incresed nginx client_max_body_size 15M, but I still get the error. But given that the images do get uploaded, I think the max body size is not the problem. -
How can we use consumer sent function in django model manager function?
i'm trying to send a message whenever a new task created.. The problem here is.. there is not error coming in terminal and anywhere but the message that suppose to send is not sending.. the model manager function is unable to reach consumer sent function... class TaskManager(models.Manager): async def send_now(self,data): ........ room_name = await create_roomname_threadID(mydata["project_key"],username) print("room_name :",room_name) channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( room_name, { 'type': 'sent', 'object': object }) asgi from notifications.sockets import routing "websocket": AuthMiddlewareStack( URLRouter( routing.websocket_urlpatterns, ) ), routes websocket_urlpatterns = [ path('ws/project/<str:project_key>/<str:username>/', consumers.ProjectConsumer.as_asgi()), ] consumer ..... # Receive message from room group async def sent(self, event): sender = event['object']["sender"] receiver = event['object']["receiver"] message = event['object']["message"] print("hey hey hey ") # Send message to WebSocket await self.send(text_data=json.dumps({ 'sender':sender, 'receiver':receiver, 'message':message, })) -
Desing path to create a C++ web framework
I would like to pose a metatopic about a nice (the best it's too much, I guess) way to develop a C ++ web framework, like Java's Spring or Python's Django. We need some sockets programming, some nice template programming to offer a nice and usable API, web request and response handlers, database handlers, possible some kind of ORM ... but ... what more? And in which order? How do you imagine a nice abstract approach (the big steps) that you should make to create a monster project like this? Bonus points to who answer this one thinking about the best user experience (since C++ it's not exactly the most syntax friendly programming language) using the internal API's that should be the core of the project, (in big words, not concrete). -
problem showing errors in field in django form
I have a problem displaying an error in a field of my form In the view I get this but without the error description: But in the html the tag if the description exists, it just isn't showing it to me: Here is the implementation of the error, it is nothing to write home about: def clean(self): form_data = self.cleaned_data result = utils.verificarFechaPeriodo(self.AIGN_PER_ID, form_data['act_fechaini'], 6,'YYYY-MM-DD') if result[0][0] is not None: self._errors["act_fechaini"] = [str(result[0][0])] del form_data['act_fechaini'] return form_data -
why this occurs AttributeError: 'User' object has no attribute 'cusromer'
why this error occurs I cant understand .I am creating a e-commerce website where a customer can add products to cart and and purchase it # .I look allot but not getting the right answer which can remove that please help me to solve this it is showing'User' object has no attribute 'Customer' and Customer = request.user.Customer thus there is a problem in customer word or some other thing . models.py from django.db import models from django.contrib.auth.models import User from django.db.models.fields.related import OneToOneField class Customer(models.Model): user = OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=400, null=True) email = models.EmailField(max_length=254) def __str__(self): return self.name class products(models.Model): name = models.CharField(max_length=500, null=True) price = models.FloatField() degital = models.BooleanField(default=False, null=True, blank=False) image = models.ImageField(null=True,blank=True) def __str__(self): return self.name @property def imageURL(self): try: url =self.image.url except: url ='' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=500, null=True) def __str__(self): return str(self.id) class Orderitem(models.Model): product = models.ForeignKey(products, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class shippingaddress(models.Model): customer = models.ForeignKey( Customer, on_delete=models.SET_NULL, null=True, blank=True ) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True) address = models.CharField(max_length=500, null=True) city = … -
Not able to redirect the forms in my website and show Success message in django
I am new to Django, The form takes input from a user and saves it in /admin and also sends mail to my email.I am trying to get success message after clicking on Send message but I am not able to get the Success message.Also I want page to redirect in same contact form and cleared input fields. Thankyou #My Views.py from django.shortcuts import render from django.shortcuts import render from collections import namedtuple from django.contrib import messages from django.shortcuts import redirect, render from django.views.generic import ListView, CreateView, DeleteView, DetailView from . import models from . import forms from django.core.mail import send_mail from django.conf import settings from django.http import HttpResponseRedirect def home(request): return render(request, 'index.html') def contact(request): contact = models.Contact.objects.all() form = forms.ContactForm() if request.method == 'POST': firstname = request.POST['firstname'] lastname = request.POST['lastname'] email = request.POST['email'] phone = request.POST['phone'] message = request.POST['message'] data = { 'firstname': firstname, 'lastname': lastname, 'email': email, 'phone': phone, 'message': message } message = ''' The message is sent by: {} {} Email_id: {} Phone No: {} Message: {} '''.format(data['firstname'], data['lastname'], data['email'], data['phone'], data['message']) send_mail(data['email'], message, '', ['bbchanna@gmail.com']) form = forms.ContactForm(request.POST) if form.is_valid(): form.save() form = forms.ContactForm() return render(request, 'contact.html', {'form': form, "success": True}) else: raise NotImplementedError …