Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Pagination count increasing endlessly
I have created a Django app wherein my views.py I have the following code: a)For a POST request view- p = Paginator(bigarray, 5) page = request.POST.get('page' , 1) pagelist = p.get_page(page) a)For a GET request view- p = Paginator(bigarray, 5) page = request.GET.get('page' , 1) pagelist = p.get_page(page) The HTML page that renders this code is the follows: <ul class="pagination justify-content-center"> {% if data.has_previous %} <li class="page-item"> <a href="?page=1" class="page-link">&laquo; First</a></li> <li class="page-item"> <a class="page-link" href="?page={{ data.previous_page_number }}">Prev</a> </li> {% endif %} {% if data.has_next %} <a href="?page={{ data.next_page_number }}" class="page-link">Next</a></li> <li class="page-item"> <a class="page-link" href="?page={{ data.paginator.num_pages }}">Last &raquo;</a> </li> {% endif %} <li class="page-item disabled"> <a href= "#" class="page-link"> Currently {{data.number }} of {{data.paginator.num_pages }} pages </a> </li> </ul> The page renders this image in the link: [1]: https://i.stack.imgur.com/MBrIM.png But now if I go over to the last page, it becomes this(one extra pagination page is getting create): Currently 3 of 4 pages (Could not append the image as only one image link was being supported on this post) The contents on each of the paginated sections is just replicated. What could be the root cause of the ever increasing pagination sections? Any help would be greatly appreciated, thank … -
django - how to reset superuser passwowrd if it's lost when the app online
I'm still a biginner whith django and web development in general and I now almost nothing about deployment and how the stuff works online, I noticed that the login page on django admin panel does not contain a button or a url to reset the passowrd of the superuser if it's lost although it's possible to recreate a new one with the cmd, but I was wondering how will the user reset he's password or recreate a new superuser when the app is online ? -
Error Django The 'imagem' attribute has no file associated with it
can someone help me understand why the tag: {{ post.author.imagem }} Returns me --> perfil/imagem1.jpg and the tag {{ post.author.imagem.url }} Returns me an error: The 'imagem' attribute has no file associated with it. html {% if post.author.imagem %} <img src="{{ post.author.imagem.url }}" alt="{{ post.author.first_name }}" class="rounded-circle" style="width: 50px; height: 50px; margin-right: 20px;"> {% endif %} class Post(models.Model): author = models.ForeignKey(get_user_model(), verbose_name='author', on_delete=models.CASCADE , null=True, blank=True) -
How to get latest db record based on 2 columns in django
I have a table which have combination of foreign keys F1, F2 and a column for storing the created datetime. How can I query the latest records for the combinations of the foreign keys. These are the columns in table. ChallengeID, UserID, createdDatetime, points If a challengeID is CH1 and we have 2 users U1, U2, and there could be multiple records for that combination. for ex. CH1 and U1, there are 5 records. and out of those one is latest record based on createdDatetime. How do I get the points value from the latest records for all the users for a particular challenge using Django ORM? something like: CH1, U1 - PV1 CH1, U2 - PV2 CH1, U3 - PV3 Here's the code that I tried. def challenge_leaderboard(request): challenge_id = request.GET.get('challenge_id') users = RewardPointLog.objects.filter(challenge_user__challenge_id=challenge_id).values_list('user', flat=True) users_points = {} for user in users: points = RewardPointLog.objects.filter(challenge_user__challenge_id=challenge_id, challenge_user__user=user).latest('created_datetime').points users_points[user.id] = points return Response(users_points, status=200) -
I have face a problem with python datetime objects, specifically the datetime.timedelta()
I am trying to find the difference in days as a number and not a datetime.timedelta() instance. I am using Django version 3.2 and fetching date values from a form on a template [Assume all the neccesary libaries are imported because its not an import error i am facing here] here is the code from the template - dateform.html <span style="position: absolute; right: 0%;font-size: 0.5em;" class="pull-left"> <form method="GET" action="{% url 'shifts:timeSheetFiltered' %}"> {% csrf_token %} start <input type="date" id="start-date" name="start-date" > end <input type="date" id="end-date" name="end-date" > <button type="submit" class="btn btn-xs btn-info"><i class="fa fa-filter"></i></button> </span> </form> </span> here is the view function in one of the django views. def timeSheetFiltered(request): end_date = forms.DateField().clean(request.GET.get('end-date')) start_date = forms.DateField().clean(request.GET.get('start-date')) num_days = end_date - start_date num_weeks = math.ceil(num_days/7) week_pack = [] counter = 0 while counter <= num_days: week_pack.append(start_date + timedelta(days=counter)) counter = counter + 1 shifts = Shift.objects.filter(time_added__range = [start_date,end_date]) context = { 'shifts': shifts, 'start_date': start_date, 'end_date': end_date, 'week_pack': week_pack, 'num_weeks': num_weeks } return render(request, 'shifts/timeSheetFiltered.html', context) Now when trying to process the request, i know the num_days variables is returning a datetime.timedelta(days={what-ever-the difference-here}) . I do not want that object, how can i extract the number of days as a plain … -
Is it valid to use LoginRequiredMixin, PermissionRequiredMixin in DRF APIview?
**DRF API view ** class UserAPI(**LoginRequiredMixin, PermissionRequiredMixin,**generics.ListAPIView): queryset = User.objects.filter(user_type="BRANCH_MANAGER") serializer_class = UserSerializer permission_required = ["accounts.view_branchmanager"] login_url = "api-auth/login/" -
PersonalInfo matching query does not exist
I wanted to add a multiple choice field to my form and after searching I finally made it work. however, when I create a new user and try to fill the personal info form, it gives me PersonalInfo matching query does not exist error. these are my codes: models.py: class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_fields = models.ManyToManyField(Field, blank=True) forms.py: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] views.py: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() form.save_m2m() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) I know that the issue is because of this line in views: form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) when I remove the instance, the form gets saved as the users' personal info but form wont replace the previous, it creates a new one. then again I put instance back and try to save the form and everything … -
Share details view to modal in django
Getting stuck to share details view to modal. Found this answer but can't understand it properly. I am sharing my code below. Views.py from django.shortcuts import render from .models import Post from django.views.generic.list import ListView from django.urls import reverse_lazy class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'f_home/index.html' models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): name = models.CharField(max_length=200, blank=True) email=models.CharField(max_length=200, blank=True) address=models.CharField(max_length=400, blank=True) weblink = models.URLField(max_length=200) image = models.ImageField( default='default.png', upload_to='uploads/%Y/%m/%d/') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'Added {self.name} Profile' Template {% for post in posts %} <div class="purple card"> <div class="image"> <img src="{{ post.image.url }}"> </div> <div class="content"> <div class="header"><a href="{{ post.weblink }}">{{ post.name }}</a></div> </div> <div class="ui bottom attached button" onclick="pop()"> <i class="globe icon"></i> <p>View Details</p> </div> </div> {% endfor %} <div class="ui modal"> <i class="close icon"></i> <div class="header"> Modal Title </div> <div class="image content"> <div class="ui medium image"> <img src="{% static 'images/cool-background.png' %}"> </div> <div class="description"> <div class="ui header">We've auto-chosen a profile image for you.</div> <p>We've grabbed the following image from the <a href="https://www.gravatar.com" target="_blank">gravatar</a> image associated with your registered e-mail address.</p> <p>Is it okay to use this photo?</p> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" … -
TypeError: Cannot read properties of undefined (reading 'image')
import React from 'react' import { Link } from 'react-router-dom' import { Row, Col, Image, ListGroup, Button, Card } from 'react-bootstrap' import Rating from '../components/Rating' import products from '../products' function ProductScreen({ match }) { const product = products.find((p) => p._id === match.params.id) return ( Go Back <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> </ListGroup.Item> <ListGroup.Item> <Rating value={product.rating} text={'${product.numReviews} reviews'} color={'#f8e825'} ></Rating> </ListGroup.Item> <ListGroup.Item> Price: ₹{product.price} </ListGroup.Item> <ListGroup.Item> Description: {product.description} </ListGroup.Item> </ListGroup> </Col> <Col md={3}> <Card> <ListGroup variant="flush"> <ListGroup.Item> <Row> <Col>Price:</Col> <Col> <strong>{product.price}</strong> </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Row> <Col>Status:</Col> <Col> {product.countInStok > 0 ? 'In Stock' : 'Out of Stock'} </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Button className='btn-block' type='button'> add to Cart </Button> </ListGroup.Item> </ListGroup> </Card> </Col> </Row> </div> ); } export default ProductScreen enter image description here -
django: how to read and manipulate .csv file from View.py
I am trying to work from csv files located inside of a django app. I am trying to load the file using pandas like: pd.read_csv("...") without success, I keep getting an error. Here is what the directory tree looks like: ├── __pycache__ │ ├── forms.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── views.cpython-36.pyc │ └── urls.cpython-36.pyc ├── apps.py ├── files │ ├── t1.csv │ ├── t2.csv │ ├── t3.csv │ ├── t4.csv │ └── parametre.csv ├── finished_apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ ├── 0002_remove_carriers_carriersheet.cpython-36.pyc │ ├── 0003_auto_20211021_1200.cpython-36.pyc │ ├── 0004_auto_20211021_1203.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── views.py ├── templates │ ├── add_carrier.html │ ├── base.html │ ├── delete_carrier.html │ ├── delete_carrier_confirmation.html │ ├── _carrierdetails.html │ ├── _carrierlist.html │ ├── simulation.html │ └── update_carrier.html └── urls.py I have tryed the following inside of views.py df = pd.read_csv("/files/t1.csv") #not working df = pd.read_csv("./files/t1.csv") #not working df = pd.read_csv("t1.csv") #not working df = pd.read_csv("../files/t1.csv") #not working I have also tried doing that: from files import t1 that's not working either. I am now wondering whether it is possible to import a file this way or I am missing something obvious here! -
Django/Celery task received but nothing happened
Im trying to update database object via celery task. without celery task im able to update the db object but when i add .delay() and send it to celery task ive got Task passenger.tasks.create_circle[3e60c0ee-6da7-4e7c-80c8-663b27b90762] received child process 116 calling self.run() child process 5952 calling self.run() and then nothing happened.I cant update the db object whatsoever. here is my settings.py BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' and here is the tasks.py @shared_task(bind=True) def create_circle(self, userid): print('celery working') radius = 500 user = Passenger.objects.get(id = userid) point = user.location point.transform(6347) poly = point.buffer(radius) poly.transform(4326) user.circle = poly user.save() any idea? -
535, b'Error: authentication failed when using os.environ to get the password
I'm trying to setup the password-reset route on Django, for not showing the account and the password directly in the code, I set them in the Mac environment, but keep getting the 535 error. its working if I write the password in the code, but getting error through "os.environ.get". EMAIL_HOST_USER = os.environ.get('DB_USER') EMAIL_HOST_PASSWORD = 'THESAMEPASSWORD'//this line works EMAIL_HOST_PASSWORD = os.environ.get('DB_PASS')//this line getting error DEFAULT_FROM_EMAIL = os.environ.get('DB_USER') -
Call django view in the background (every 15 seconds) until to get the customer details on form and then call auther view
I explain my problem to you i have two views function on django (check_flights and save_booking ) and i must Call check_flights successfully in two phases: 1st phase: Call check_flights every 2 or 3 seconds in the first 10 seconds of calling it, until i receive the parameters with the following values: - "flights_checked": true "price_change": false "flights_invalid": false 2nd phase: Once the flights are checked ("flights_checked: true"), continue calling check_flights in the background (every 15 seconds) until i get the customer details and then call save_booking. I need help from the 2nd phase thanks -
Distinguish which link-button clicked in django
I have that html code: <form id="my-form" method="POST" action="{% url 'my_view' %}"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <div class="md-form mb-1"> <textarea id="message" name="message" rows="2" class="form-control md-textarea"></textarea> </div> </div> <div class="col-md-6"> <div class="md-form mb-1"> <textarea id="message_then" name="message_then" rows="2" class="form-control md-textarea"></textarea> </div> </div> </div> <div class="text-center text-md-left"> <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name1">Click1</a> </div> <div class="text-center text-md-left"> <a class="btn btn-primary" onclick="document.getElementById('my-form').submit();" style="width: 78px;" name="name2">Click2</a> </div> </form> Now I would like to get to know which "button" was clicked. Unfortunately request.POST doesn't have that information. -
Why this form doesn't change the language of the website?
This is my language-switching form. {% get_current_language as lang_code %} {% get_available_languages as languages %} {% get_language_info_list for languages as langs %} <form action="{% url 'set_language' %}" method="POST"> {% csrf_token %} <select name="language" title="{% translate 'Language' %}"> {% for lang in langs %} <option value="{{ lang.code }}"{% if lang.code == lang_code %} selected{% endif %}> {{ lang.name_local }} ({{ lang.name_translated }}) </option> {% endfor %} </select> <input type="submit" value="OK" /> </form> I include this in the footer of my base template. Then, here is my courses/urls.py (app urls). from django.contrib import admin from django.urls import path from django.utils.translation import gettext_lazy as _ from . import views admin.site.site_header = _("FilFak administration") admin.site.site_title = _("FilFak admin") admin.site.index_title = _("Manage FilFak") urlpatterns=[ path("courses/", views.CourseList.as_view(), name="course_list"), path("professors/", views.ProfessorList.as_view(), name="professor_list"), path("exams/", views.ExamList.as_view(), name="exam_list"), path("courses/<slug:slug>", views.CourseDetails.as_view(), name="course_details"), path("professors/<slug:slug>", views.ProfessorDetails.as_view(), name="professor_details"), path("exams/<slug:slug>", views.ExamDetails.as_view(), name="exam_details"), path("", views.Index.as_view(), name="index"), ] And lastly filfak/urls.py (project urls.py). from django.contrib import admin from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.conf import settings from django.utils.translation import gettext_lazy as _ urlpatterns = [ path("admin/", admin.site.urls), path("lang/", include("django.conf.urls.i18n")), ] urlpatterns += i18n_patterns( path("", include("courses.urls")), prefix_default_language=False ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I click OK … -
Making readonly() field on modelform in Django 3.2.8
I'm trying to clon a form from a model and I want one specific field to be readonly but this field must POST the data to the DB as usual(it will initated with a pre-selected value).. All the SO questions that I've read were about old versions of Django and major part of them are mentioning about the leak with readonly(). So far I tried to implement idea's from old SO posts but I didn't succeed. Help please.. views.py class HairRequestFormView(FormView): template_name = 'request_templates/hair_request.html' form_class = HairRequest_form success_url='/thanks/' def form_valid(self, form): form.save() form.send_email() return super().form_valid(form) forms.py class HairRequest_form(forms.ModelForm): class Meta: model = Offline_User fields = "__all__" #pre-selected element block def __init__(self, *args, **kwargs): super(HairRequest_form, self).__init__(*args, **kwargs) self.fields['Request'].initial = Request(1) so I want that pre-selected field should be also readonly. Since readonly() func. will cause leaks is there any other approaches? Thanks -
Creating a multiplechoice field using many to many relationship
Im trying to add a field called, interested_fields inside my personalInfo model which users can choose from and the choices themselves come from another models' objects with the help of ManyToMany relation between the two models. Here are my models.py codes(I simplified my personal model by removing some other fields like name, age, etc in order to make it more readable for you): class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) interested_fields = models.ManyToManyField(Field, blank=True) then, I created a ModelForm like this: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] and created a get and post functions inside my views like this: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) and finally in template, inside the form I added this for loop: {% for field in fields %} <label class="containerq ant-col ant-col-md-6 ant-col-xs-8" > <span> <input type="checkbox" name="interested_fields" {% … -
Traverse multiple manytomany relationship, without iterating
class ModelA(models.Model): # ... class ModelB(models.Model): my_model_a = models.ManyToManyField(ModelA, blank=True) my_model_c = models.ManyToManyField(ModelC, blank=True) class ModelC(models.Model): # ... Suppose that I have an instance of ModelA in a variable myModelA. I would like to have a queryset with all ModelC instances associated to it, if any. def solution(myModelA): result = [] for model_b in myModelA.modelb_set.all(): result.append(model_b.my_model_c.all()) return set(result) This solves the problem, but requires iterations in Python. Is this doable solely with the ORM, without iterating in Python? -
Template Inheritance Does Not Work - Django Tutorial
I am following Corey Schafer' Django tutorial. I have reached where I have to create a base.html template inheritance. After adjusting everything according to my project and running the server, my webpage presents itself as a source code in html format. click to see the page after server run. My views.py code: from django.shortcuts import render from django.http import HttpResponse from django.template import loader # Create your views here. def index(request): text = "welcome to the website - python" posts = [ { 'title': 'The Fault in Our Stars', 'price': '3.0 BD', 'post_date': '24-10-2021' }, { 'title': 'The Black Swan', 'price': '3.5 BD', 'post_date': '23-10-2021' }, { 'title': 'Watchmen', 'price': '5.0 BD', 'post_date': '22-10-2021' } ] context = { 'text': text, 'posts': posts } return render(request, 'blog/index.html', context, {'title': 'Bookish Bahrain - Home'}) My base.html code: <!DOCTYPE html> <html lang="en"> <head> {% if title %} <title> {{ title }} </title> {% else %} <title> Bookish Bahrain </title> {% endif %} </head> <body> {% block content %}{% endblock %} </body> </html> My index.html code: {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <p> {{post.title}} </p> <p> {{post.price}} </p> <p> {{post.post_date}} </p> {% endfor %} {% … -
How to filter category wise product in Django using generic class view
I am making a POS system where there would be customers and each customer would have there own transactions. I can show all the transactions but having tough time figuring out how to filter transactions based on customer only. In models.py class Customer(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() address = models.CharField(max_length=200) number = models.IntegerField(null=True, blank=True) class AccountHolder(models.Model): customer = models.ForeignKey(Customer, on_delete=CASCADE) date = models.DateTimeField(default=timezone.now, auto_created=True) share_deposit = models.IntegerField(blank=True, null=True) share_return = models.IntegerField(blank=True, null=True) share_total = models.IntegerField(blank=True, null=True) I want to use generic classes in order do the filtration. Inside views.py class CustomerDetail(ListView): model = AccountHolder context_object_name = 'customers' template_name = 'customertransaction.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['customers'] = context['customers'].filter(customer=self.request.customer) -
Django: How to convert string and int into variable
I have declared a variable as" a1 = 10 Now in a function I need to call this variable by adding "a"+"1". However result is a1 in string and not above declared variable. Here is the code: a1 = 10 b = "a"+"1" print(b) a1 when I print b, answer is a1, instead of 10. How can I change this concatenate to declared variable? -
How to create test case with Factory boy? Django
I am trying to test my code using factory boy, but i am still getting errors like "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username " or "The row in table 'analytics_event' with primary key '1' has an invalid foreign key: analytics_event.created_by_id contains a value '7' that does not have a corresponding value in auth_user.id." my model: class Event(models.Model): name = models.CharField('the name of the event', max_length=255) created_at = models.DateTimeField(default=timezone.now, validators=[LessThanNowValidator()]) additional_data = models.CharField(max_length=300, blank=True, default='') created_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class CustomUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) api_token = models.CharField(max_length=100, blank=True, null=True, unique=True) def __str__(self): return f"{self.user.username}" I am trying to test with factory boy: class EventFactory(factory.django.DjangoModelFactory): class Meta: model = Event created_by = None class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: "User %d" % n) @factory.post_generation def user_related_models(obj, create, extracted, **kwargs): if not create: return EventFactory.create( created_by=obj ) john = UserFactory.create() class EventTestCase(TestCase): def test_post(self): self.assertEquals( Event.objects.count(), 0 ) Event.objects.create( name='event1', created_by=john ) self.assertEquals( Event.objects.count(), 1 ) -
Django how to output value list to html for 'for loop' in my case?
I want to know how I can ouput something like [value1, value2, value3] from Django, the Chart.js use data format like this. In my understanding, the counts_data=...aggregate(..., ..., ...) is a list similar to value list (value1, value2, value3), but then when I return, it must to be a dict, so I turn it context = {"counts_data", counts_data}, which is similar to {counts_data1: (value1, value2, value3), counts_data2:(value1, value, value3),...}, so I'm not sure how I can output data like [value1, value2,value3], I tried to put them into one queryset, but a queryset can only get or filter one status, I have 3 status, so I'm confused, it would be great if anyone could explain a little bit? Cheers views.py ''' def visualisation(request, project_id): project = Project.objects.get(id=project_id) counts_data = Todo.objects.aggregate( to_do_count=Count('id', filter=Q(status='to_do')), in_progress_count=Count('id', filter=Q(status='in_progress')), done_count=Count('id', filter=Q(status='done')) ) return render(request, 'todo_lists/progress.html', {"counts_data":counts_data}) ''' html ''' $(document).ready(function() { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'doughnut', data: { // labels format ['label1', 'label2', 'label3', ] // you can choose to have a static labels if you are sure that // there is always a specific number of labels labels: [{% for label in counts_data %} '{{ label }}', {% … -
Multiplying three models in django and getting the result in views
My model: class VisData(models.Model): visdata_id = models.AutoField(primary_key=True,blank=True) user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True) title = models.CharField(max_length=200, null=True,blank=True) buy_sell = models.CharField(max_length=1, null=True,blank=True) date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True) hour = models.TimeField(auto_now=False, auto_now_add=False,null=True,editable=True,blank=True) shares_number = models.DecimalField(decimal_places=0,default=0,max_digits=999,null=True,blank=True) course = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True) fare = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True) def __str__(self): return self.title and I want to assign: total_value = (shares_number * (course - fare)) and just print it in terminal my views: def summaryPage(request): visdata = VisData.objects.all() #print(visdata) context = {} return render(request, 'smth/homepage.html', context) I found some close answers but I couldn't understand the solution and use them in my code -
How to store only the desired values in Django View
I'm a student learning Django for the first time. I want to save only the values I want in Django's View, but I don't know what to do. Below are Models.py and Views.py, forms.py. I want to save it by entering only one without entering second_value and third_value in value_name. Please help me a lot. def product_upload(request): current_category = None categories = Category.objects.all() products = Product.objects.all() photos = Photo.objects.all() designated_object = Designated.objects.all() options = Option.objects.all() slug = Product.slug if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = Product() product.name = form.cleaned_data['name'] product.benefit = form.cleaned_data['benefit'] product.detail = form.cleaned_data['detail'] product.target_price = form.cleaned_data['target_price'] product.start_date = form.cleaned_data['start_date'] product.due_date = form.cleaned_data['due_date'] product.category_code = form.cleaned_data['category_code'] product.image = request.FILES['photo'] product.username = request.user product.slug = slug product.kakao_link = form.cleaned_data['kakao_link'] product.save() for img in request.FILES.getlist('image'): photo = Photo() photo.product_code = product photo.photo = img photo.save() if request.method == "POST": form = OptionForm(request.POST) if form.is_valid(): option = Option() option.name = form.cleaned_data['option_name'] option.product_code = product option.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['value_name'] value.option_code = option value.product_code = product value.extra_cost = form.cleaned_data['option_price'] value.save() if request.method == "POST": form = ValueForm(request.POST) if form.is_valid(): value = Value() value.name = form.cleaned_data['second_value'] value.option_code = …