Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to avoid raw SQL query with multiple JOINs?
Is there any way how to make complex SQL selects in Django methods? With multiple JOINs cross multiple tables with different relations. I've tried many attempts with select_related method, but haven't figured out that. Simply - I need ListView for model Objekt filtered by model User. Database looks like this - https://dbdiagram.io/d/61d699903205b45b73d92750/ I think that these kind of queries has to be done much simpler way. Query set for ListView def get_queryset(self): return Objekt.objects.raw('''SELECT portal_objekt.id AS id, portal_objekt.cislo_objektu AS cislo_objektu, portal_objekt.mesto AS objekt_mesto, portal_objekt.ulice AS objekt_ulice, portal_objekt.c_popisne AS objekt_c_popisne, portal_objekt.c_orientacni AS objekt_c_orientacni, portal_objekt.psc AS objekt_psc, CASE WHEN portal_mereni.komodita = 'e' THEN 'elektřina' WHEN portal_mereni.komodita = 'p' THEN 'plyn' WHEN portal_mereni.komodita = 'v' THEN 'voda' WHEN portal_mereni.komodita = 't' THEN 'teplo' ELSE 'ostatní' END AS mereni_komodita FROM portal_objekt INNER JOIN portal_sluzbakesmlouve ON portal_sluzbakesmlouve.objekt_id = portal_objekt.id INNER JOIN portal_smlouva ON portal_sluzbakesmlouve.smlouva_id = portal_smlouva.id INNER JOIN portal_uzivatelkesmlouve ON portal_uzivatelkesmlouve.smlouva_id = portal_smlouva.id INNER JOIN portal_user ON portal_uzivatelkesmlouve.uzivatel_id = portal_user.id INNER JOIN portal_mereni ON portal_mereni.objekt_id = portal_objekt.id WHERE portal_user.email = %s AND portal_sluzbakesmlouve.platnost_od < CURRENT_DATE AND ( portal_sluzbakesmlouve.platnost_do > CURRENT_DATE OR portal_sluzbakesmlouve.platnost_do IS NULL ) ORDER BY portal_objekt.cislo_objektu''', [ self.request.user.email ] ) -
Executing only one row in the loop
I'm trying to execute all the rows in the payload through loop but after executing the first row I'm getting an 'str' object has no attribute 'get' like wise its happening for all the remaining rows in the API. payload: [ 0: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 1, Answer: "2", SID: "0",…} 1: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 2, Answer: "2", SID: "0",…} 2: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 3, Answer: "2", SID: "0",…} 3: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 4, Answer: "2", SID: "0",…} 4: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 5, Answer: "5", SID: "0",…} 5: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 6, Answer: "5", SID: "0",…} 6: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 7, Answer: "3", SID: "0",…} 7: {AuditorId: 122, Agents: "", Supervisor: "", TicketId: "12111", QId: 8, Answer: "3", SID: "0",…} ] Here, I get the random number such as 8938 for the first row and remaining rows I should get as 0 views.py @api_view(['POST']) def SaveUserResponse(request): if request.method == 'POST': for ran in request.data: auditorid =ran.get('AuditorId') print('SaveUserResponse auditorid---', auditorid) … -
JavaScript how to set JWT for <img> resource
At my Django application, I want to display an image from an external web server. This web server only returns the image if an authorization token (JWT) is set in the request header. At my Django template, I currently do: <img src="{{ blabla.cover_url }}"> Where cover_url currently is only a string like "https://test.mydomain.com/test/OUINBWU.jpg" As I cannot send a whole HttpResponse object that includes the JWT using Django I need to use Javascript here to instruct my browser to load the <img> with a JWT in the request header. Assuming I have passed a valid JWT and the link to my template, how does the JavaScript code have to look like in order to request the img with the JWT set at the header? Total JS newbie here Thanks in advance -
How to add ID or class with every option in ChoiceField - forms.py Django
currently I make a tuple for options and passed the two arguments value and label like TAG_OPTION = ( ('', 'Choose Tagging'), ("Option A","Option A"), ("Option B","Option B"), ("Option C","Option C"), ("Option D","Option D"), ("Option AB","Option AB"), ("Option BA","Option BA") ) and then passed the TAG_OPTION to the choices of ChoiceField like tagging_type = forms.ChoiceField(choices=TAG_OPTION,widget=forms.Select(attrs={'id':'tagging_type'})) However, what output I want is, <select name="tagging_type" id="tagging_type"> <option value="">Choose Tagging</option> <option id="optA" value="Option A">Option A</option> <option id="optA" value="Option B">Option B</option> <option id="optA" value="Option C">Option C</option> <option id="optA" value="Option D">Option A</option> <option id="optB" value="Option AB">Option AB</option> <option id="optB" value="Option BA">Option BA</option> </select> Can anyone help me out to know the easy way to achieve this ? -
ValueError at /Insert The view CRUDOperation.views.Insertemp didn't return an HttpResponse object. It returned None instead
from django.shortcuts import render from CRUDOperation.models import EmpModel from django.contrib import messages def showemp(request): showall = EmpModel.objects.all() return render(request,'Index.html',{"data":showall}) def Insertemp(request): if request.method == 'POST': if request.POST.get('firstname') and request.POST.get('middlename') and request.POST.get('lastname') and request.POST.get('department') and request.POST.get('designation') and request.POST.get('location') and request.POST.get('salary') and request.POST.get('status') and request.POST.get('gender'): saverecord=EmpModel() saverecord.firstname=request.POST.get('firstname') saverecord.middlename=request.POST.get('middlename') saverecord.lastname=request.POST.get('lastname') saverecord.department=request.POST.get('designation') saverecord.designation=request.POST.get('designation') saverecord.location=request.POST.get('location') saverecord.status=request.POST.get('status') saverecord.salary=request.POST.get('salary') saverecord.gender=request.POST.get('gender') saverecord.save() messages.success(request,'Employee'+saverecord.firstname+'is saved successfully! :)') return render(request,'Insert.html') else: return render(request,'Insert.html') above is the code where the problem MIGHT be there,can someone point out what error is there? what problem could be there in the code? -
django-pgcrypto-fields taking long time to load
I'm using django 2.2.13 and django-pgcrypto-fields 2.5.2. Also i'm using email as authentication method. email is stored as pgcrypto field. There are around 10000 active users. When user tries to login it takes a long time (8-9 seconds). I tried to login from shell, it also takes a long time. from django.contrib.auth import authenticate user = authenticate(email='john@gmail.com', password='secret') The authenticate function takes almost 7-8 seconds to execute. user = authenticate(username='john', password='secret') When I try to authenticate using username, it executes within 1 seconds from app.models import User user = User.objects.filter(email=email).first() The above query also takes a long time to execute (7-8 seconds). How can I speed up authentication and filter queries for pgcrypto fields? -
how to export only filtered data to excel in django
this is my view but in this only return_type = 'time_slot"is working elif return_type= 'export is not working ' my intention is to export excel with filtered data so I came up with this. thanks in advance class TimeSlotReportView(AdminOnlyMixin, generic.DetailView): template_name = 'reports/time_slot_report.html' def get(self, request, *args, **kwargs): if request.is_ajax(): zone_val = request.GET.getlist('zone_val[]') slot_val = request.GET.getlist('slot_val[]') date_val = request.GET.get('date_val') return_type = request.GET.get('return_type') slots = [] if return_type == 'time_slot': for t in slot_val: slots.append(parse(t)) slot_len = len(slot_val) + 1 slot_size = len(slot_val) zones = Zone.objects.filter(id__in=zone_val) daily_tasks = DailyTask.objects.filter(date=date_val, zone__id__in=zone_val, slot__start_time__time__in=slots) total_used = 0 total_unused = 0 total = 0 for task in daily_tasks: total_used += task.used_tasks total_unused += task.unused_tasks total += task.total_tasks # print(total_used, '/', total_unused, '/', total) context = { 'daily_tasks': daily_tasks, 'zones': zones, 'slot_len': slot_len, 'slot_size': range(slot_size), 'task_used': total_used, 'task_unused': total_unused, 'task_all': total } html = render_to_string('reports/time_slot_filter.html', context, request) return JsonResponse({'html': html}) elif return_type == 'export_excel': def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename=Timeslot Report' + \ str(datetime.datetime.now()) + '.xls' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Time Slot Report') row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Zones', 'Coordinates'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = Zone.objects.all().values_list('name', 'coordinates') for … -
Python Django Filter assist for filter[last_login][gte]
I have DjangoFilterBackend for filtering with respective JSON API Specs. Here is my filter class below. The problem with this is it works for /api/user?filter[last_login__gte]=2022-06-24T11:00:00Z How can I modify to make it /api/user?filter[last_login][gte]=2022-06-24T11:00:00Z class UserFilter(django_filters.FilterSet): id = django_filters.CharFilter(field_name="external_id") class Meta: model = User fields = { "id": ["exact", "in"], "email": ["exact", "in"], "first_name": ["exact", "in"], "last_name": ["exact", "in"], "is_active": ["exact"], "last_login": ["isnull", "exact", "lte", "gte", "gt", "lt"], } filter_overrides = { models.DateTimeField: {"filter_class": django_filters.IsoDateTimeFilter} } -
How to merge colms in python dictionary where particular fields are same?
I have list of dictionaries as u can see below: [{ 'name': 'First Filter', 'nut': '122222', 'cpv': '111' }, { 'name': 'First Filter', 'nut': '122222', 'cpv': '123' }, { 'name': 'First Filter', 'nut': '123-41', 'cpv': '111' }, { 'name': 'First Filter', 'nut': '123-41', 'cpv': '123' } ] I want results like this: ''' { 'name': 'First Filter', 'nut': ['122222', '123-41'], 'cpv': ['111', '123'] } ] ''' Please help me, i tried to do this by pandas dataframe but couldn't get it! -
Implementing SAML SSO session expiry on navigating back and forth between our system domains and external domains
My system uses django framework with MongoDB and reactJS. I have implemented SSO with the opensource python toolkit provided by OneLogin (https://pypi.org/project/python3-saml/) Suppose we have a known set of our system domains (www.app1.com, www.app2.com). Am trying to implement session expiry when a user logs in with SSO in either of our known domains and navigates out to an external domain(like youtube etc.). As long as the user switches between our known set of domains the existing session need not be invalidated. I have currently integrated with Azure active directory as the Identity Provider(IDP). When i login with SSO it redirects me to microsoft login and after successful login am redirected back to my backend server where i store the SAML token and redirect back to the frontend application domain. The session data is getting stored under the microsoft domain in the browser and hence i have no access to that session data to clear it from the frontend when the user is navigating out of my domain. And it doens't matter even if i delete the session data stored in my backend server since it is still present in the browser. It just takes that session from browser and sends … -
How to customise the default error message for empty username on login
login credentials : { "account_id":"", "password":"abdu@123" } response : { "account_id": [ "This field may not be blank." ] } This error comes from rest_framework.fields.CharField. I tried to override it by doing : class MyField(CharField): default_error_messages = { 'invalid': _('Not a valid string.'), 'blank': _('This field may not be blank changed......'), 'max_length': _('Ensure this field has no more than {max_length} characters.'), 'min_length': _('Ensure this field has at least {min_length} characters.'), } This doesn't change the error message. -
How to filter the database through dropdown with the help of ajax?
Thank you for your help. I have a template that takes a value from the user via dropdown, then this value is sent to the server via ajax. I want to filter the database data based on this value. But after filtering, the queryset value in the template is empty. Why is the queryset empty? my template: my ajax code views code: Filter data based on data received from the user via ajax Where filtered data should be displayed: enter image description here What is currently displayed: There is no data -
How to disable ALLOWED_HOST check on paticular Django REST API URL?
IS there any way to disable DJANGO ALLOWED_HOST check on particular API URL, We want to allow API requests from list of websites(HOSTS), but there is RFID reader machine which will also be writing data on our DJANGO server using REST API and we want to make only that particular REST API URL public and other REST APIs should be allowed as ALLOWED_HOST check of DJANGO. -
Models relationship and mapping of models
I have a Warehouse model and an Item Model, simplified to - class Warehouse(models.Model): warehouseCode = models.CharField(max_length=30) class Item(models.Model): itemCode = models.CharField(max_length=30) and a third model to map the relationship as whether an item can be stored in a warehouse or not. (locked is the field) class ItemWarehouse(models.Model): item = models.ForeignKey(ItemMaster) warehouse = models.ForeignKey(Warehouse) locked = models.BooleanField(default=False) The system is designed such that before creating any item at least we should have one warehouse. Now suppose we have 2 warehouses (warehouse_1 and warehouse_2) and we created the First item. As mentioned above warehouse_1 can have the item First and warehouse_2 is locked for item First (No transaction of item First can be done in warehouse_2). The question is after creating 500 such items (n numbers of items), we created 1 more warehouse called warehouse_3. What should be the optimized or best way to map the relationship of the newly created warehouse with all the previously created items. Thinking in mind of system design and UI design. I'm using the rest framework and frontend client. Or a better complete design than what I have till now. -
How to define ManyToManyField in Django for tests
To test my serializers in django rest framework I use Model Name.objects.create method to create fields. But I can't create ManyToManyField. Guess, firstly I need to create objects for first model and for second model otherwise ManyToManyField bound can't be created. But still can't define ManyToManyField for test with create method. Please help me to realize how it should work correctly. I've red django documentation, but haven't got how to solve my issue. Here is my code example: models.py class Book(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=7, decimal_places=2) author_name = models.CharField(max_length=200) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='my_books') readers = models.ManyToManyField(User, through='UserBookRelation', related_name='books') test.py class BookSerializerTestCase(TestCase): def setUp(self): self.user = User.objects.create(username='test_username') self.book_1 = Book.objects.create(name='Test book 1', price=750, author_name='Author 1', owner=self.user) self.book_2 = Book.objects.create(name='Test book 2', price=650, author_name='Author 1', owner=self.user) def test_readers(self): users = [self.user] reader = self.book_1.readers.set(users) print(f'Readers: {reader}') readers is None, how to define self.user? Thank you in advance. -
"get()" Record from Django SQLite3 DB AFTER Encryption with django_cryptography
I have created a Django application, where I ask the visitor of the site to input their name into a form. Upon POST submission, it stores their name, and the IP address they are visiting from into an SQLite3 database. For practise, I encrypt the IP address before storing it in the db. If the user "returns" to the site, my code is set to find a record for that user in the db first, based on their IP address. If there's already a record in the db with that IP, it'll display a "welcome back" message. If I don't encrypt the IP, my app works fine, but when I attempt to use django_cryptography I get stuck. What I have so far is: models.py from django.db import models from django import forms from django_cryptography.fields import encrypt INT_MAX_NAME_STRING_LENGTH = 100 # Previous visitors object class Previous_Visitor_Model(models.Model): visitor_name = models.CharField(max_length=INT_MAX_NAME_STRING_LENGTH) visitor_ip = encrypt(models.CharField(max_length=16)) # IP_Address_Field() # The name form on the initial page class NameForm(forms.Form): visitor_name = forms.CharField(label='Your (company) name', max_length=INT_MAX_NAME_STRING_LENGTH) So I encrypt their IP address in the model. When a visitor enters their name into the form and submits, a new record is created in the db, with their name, … -
Django log out view doesn't work (no network traffic)
I'm learning Django to build the back end for my website. I'm making an authentication app for the project. I'm testing it using a separate html file instead of template since I want to eventually connect it with my front end. The log in view works fine but the log out one doesn't. It prints to the server terminal what looks like a success message: "POST /members/logout_user/ HTTP/1.1" 200 10 but it doesn't do anything in the browser. There is no network traffic. Views: from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.http import HttpResponse from rest_framework.decorators import api_view @api_view(['POST']) def login_user(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponse("Logged in") else: return HttpResponse("incorrect") @api_view(['POST']) def logout_user(request): logout(request) return HttpResponse("logged out") My html client: <!DOCTYPE html> <html> <body> <form method="POST" action="http://127.0.0.1:8000/members/login_user/"> User name: <input type="text" name="username" id="username" /> <br /> Password: <input type="password" name="password" id="password" /> <input type="submit" /> </form> <button onclick="logout()">Log out</button> <script> function logout() { csrf_cookieValue = document.cookie .split(";") .find((row) => row.startsWith("csrftoken")) .split("=")[1]; let xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:8000/members/logout_user/"); xhr.setRequestHeader("X-CSRFToken", "csrf_cookieValue"); xhr.send(); </script> </body> </html> -
relation "users_user" does not exist
so I am trying to migrate my app after just creating a project and this error just pop up out of the blue.. LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."user.... the only thing I did differently was that I used abstract user to extend my user models so that I can be able to give my user a specific role.it also does not allow me to create a super user as it throws the same error. I am new to all of this so some help can be really useful currently using Django 4.04. I tried deleting all migrations files and rerun migrations and didn't change anything models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_admin = models.BooleanField('Admin', default=False) is_teacher = models.BooleanField('Teacher', default=False) class Teacher(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) class Admin(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] AUTH_USER_MODEL = 'users.User' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') LOGIN_REDIRECT_URL = 'dashboard/' LOGIN_URL = 'login/' form.py from attr import field from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm class TeacherRegisterForm(UserCreationForm): email = forms.EmailField() class Meta(UserCreationForm.Meta): model = User fields = … -
Django count all unique accurance of a many to many field
I have models like : class Book: author = models.ManyToManyField() class Author: ... I want to get all unique authors that have books. example BookA: AuthorA, AuthorB BookB: AuthorB, AuthorC Auther D, E, F has no book so the result should be a query set of Author ABC. Most existing answers are just count of authors of each book. Thanks -
Permission for owner that user account
I building 2 permission for the user account owner and the apartment owner. Although they have the same code, the user account owner doesn't work. permissions.py class IsOwnerUserOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.username == request.user # Not Work class IsOwnerApartmentOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.seller == request.user # Work OK views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerUserOrReadOnly] class ApartmentViewset(viewsets.ModelViewSet): queryset = Apartment.objects.filter(issold=False).order_by('-timestamp') serializer_class = ApartmentSerializer # Set permission for only user owner apartment can edit it. permission_classes = [ permissions.IsAuthenticatedOrReadOnly, IsOwnerApartmentOrReadOnly] -
Problem in logging in the user in django webpage
I have issues with creating a login page in django. I am done with the views and html and stuff but the issue is that when I hit login it won't log the user in. After some debugging I saw that the issue is that the value of the user is None but I don't know why If anyone could help me with this it would be great i am posting the code below: views:- from django.shortcuts import render, redirect from .forms import RegisterForm, ProfileForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate def loginUser(request): if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] try: user = User.objects.get(email=email) except: print("User does not exist!") user = authenticate(request, email=email, password=password) if user is None: login(request, user) return redirect('home') else: print('The email or password is incorrect') html:- <div> <div class="login-container"> <div class="header-container"> <h1 class="header-text heading"><span>login</span></h1> </div> <div class="login-container1"> <div class="login-container2"> <span class="login-text biggerSubHeading">welcome</span> <form method="POST"> {% csrf_token %} <div class="login-container3"> <div class="label-container"> <label class="label"><span>Email</span></label> </div> <input type="text" name="email" placeholder="placeholder" class="login-textinput input" /> </div> <div class="login-container4"> <div class="label-container"> <label class="label"><span>Password</span></label> </div> <div class="password-field-container"> <div class="password-field-container1"> <input type="password" name="password" placeholder="placeholder" class="password-field-textinput input" id="lPassword" /> </div> <div class="password-field-container2"> <input type="checkbox" onclick="reveal3()" id="check3" class="password-field-checkbox" /> … -
How to handle two Django forms in one view?
I have a view that contains two Django forms. They were previously working but now whichever one is underneath the top one does not work. I have tried switching the order of the forms and whichever form is on the top will work while the other one will not do anything when submitted. I tried changing my forms so they resemble this example if request.method == "POST" and "selectgenderform" in request.POST: but that did not work (the forms did nothing). Does anyone know how to fix this problem? part of views.py def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) #code for comment and bid forms listing_price = listing.bid sellar = listing.user comment_obj = Comments.objects.filter(listing=listing) #types of forms comment_form = CommentForm() bid_form = BidsForm() #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for bid in other_bids: if bid.bid > max_bid: max_bid = bid.bid #checks if request method is post for all the forms if request.method == "POST": print(request.POST) #forms comment_form = CommentForm(request.POST) bid_form = BidsForm(request.POST) #checks if bid form is valid if bid_form.is_valid(): print('!!!!!form is valid') #print("bid form is valid") print(listing.bid) new_bid = float(bid_form.cleaned_data.get("bid")) if (new_bid >= listing_price) or (new_bid > max_bid): bid = bid_form.save(commit=False) … -
Django: Download a temporary image
I am currently trying to create a function within a Django app to download a pandas dataframe as an image. I wanted to create the image as a temporary file, download it, then delete it. Does anyone know how to integrate tempfile into this code? Views.py def download_png(request, study): Names(study) #Funciton to get (name) variable Retrieve(study) #Function to get (data) variable BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) pngfilename = str(name) + "_" + str(current_time) + ".png" temp = tempfile.NamedTemporaryFile(suffix=".png") fig = temp.write(df2img.plot_dataframe(data)) filepath = temp.name response = HttpResponse(df2img.save_dataframe(fig=fig, filename=filepath), content_type=mimetypes.guess_type(filepath)) response['Content-Disposition'] = "attachment; filename=%s" % pngfilename return response -
How to fix issue saving form to django database?
So I have a form you can fill from the webpage which I want to save to my django database to create a new object when submitted instead of adding it in admin. I've tried it and the system works except for one thing, saving it, the function starts as I've managed to switch pages from that function when clicking submit but the object isnt found in the database after so I guess the saving is the only issue. Here is my views.py : def uploadform(request): if request.method == 'POST': name = request.POST['name'] details = request.POST['details'] littype = request.POST['littype'] image = request.POST['image'] new_object = PostForm.objects.create(name=name, details=details, littype=littype, image=image) new_object.save() return render(request, 'uploadform.html', {}) Here is my models.py (The one to save the form is the "PostForm" class) : from email.mime import image from django.db import models from django.db.models import Model # Create your models here. class info(models.Model): name = models.CharField(max_length=100) details = models.CharField(max_length=10000) littype = models.CharField(default="Type of Litterature", blank=True, max_length=100) image = models.ImageField(default=None, blank=True, upload_to='app/files/covers') class PostForm(models.Model): name = models.CharField(max_length=200) details = models.TextField() littype = models.TextField() image = models.FileField(upload_to='app/files/') def __str__(self): return self.name Here is my html page : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link type="text/css" … -
How can I add to my investment balance with django
With the code below, I'm attempting to add the amount to my current balance but I am getting a 'QuerySet' object has no attribute 'balance' def create_investment_view(request): if request.method == "POST": form = InvestmentForm(request.POST) if form.is_valid(): amount = form.cleaned_data['amount'] user_investment = Investment.objects.all() user_investment = user_investment.balance + amount else: form = InvestmentForm() context = { 'form':form, } return render (request, 'create-investment.html', context) class Investment(models.Model): balance = models.IntegerField() class InvestmentForm(forms.Form): amount = forms.IntegerField(widget=forms.TextInput(attrs={'required':True, 'max_length':80, 'class' : 'form-control', 'placeholder': ' 1,000,000'}), label=_("Amount to deposit (Ksh.)"), error_messages={ 'invalid': _("This value must contain only numbers.") })```