Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to display all the data entered by user in view_project.html page in django
views.py @login_required(login_url="/accounts/login/") def add_project(request): if request.method == 'POST': form = forms.CreateProject(request.POST, request.FILES) if form.is_valid(): # save in db instance = form.save(commit=False) instance.candidate = request.user instance.save() return redirect ('view_project') else : form = forms.CreateProject() return render(request, 'home/add_project.html', {'form': form}) @login_required(login_url="/accounts/login/") def view_project(request): return render(request, 'home/view_project.html') This is the views.py file where the project is added into the database for a particular user and the HTML file used for this is add_project.html -
Mail is not validated because I do not change my username
I have a form that takes "username" from the User model and my own "email" field. I want to change this data for the User model. At first glance everything seems to work fine, the name changes and the mail is the same. But if I only change the mail and I don't touch the username, I get an error: "A user with this name already exists. Is there any way I can make an exception for this situation? file views.py: form=UserUpdateForm(request.POST) if form.is_valid(): user=User.objects.get(username=self.request.user) user.username=form.cleaned_data.get('username') user.email=form.cleaned_data.get('email') user.save() file forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField(required=False) def __init__(self, *args, **kwargs): super(UserUpdateForm, self).__init__(*args, **kwargs) if 'label_suffix' not in kwargs: kwargs['label_suffix'] = '*' self.fields['username'].widget = forms.TextInput(attrs={'class':'input-text'}) self.fields['email'].widget = forms.EmailInput(attrs={'class':'input-text'}) class Meta: model = User fields = ("username","email",) def clean_email(self): cleaned_data = super(UserUpdateForm,self).clean() email=cleaned_data.get('email') return email -
Django , upload multiple images with formset's
I've been trying for days to understand the reason for my error, in the first phase I detected that it was missing {{ formset.management_form }} in the html, which i include and still continues to give the same error: "ManagementForm data is missing or has been tampered with" And I don't know if my views are the way they should be done. Models class Intervencao(models.Model): ........ class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) <!-- e Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = __all__ class TabletFormImagem(forms.ModelForm): imagem = forms.ImageField(required=True) class Meta: model=Imagem fields = ['imagem',] Views def project_detail_chefe(request, pk): ImagemFormSet = modelformset_factory(Imagem,form=TabletFormImagem, extra=3) instance = Intervencao.objects.get(id=pk) d1 = datetime.now() intervencaoForm = TabletForm2(request.POST or None, instance=instance) formset = ImagemFormSet(request.POST, request.FILES,queryset=Imagem.objects.none()) if request.method == "POST": if intervencaoForm.is_valid() and formset.is_valid(): instance_form1 = intervencaoForm.save(commit=False) instance_form1.data_intervencao_fim = d1 instance_form1.save() images = formset.save(commit=False) for image in images: image.intervencao = instance_form1 image.save() return redirect('index') else: intervencaoForm = TabletForm2(request.POST) formset = ImagemFormSet(queryset=Imagem.objects.none()) context = { 'intervencaoForm':intervencaoForm, 'formset':formset, } return render(request, 'tablet/info_chefes.html', context) HTML <form method="post" enctype="multipart/form-data" id="gravar"> <div class="row"> <div class="col-md-12"> <table> {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} … -
If statement in Django views
I have followed an ecommerce tutorial by Dennis Ivy in Django (Python). I want to expand on the project by adding product categories. So the idea is that every product has a dropdown menu (models.py) CATEGORIES = ( ('code','CODE'), ('books', 'BOOKS'), ('computer','COMPUTERPARTS'), ('other','OTHER'), ) category = models.CharField(max_length=15, choices=CATEGORIES, default='code') The store.html shall only render products from a given category. If I type 'localhost/code' in my browser it shall only display the items that have the category: 'code'. Currently it just displays everything, when I just goto 'localhost/'. I have thought about making a urlpattern for each individual category, but I think it will get messy pretty quickly. I have a function called store in views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) Is there a way to return only a specific category -or to return something else than objects.all()? products = Product.objects.all() The store.html looks like this: {% for product in products %} <div class="col-lg-4"> <img class="thumbnail" src="{{product.imageURL}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> {{product.about}}<br><br> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> {{product.category}} <h4 style="display: inline-block; float: right"><strong>${{product.price}}</strong></h4> </div> </div> {% … -
Django Orm Compare to same model querysets
I am trying to convert a sql join query to django orm, not quite getting how to do it. Models class Author(models.Model): author_name = models.CharField( verbose_name='Author', primary_key=True, max_length=250) country = models.CharField(verbose_name='Country', null=False, blank=False, max_length=250) def __str__(self): return self.author_name class Publisher(models.Model): publisher_name = models.CharField( verbose_name='Publisher', primary_key=True, max_length=250) pub_add = models.TextField(verbose_name='Address', blank=False, null=False) def __str__(self): return self.publisher_name class Book(models.Model): isbn = models.IntegerField(verbose_name='ISBN', primary_key=True) title = models.CharField(verbose_name='Title', unique=True, blank=False, null=False, max_length=250) pub_year = models.IntegerField(verbose_name='Publish Year', blank=False, null=False) unit_price = models.IntegerField(verbose_name='Unit Price', blank=False, null=False) authors = models.ForeignKey(Author, verbose_name='Author of book', on_delete=models.DO_NOTHING) publishers = models.ForeignKey(Publisher, verbose_name='Publisher of book', on_delete=models.DO_NOTHING) Sql Query is select distinct B1.title from Book B1, Book B2 where B1.unit_price > B2.unit_price and B2.pub_year = 2004; django query I tried qs = Book.objects.filter( pub_year=2004 ) qs = Book.objects.filter( unit_price__gt__in=qs ) It gives this error I feel like this is actually really, really easy and I am missing some obvious thing, any guidance will be helpful. Thanks. -
Add identifier only if there is a conflict for slug
I have a slug customization, It provides to create slug from title automatically. Here is my code, #models.py from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class Blog(models.Model) title = models.CharField(max_length=200) slug = models.SlugField(blank=True) def get_absolute_url(self): return reverse('school', kwargs={'slug':self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) #admin.py class BlogAdmin(admin.ModelAdmin): list_display = ('title') prepopulated_fields = {'slug': ('title',)} admin.site.register(Blog,BlogAdmin) #urls.py from django.urls import path from .views import * urlpatterns = [ path('blog/<slug:slug>', entry.as_view(), name='entry'), ] If I make Slug as unique=True, when blog titles are the same(It could be same), slugs should be changed manually. I don't want this. I want to add identifier with numbers but only if there is conflict. The scenario I want is as follows, Lets assume that, Admin creates a blog, blog title is "London travel guide" -> This is the first time created blog with this title. so slug is "london-travel-guide" Second time admin creates a blog with title as "London travel guide" slug should be "london-travel-guide-1" Third time, slug should be "london-travel-guide-2" and so on. How can i implement this, thanks for help. -
URL Pattern with Primary Key not working properly
Need help with the regex in urls. I'm building a different app, not the one shown in the lecture above. To relate to my case with the lecture, School is Clients, and Students is categories. In urls.py file, from url_patterns : url(r'^(?P<pk>[-\w]+)/$', views.DetailClientList.as_view(), name='Detail_Client_List'), This work correctly, with the address being http://127.0.0.1:8000/App1/cli1/, where cli1 is a Clients table primary key (one of the records). But when I put the line below in url patterns (instead of the above) url(r'^<str:pk>/$', views.DetailClientList.as_view(), name='Detail_Client_List') I get the following error (same error for int:pk): Page not found (404) Request Method:GET Request URL:http://127.0.0.1:8000/App1/cli1/ The resulting URL is the same in both cases described above. So where am I going wrong here. I'm guessing its an issue with the url pattern regex (although resulting URL is the same?). Please help. TIA! -
There should be an error here, but does'nt
i'm following the Django's tutorial for first app, and in the Part 5 they say: Different error? If instead you’re getting a NameError here, you may have missed a step in Part 2 where we added imports of datetime and timezone to polls/models.py. Copy the imports from that section, and try running your tests again. But i not missed nothing, i write line by line, and i not received the expected message. I put my code below, if someone with more experience can help me to understand why i not receive the error message, i'll thank you ( the word appreciate and its meaning is very strange uhh). my_project/project/polls/model.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text my_project/project/polls/tests.py import datetime from django.test import TestCase from django.utils import timezone from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self) time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(),False) -
What is forloop.counter in Django?
This is the code in Django official website tutorial: <h1>{{ question.question_text }}</h1> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} <input type="submit" value="Vote"> </form> -
Video doesnot load in django
I am trying to play video in my django built website but it is not playing Here is my setting code STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') ##lINKING THE STATIC FILES THAT IS CSS STATICFILES_DIRS= [ STATIC_DIR ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/movies/' Views.py def Movie_detail(request, pk): post = get_object_or_404(Postmovie, pk=pk) ##EITHER gets specific object from primary key or return 404 stuff_for_frontend = {'post': post} return render(request, 'Movie_Management_System/Movie_details.html',stuff_for_frontend) #render movie details Source i gave in Movie_details.html <br><br> <video width='1000' controls> <!--video player using html--> <source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'> </video> <br><br> Directory structure is like this Directory looks like enter image description here -
Django E.410 errors on runserver
ERRORS: ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. System check identified 1 issue (0 silenced). it is already present in it but why error -
How can I request a POST to the django rest framework except for null json?
I'm making an api with the django rest framework. Now, in my api, where I don't want the content to go in, I'm sending a request: "field": null. But I want to send a request without specifying this field in json, how should I handle it? Here's my code. class PostSerializer (serializers.ModelSerializer) : owner = userProfileSerializer(read_only=True) like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() images = ImageSerializer(read_only=True, many=True) liked_people = LikeSerializer(many=True, read_only=True) tag = serializers.ListField(child=serializers.CharField(), allow_null=True) #If I don't want to get a tag, I want to erase the tag field altogether instead of "tag": null. comments = CommentSerializer(many=True, read_only=True) class Meta : model = Post fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments') -
django verion:1.11.7, while python manage.py collectstatic i am getting following error
(ecommerce) PS C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\src> python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management_init_.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management_init_.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 173, in handle if self.is_local_storage() and self.storage.location: File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\utils\functional.py", line 239, in inner return func(self._wrapped, *args) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\lib\site-packages\django\core\files\storage.py", line 283, in location return abspathu(self.base_location) File "c:\users\heisenbergsmn\appdata\local\programs\python\python38\lib\ntpath.py", line 527, in abspath return normpath(_getfullpathname(path)) TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not tuple (ecommerce) PS C:\Users\HeisenbergSMN\Desktop\developer\ecommerce\src> -
Django - get model in navbar
I have a class in models: class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200, null=True, blank=True) email = models.CharField(max_length=200, null=True, blank=True) device = models.CharField(max_length=200, null=True, blank=True) Is there a way to access this model in navbar without creating entry in "views.py"? I would like to access similarly to {{ request.user.id }}. -
How can I do to have a new id?
Hello I am using Django below is my code : A = myobject.objects.filter(test='a') A.test= 'b' A.save() But I noticed when I saved that I have just one query like this : myobject.objects.filter(test='b') Not like this : myobject.objects.filter(test='a') whereas I want both. Could you help me please ? -
Django not show image field
Not showing image when upload , what is problem ? setting.py MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = 'media/' html. {% for tt in article %} <div class="content_box"> <div class="content_l left"> <div class="horoscope_box_big"> <div class="blog_img1"> <img src="{{ tt.image.url }}" alt="{{tt.title}}" width="50%" /> {{ tt.image.url }} </div> <h1 class="blog_title1"> {{ tt.Title }} <div class="blog_descr1"><h1>more about</h1> <p> {{ tt.body }}</p> </div> </div> {% endfor %} models.py class Blogmodel(models.Model): Title = models.TextField(blank=True, null=True) image = models.ImageField(upload_to="images/",null=True) body = RichTextField(blank=True, null=True) slug = AutoSlugField(populate_from='Title', unique=True,blank=True, null=True) def __str__(self): return self.Title views.py def blog_list(request): articles = Blogmodel.objects.all() args = {'articles':articles} return render(request,'blog.html',args) def blogDetail(request, slug): article = Blogmodel.objects.filter(slug=slug) args = {'article':article} return render(request,'blogdetail.html',args) urls.py from django.urls import path from .views import singCategory,Home,blog_list,blogDetail from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('',Home,name= "Home"), path('horoscope/<slug:slug>/<slug:cat>',singCategory,name='singCategory'), path("blog/",blog_list, name="blog_list"), path("blog/<slug:slug>",blogDetail, name="blogDetail"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
File upload problem with AWS using Django
I have deployed my django app through cpanel. Static and media files are correctly served through AWS S3. But when i try to upload a file/pic it is not uploading and shows no error and redirects to home page with the url of the page on which file was uploaded. Home page URL: www.example.com, Upload page URL:www.example.com/upload. Bucket access is public. IAM user has full access to S3 I will be very thankful to you for your precious time and help. CORS Policy <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> Bucket Policy { "Version": "2012-10-17", "Id": "Policy1603207554013", "Statement": [ { "Sid": "Stmt1603207062804", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::django-bucket/*" }, { "Sid": "Stmt1603207552031", "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::085459706277:user/django_user" }, "Action": "s3:*", "Resource": [ "arn:aws:s3:::django-bucket/*", "arn:aws:s3:::django-bucket" ] } ] } settings.py AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATIC_LOCATION}/' STATICFILES_STORAGE = 'stock_app.storage_backends.StaticStorage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'stock_app.storage_backends.PublicMediaStorage' storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class StaticStorage(S3Boto3Storage): location = 'static' default_acl = … -
how to reflect changes made on postgres database of django from one pc to other
We three working with Django and postgres is the database. Whenever we push the code to GitHub. The database data is not reflecting. The data I stored is visible to me only. The postgres user, password and database name are same on all our laptops. How to make when I push that has to go their databases also. -
How to send multiple json objects to a django model serializer
This is my modelserializer class Testmasterserializer(serializers.ModelSerializer): class Meta: model = Dime3d_testmaster fields = ('visitId','testId','testType','status') I want to send multiple json object how can I send [{ "visitId": "wsTp6anrDBQE", "testId": "RVeaJn6n", "testType": "windlass", "status": "fine" }, { "visitId": "wsTp6anrDBQE", "testId": "Sq3LxKsNDP", "testType": "windlass", "status": "fine" } ] Like this. How can I do it. Is there anyway? I dont want to use nested serializer as in that one params is added as like this ["data" :{ "visitId": "wsTp6anrDBQE", "testId": "RVeaJn6n", "testType": "windlass", "status": "fine" }, { "visitId": "wsTp6anrDBQE", "testId": "Sq3LxKsNDP", "testType": "windlass", "status": "fine" } ] I dont want this -
Resend failed web socket messages django
I have setup django channels with redis: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": {"hosts": [(REDIS_HOST, REDIS_PORT)]}, } } On connection to my websocket channel I update a row in my database for the corresponding user/team - socket_channel - with the websocket channel_name. team.socket_channel = self.channel_name team.save() On disconnection, I remove this from the row. I have created a handler for my Team model: def send_ws_message(self, message: WSStruct) -> bool: channel_layer = get_channel_layer() if not self.socket_channel: logging.error(f"{self.username} is not connected to a socket") # TODO store message in redis return False async_to_sync(channel_layer.send)(self.socket_channel, message.dict()) return True I am wanting to add two pieces of functionality: When the team connects to the channel again they will receive all messages that were not received because of the team not actually being connected to the websocket (the TODO above). A sort of ack that the client actually received the websocket message and if not will store for sending on reconnection/ping-pong. I am assuming the best way to do this is with a redis store? But I would also like to not reinvent the wheel here as imagine this is a fairly common design? Any advice would be greatly appreciated. -
Problem with ValidationError function when writing your own validation
Problem with ValidationError function when writing your own validation. I want to write my own ValidationError function without using the clean prefix. When I use the ValidationError function, I expect the error to be displayed in a form, but the error is displayed in the console. What can you give me advice? if clean_data['email']!=user.email: if User.objects.filter(email=clean_data['email']).exists(): raise ValidationError('') -
Ajax is reloading the entire page while using django pagination
ajax : AJAX.update('update', {'target_url': SEARCH_URL, 'data': SEARCH_PARAMS, 'processor': function (data) { var $html = $(data.html); $('#update').replaceWith(data.html); } }); html : <div id="update" style="overflow-x: hidden;"> <table> <thead> ---------- </thead> <tbody> {% for yacht in page.object_list %} <tr> ----- </tr> {%endfor%} </tbody> </table> Table is using django pagination while we edit 3rd page its redirecting to page1. How can we restrict redirection to the first page using AJAX? -
Is Django Backend APi reliable with React Frontend
I need guidance or explanation about is Django Backend api is reliable or useful for React or not. Any One Full stack developer provide me detail. -
Django ORM query by model method returned value
I am trying to query fields that are model fields, not user fields. These is my models: class Itinerary(models.Model): days = models.PositiveSmallIntegerField(_("Days"), null=True, blank=True) class Tour(models.Model): itinerary = models.ForeignKey( Itinerary, on_delete=models.CASCADE ) start_date = models.DateField(_("Start Date"), null=True, blank=True) def get_end_date(self): return self.start_date + datetime.timedelta(days=self.itinerary.days) I am trying to query the Tour table like this below way: tour = Tour.objects.filter( get_end_date__gte=datetime.now() ) But it returning the error that i don't have such fields Can anyone help me in this case? -
django how to create instance of user
I am creating a simple application, successfully created for a single user, but I want to develop for multiple users, but unable to do so... i.e. user A can create his task and save in the database. similar B user can create tasks and store in the database. and each can see their own tasks I am newbie unable to proceed with the creation of instance can someone please guide me or point me to a blog ( searched online but no help ) I already asked this question however i was not clear ( django each user needs to create and view data Issue) hope now I am clear. My model : from django.contrib.auth.models import User, AbstractUser from django.db import models # Create your models here. from django.db.models import Sum, Avg class Task(models.Model): user = models.ForeignKey(User, null=True,on_delete=models.CASCADE) title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True,auto_now=False,blank=True) purchase_date = models.DateField(auto_now_add=False,auto_now=False,blank=True,null=True) price = models.FloatField(max_length=5,default='0.00',editable=True) def __str__(self): return self.title @classmethod def get_price_total(cls): total = cls.objects.aggregate(total=Sum("price"))['total'] print(total) return total Views def createTask(request): form = TaskForm() if request.method =='POST': form=TaskForm(request.POST) if form.is_valid(): form.save() return redirect('query') context = {'form':form} return render(request,'tasks/create.html',context) urls from django.urls import path from . import views urlpatterns = [ #path('', views.index, …