Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to show amount in html page?
I have saved some random numbers in database and I am trying to fetch to show it in html page. but it is not showing me. I want to show each user their amount of money after they login. It is like a wallet where the amount will be saved for every user. I have saved that amount in database. views.py from decimal import Decimal def payment(request): total_amount = Payment.objects.all()['total_amount'] or Decimal('0.00') for field in total_amount: field.amount context = { 'total_amount': total_amount.amount } return render(request, 'index.html', context) models.py class Payment(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) HTML PAGE <li style="float: right;">Your Balance: Rs. {{total_amount}}</li> Images of database which contains content https://ibb.co/481nzqv https://ibb.co/B4M1NTk -
Adding an attribute to a django model, which did not exist previously
I created Django model for my application. It had some attributes, such as title, description, etc. Then I wanted to add 'slug' of the title, so from My Project it shall be my-project. But my already created model instances do not have these attributes. I tried just basically adding the attribute as, but it created something like: djangodbmodelsfieldscharfield. I also tried doing it with saving, but it only created this attribute to the newly added model instances class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() # create p1 class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() slug = slugify(title) # create p2 # p1.slug, p2.slug -> 'djangodbmodelsfieldscharfield' class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() def save(self, *args, **kwargs): if not self.id: # Only set the slug when the object is created. self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs) # create p3 # p1.slug, p2.slug -> AttributeError # p3.slug -> my-title-in-desired-form So my goal would be to create this attribute to every instance in the database. Is it possible, or how should I approach this problem? -
Use variable as dict key in django templates
I have two dict with the same keys. I use one dict to build table but I don't know how to get access to other dict. Example {% for key1, item1 for dict1.items %} {% for key2, item2 for item1.items %} <p>{{ item2.value }}</p> <p>there should be value from dict2</p> {% endfor %} {% endfor %} In python I can use dict2[key1][key2]["value"] but how do this with template? -
How to display two not associated models on one page via admin interface?
I have two models, not connected by ForeignKey. I would to display them on one page in admin interface, in the way like inlines in Django. I can't associate PostFile with Post, because uploaded medias should be available to every Post which was and will be created in future. I have no idea what I can do if inlines are unavailable. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique_for_date='publish_date', blank=True) author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE, blank=True) content = MarkdownxField() publish_date = models.DateTimeField(default=timezone.now) creation_date = models.DateTimeField(auto_now_add=True) last_update_date = models.DateField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') tags = models.ManyToManyField(Tag) objects = models.Manager() class Meta: ordering = [ '-publish_date' ] def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('blog:post_detail', args=[ self.publish_date.strftime('%Y'), self.publish_date.strftime('%m'), self.publish_date.strftime('%d'), self.slug ]) #https://github.com/neutronX/django-markdownx/issues/83 def formatted_markdown(self): return markdownify(self.content) class PostFile(models.Model): file_name = models.CharField(max_length=200, blank=True) file_object = models.FileField(upload_to='post_files/') file_upload_date = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.file_name: self.file_name = self.file_object.name super(PostFile, self).save(*args, **kwargs) def file_url(self): return self.file_object.url def __str__(self): return self.file_name I would to receive in output a Post model admin page, where on the bottom I have listed all PostFile … -
Where is django TEMPLATES
I need to find Django TEMPLATES location to add in a line under 'context_processors' om 'OPTIONS' I researched and found this which looks to be my problem solver, however I am unable to find the location of the document where I am supposed to input the details specified: django.core.exceptions.ImproperlyConfigured: Enable 'django.contrib.auth.context_processors.auth' The project only relies on Django as a plugin so I am in no means experienced with setting up Django. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ "django.contrib.auth.context_processors.auth", ] } } ] I can not find the 'TEMPLATES' document. -
KeyError at admin/users/myuser/ Error during template rendering
I can not view or edit users in Admin because of getting the next error. Another links and models in Admin are working fine. Link /admin/users/myuser/ works before I switched the database from SQLite to MySQL. But I do not know if the problem is with this or something else. KeyError at /admin/users/myuser/ Request Method: GET Request URL: http://127.0.0.1:8000/admin/users/myuser/ Django Version: 2.2.4 Exception Type: KeyError Exception Value: '0' Exception Location: C:\my_project\venv\lib\site-packages\django\contrib\admin\templatetags\admin_list.py in _boolean_icon, line 195 Python Version: 3.7.0 Error during template rendering In template C:\my_project\venv\lib\site-packages\django\contrib\admin\templates\admin\base.html, error at line 62 52 {% endblock %} 53 </div> 54 {% endif %} 55 {% endblock %} 56 {% block nav-global %}{% endblock %} 57 </div> 58 <!-- END Header --> 59 {% block breadcrumbs %} 60 <div class="breadcrumbs"> 61 <a href="{% url 'admin:index' %}">{% trans 'Home' %}</a> 62 {% if title %} &rsaquo; {{ title }}{% endif %} 63 </div> 64 {% endblock %} 65 {% endif %} 66 67 {% block messages %} 68 {% if messages %} 69 <ul class="messagelist">{% for message in messages %} 70 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message|capfirst }}</li> 71 {% endfor %}</ul> 72 {% endif %} I totally do not understand where … -
How to fix 'Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 21221: character maps to' error?
I'm trying to import a csv file to my django project. Until now, the previous times I did this i never had a problem. However, all of a sudden I keep getting this error that says "Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x9d in position 21221: character maps to" when i try to import the csv file in. I don't understand why I am getting the error this is what i keep getting. I am trying to import my excel file like this: and this is what my csv file looks like: -
unable to install django==1.8 with *fab setup_all*
i am trying to install all the packages with fab like 'fab setup_all' in unix 16.x. Except one django==1.8.19 root@bridge-All-Series:/home/bridge/ticketing/docker# fab setup_all Installing worker requirements... pip_compile_and_sync worker /var/www/ticketflap/apps/worker/requirements.txt [localhost] local: docker run --rm --volume $(pwd)/../logs:/var/log/ticketflap/ --volume $(pwd)/../logs/celery:/var/log/celery/ --volume $(pwd)/..:/var/www/ticketflap --volume $(pwd)/worker/supervisord.conf:/etc/supervisor/conf.d/supervisord.conf:ro --volume ticketflap-worker-virtualenv:/virtualenv --env DONT_SWITCH_USER=1 --network=ticketflap-dev --network-alias=worker.dev.ticketflap.net --interactive --tty ticketflap-worker /var/www/ticketflap/docker/base/_run.sh pip-compile --output-file /var/www/ticketflap/apps/worker/requirements.txt.compiled /var/www/ticketflap/apps/worker/requirements.txt No handlers could be found for logger "pip._vendor.cachecontrol.controller" Could not find a version that matches django==1.8.19,>=1.11,>=1.2,>=1.3,>=1.4,>=1.4.2,>=1.6,>=1.7,>=1.8 Tried: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.5.12, 1.6, 1.6, 1.6.1, 1.6.1, 1.6.2, 1.6.2, 1.6.3, 1.6.3, 1.6.4, 1.6.4, 1.6.5, 1.6.5, 1.6.6, 1.6.6, 1.6.7, 1.6.7, 1.6.8, 1.6.8, 1.6.9, 1.6.9, 1.6.10, 1.6.10, 1.6.11, 1.6.11, 1.7, 1.7, 1.7.1, 1.7.1, 1.7.2, 1.7.2, 1.7.3, 1.7.3, 1.7.4, 1.7.4, 1.7.5, 1.7.5, 1.7.6, 1.7.6, 1.7.7, 1.7.7, 1.7.8, 1.7.8, 1.7.9, 1.7.9, 1.7.10, 1.7.10, 1.7.11, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8, 1.8.1, 1.8.1, 1.8.2, 1.8.2, 1.8.3, 1.8.3, 1.8.4, 1.8.4, 1.8.5, 1.8.5, 1.8.6, 1.8.6, 1.8.7, 1.8.7, 1.8.8, 1.8.8, 1.8.9, … -
Celery can't connect to local PostgreSQL from within Docker container
I have a Django-Celery-PostgreSQL project that should partially run in Docker. Having Redis and PostgreSQL servers running locally on the machine and using virtual environment for the project everything runs smoothly. But when I try to setup Docker instance Celery seems unable to connect to the Postgres database while Django can. When running project in Docker I put only Django and Celery in it and set network_mode: "host". Redis and Postgres remains on the local machine. Django server itself works flawlessly reading and writing data into the Postgres database, but when I try to run Celery tasks - I get following exception (thrown by django_celery_results): [2019-08-13 11:26:24,815: ERROR/MainProcess] Pool callback raised exception: OperationalError('could not connect to server: No such file or directory\n\tIs the server running locally and accepting\n\tconnections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?\n',) Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The above … -
Is there any way to run a certain function at a certain time?
I am now making a website where teachers announce assignments and students submit them. I made boards that they can post their announcements or submission but do not know how to check those who did not submit their homework. I want some functions that run automatically at the designated time (in this case, on the due date of the assignment, the function judges and gathers who did not get their homework done) I looked for some libraries related to datetime but have no idea. assignments/models.py class Assignment(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) index_in_group = models.IntegerField() title = models.CharField(max_length=30, verbose_name='name') content = models.TextField(verbose_name=content') due_date = models.DateTimeField(verbose_name='due') created_at = models.DateTimeField(auto_now_add=True) class Done(models.Model): assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE) index_in_assignment = models.IntegerField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) done_img = models.ImageField(upload_to='AssignmentsDone') injung = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) The function would be like this: (not the exact one - just memo) def check_submission(request, assignment_id): members = Members of the group (I will retrieve this thoroughly when actually code) submissions = Done.objects.filter(assignment.id = assignment_id) did_hw = [x.author for x in submissions] for member in members: if member not in did_hw: mark as unsubmitter This post got too long.. but the question is actually so simple. I just wanna know if … -
Why unique field can't migrate?
First I create a table, but no serial(a unique field).Then I added the serial field to the table. When I make migrate, I have deleted all information in table.And the serial field failed to migrate. delete validators. delete all migrations files. serial = models.CharField(unique=True, max_length=12, validators=[RegexValidator(regex=r'^\d{12}$', message='...', code='questionnaire'), ], verbose_name='questionnaire_serial', help_text='questionnaire_serial') When I use mysql, the table has no the serial field. But I drop the table, then success. -
Django: Difference between cached session vs simple cache?
I have a Django application using Redis as a cached session backend (not persistent). If I am say storing only one value in a user's session, is there any storage difference between say - request.session['value'] = value and cache.set(user_identifier, value) apart from timeout/logout? Is there any con in using only cache with keys related to user_identifier vs storing values in user's session? -
How to run two methods inside django models in parallel manner?
I'm incrementing two different fields in User models which are the number of likes given to user's post and number of likes received by the user's post. I did this through adding two methods in class model. It is working when I'm liking other posts but however, if I liked my own post it is not working. Anyone know how to solve this problem? Code snippet for user models class User(models.Model): username = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) datetime_joined = models.DateTimeField(auto_now_add=True) num_likes_received = models.IntegerField(default=0) num_dislikes_received = models.IntegerField(default=0) num_likes_given = models.IntegerField(default=0) num_dislikes_given = models.IntegerField(default=0) total_votes = models.IntegerField(default=0) prediction = models.BooleanField(default=True) def add_total_votes(self, vote): self.total_votes += vote self.save() def inc_num_likes_received(self): self.num_likes_received += 1 print("1 like received") self.save() def inc_num_likes_given(self): self.num_likes_given += 1 print("1 like given") self.save() Function for submitting like to certain post and at the same time this is where I executed the created two method from the models. (inc_num_likes_received and inc_num_likes_given) def submit_like(request): User_PK = User.objects.get(username=request.user) User_Give_Like = get_object_or_404(User, pk=User_PK.id) pk = request.POST.get('Status', None) post = get_object_or_404(Post, pk=pk) post.add_num_likes() User_PK_Receive = User.objects.get(id=post.username.id) User_Receive_Like = get_object_or_404(User, pk=User_PK_Receive.id) LikeObject = Likes(username = User_Give_Like, post = post, liked=True, disliked=False) LikeObject.save() User_Give_Like.inc_num_likes_given() User_Receive_Like.inc_num_likes_received() return HttpResponse(200) … -
Implementing filters using dictionary packaging
I am trying to optimize my filter code using dictionary packaging, bt i am getting the following error: filter_queryset() missing 3 required positional arguments: 'industry', 'instructor', and 'mediaType' views.py class CourseList(generics.ListCreateAPIView): serializer_class = CourseSerializer def get_queryset(self): queryset = Course.objects.all() if(self.request.query_params): queryParams = self.request.query_params filterParams= queryParams.dict() queryset = self.filter_queryset(queryset, **filterParams) # if(queryParams.get('industry', None)): # queryset = queryset.filter(industry=queryParams.get('industry', None)) # if(queryParams.get('instructor', None)): # queryset = queryset.filter(instructor=queryParams.get('instructor', None)) # if(queryParams.get('mediaType', None)): # queryset = queryset.filter(course_media__media_type=queryParams.get('mediaType', None)) return queryset def filter_queryset(self, queryset, industry, instructor, mediaType): queryset.filter(industry=industry).filter(instructor=instructor).filter(course_media__media_type=mediaType) return queryset url: http://127.0.0.1:8000/authenticator/course/?industry=IT&instructor=5&mediaType=mp4 What am i missing here, bcoz when i debug into the filter_queryset method i can see that all the the three filter values are being populated well -
How to update status on sub section of django template
I have django app where user need to select some options, based on selected options there is flow broadly includes 3 steps including running some exe, comparing and finally we render a page with result table. I need to update the status of each stage completed on django template /frontend view till we complete all stages and print result table. Execution of above steps happen of submit button and currently till we have final results it stays on same page. -
celery error in connection with postgresql while django can
i used celery in my django project .django can connect with postgresql well but it's seem that celery can't connect to postgresql : Traceback (most recent call last): File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/classgram/www/env/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/home/classgram/www/env/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: FATAL: password authentication failed for user "hamclassy" FATAL: password authentication failed for user "hamclassy" i'm working on host now and host OS is Ubuntu 18.04 . thank you -
Reverse for 'index' not found. 'index' is not a valid view function or pattern name. PasswordChangeView and PasswordChangeForm
I am trying to implement a functionality of changing the password of the current user in Django . But no matter what I use, I always get this everse for 'index' not found. 'index' is not a valid view function or pattern name error and a Template showing these lines of codes. Error during template rendering In template /home/squad-minds/PycharmProjects/squad-services/Admin_interface/venv/lib/python3.7/site-packages/django/contrib/admin/templates/admin/base.html, error at line 3 1 {% load i18n static %}<!DOCTYPE html> 2 {% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %} 3 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}> 4 <head> where }" {% if LANGUAGE_BIDI is in Red Colour. I have implemented this using the CBV from django.contrib.auth.views import PasswordChangeView from django.contrib.auth.forms import PasswordChangeForm class PasswordChange(UserPassesTestMixin, PasswordChangeView): form_class = PasswordChangeForm success_url = '/' def test_func(self): return self.request.user.is_superuser path('password/change', views.PasswordChange.as_view(), name='change_password'), What is this Index thing and why am I getting this? -
How to add value in db django?
I'm writing a new application,where in standart Djangos table auth_user i need to add new value in column. I would like to ask how i can make it? views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] money = 0 user = authenticate(username=username, password=password,money=money) login(request, user) return redirect('index') else: form = UserCreationForm() context = {'form' : form} return render(request, 'registration/register.html',context) for example here i woulf like to add 5 in new column money of table auth_user -
How to add object level permission in django admin
I have a Building model and in that i have a field notes which has GenericRelation to GeneralNote. In Building admin added GeneralNotes as Inlines. Now I want that the GeneralNotes is editable for the user who is owner of general note. class Building(TimeStampedModel): name = models.CharField( unique=True, max_length=100, verbose_name=_("Building Name"), help_text=_("This is the name of your building") ) notes = GenericRelation(GeneralNote) class GeneralNote(TimeStampedModel): owner = models.ForeignKey( CompanyEmployee, blank=True, null=True, # related_name='noteOwner', on_delete=models.SET_NULL, verbose_name="Note Owner", ) content = models.TextField(max_length=400, null=True ) date_of_action = models.DateField(null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() attached_to = GenericForeignKey() In admin.py class BuildingAdmin(ImportMixin, GeneralNotesIncludedAdmin): inlines = (GeneralNoteInLine,) class GeneralNotesIncludedAdmin(CoreBaseAdmin): def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: if not instance.owner: instance.owner = request.user.companyemployee instance.save() super().save_formset(request, form, formset, change) class CoreBaseAdmin(admin.ModelAdmin): save_on_top = True -
How to call a class based generic API view from a custom function based view
I am having some problems and doubts about how to call my own API within my app. So I have an API to which I can send data. What I want to do in a different view is calling this sent data so I can visualize it in a template. First I was trying to call the API with the library requests inside of my view. Even though that works I am having problems with authentication. So I was thinking I could call my class based API view from my custom function based view. But I don't know if that is possible, nor do I know if that is recommendable. I was also thinking that it might be better to do that with javascript? I don't know.... So my question is twofold: a) What is the best practice to call an API view/get API data from my own app so that I can manipulate and visualize it b) If this is good practice, how can I call my class based generic API view from my custom function based view? Here is what I am trying so far: my generic view class BuildingGroupRetrieveAPIView(RetrieveAPIView): """Retrieve detail view API. Display all information on … -
can i start to learn flask or Django after python learnt python basics?
I learnt python basics but still, I can't solve problems and exercises which r given in tutorials. I want to make a website. so is it ok to start to learn flask or Django after knowing some basic of python? -
error when rendering through get_object_or_404 django
The following code in my views.py throws an error if I don't use "else" conditional statement specifying "detail = None" Is there any better way to simplify the code without using "else" statement? (just in case you don't understand the structure of my app, it only has detail, and list templates. list.html only shows the list of name record in model, and detail only shows the each name in detail page.) def SimpleView(request, sluggy=None): s = Simple.objects.all() if sluggy: detail = get_object_or_404(Simple, slug=sluggy) else: detail=None return render(request,'simple_app/list.html',{'s':s,'d':detail}) def detaily(request,sluggy): sluggys = get_object_or_404(Simple,slug=sluggy) return render(request, 'simple_app/detail.html',{'sluggy':sluggys}) -
Python: How to pass command-line arg as string instead of tuple?
In my Django site, I'm writing a management command to generate sample data in fixtures for all models, or the specified model. The first (and only) positional arg should specify the app.model to process, or "all" to do all models. The problem I'm having is that the arg is a tuple, and when I print it, it shows individual characters as each element of the tuple. Here's my code (as far as showing the arg): def add_arguments(self, parser): parser.add_argument( 'args', type=str, metavar='app.model', nargs='?', default='all', help='Model in the form: app.model (example: clients.client)') def handle(self, *args, **kwargs): self.model = args print('args-type:', type(args)) print('model-type:', type(self.model)) print('model:', self.model) Note that I've specified type=str as an add_argument option. When I try this command line: docker-compose exec api python manage.py gen_fixtures ...I get this output: args-type: <class 'tuple'> model-type: <class 'tuple'> model: ('a', 'l', 'l') It's the same if I specify "all" on the command line. And if I try this one: docker-compose exec api python manage.py gen_fixtures clients.client ...I get this output: args-type: <class 'tuple'> model-type: <class 'tuple'> model: ('c', 'l', 'i', 'e', 'n', 't', 's', '.', 'c', 'l', 'i', 'e', 'n', 't') I know that if I'm initializing a tuple in my code with … -
How to show balance to user in html page which is saved in database?
I have given balance to each user who have signed up and saved that balance in database but I am not able to show them in html page. Maybe I have made some mistakes in python files also. In views.py I have commented some code values which I used also but still didn't get the results. How to do it? models.py class Payment(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) views.py from django.db.models import Sum from decimal import Decimal def payment(request): total_amount = Payment.objects.filter( owner=request.user) # ).aggregate( # total_amount=Sum('amount') # )['total_amount'] or Decimal('0.00') for field in total_amount: field.amount context = { 'total_amount': total_amount } return render(request, 'index.html', context) HTML page <li style="float: right;">Your Balance: Rs. {{total_amount}}</li> Python Shell >>> from users.models import Payment >>> Payment.objects.all() <QuerySet [<Payment: Payment object (1)>, <Payment: Payment object (2)>]> Images of database which contains content https://ibb.co/481nzqv https://ibb.co/B4M1NTk -
how to insert multiple record in Django admin model
I want to insert multiple records of student marks but, Django provides by default one by one student insert marks. class ODE_Registation_Model(models.Model): student = models.ForeignKey(User,on_delete=models.CASCADE) subject = models.ForeignKey(SubjectMaster,on_delete=models.CASCADE) ode = models.ForeignKey(ODE_List_Model,on_delete = models.CASCADE,verbose_name="which ode") exam_date = models.DateField() registration_date = models.DateField() def __str__(self): return self.student.username class ODE_Marks_Model(models.Model): ode_registered = models.OneToOneField(ODE_Registation_Model,on_delete=models.CASCADE) marks = models.SmallIntegerField() verified_by = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return str(self.marks) my expectation: display all student name and marks(as input field) which are a register in "ODE_Registation_Model" ie:- student marks stu1 [input type=number] stu2 [input type=number] stu3 [input type=number] ... ...