Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does the script tag, not work in djagno?
I am using the navbar of this example project of Bootstarp 4.6. in my django project. Here is the code. $(function() { 'use strict' $('[data-toggle="offcanvas"]').on('click', function() { $('.offcanvas-collapse').toggleClass('open') }) }) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--Bootstrap--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Navbar--> <link rel="stylesheet" href="{% static 'css/quicky/navbar.css' %}"> <title>The</title> </head> <body> <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark"> <a class="navbar-brand mr-auto mr-lg-0" href="#">Offcanvas navbar</a> <button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Dashboard <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Notifications</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Profile</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Switch account</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Settings</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> <a class="dropdown-item" href="#">Another action</a> <a class="dropdown-item" href="#">Something else here</a> </div> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <div class="nav-scroller bg-white shadow-sm"> <nav class="nav nav-underline"> <a class="nav-link active" href="#">Dashboard</a> <a class="nav-link" href="#"> Friends <span class="badge badge-pill bg-light align-text-bottom">27</span> </a> <a class="nav-link" href="#">Explore</a> <a class="nav-link" href="#">Suggestions</a> <a class="nav-link" href="#">Link</a> <a class="nav-link" … -
i am making a test application in django and i want to submit the form when the time is over
this is my Html file and here I am trying to submit the form after 1 minute with all the values user has entered but the form is not posting any values <script> function countdown( elementName, minutes, seconds ) { var element, endTime, hours, mins, msLeft, time; function twoDigits( n ) { return (n <= 9 ? "0" + n : n); } function updateTimer() { msLeft = endTime - (+new Date); function submitform(){ document.getElementById("myForm").submit(); window.location.href = "http://127.0.0.1:8000/acceptAnswer"; } if ( msLeft < 100 ) { submitform() } else { time = new Date( msLeft ); hours = time.getUTCHours(); mins = time.getUTCMinutes(); element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits( time.getUTCSeconds() ); setTimeout( updateTimer, time.getUTCMilliseconds() + 500 ); } } element = document.getElementById( elementName ); endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500; updateTimer(); } countdown( "ten-countdown", 1, 0 );</script> <div class="container" > <div style="margin-left: 45%;" id="ten-countdown"></div> <form id="myForm" action="{% url 'acceptAnswer' %}" method="POST"> {% csrf_token %} {% for key, value in questions.items %} {{key}}){{value.question}} <br> <input type="radio" id="1" name="{{key}}" value="1">:{{value.option1}}<br> <input type="radio" id="2" name="{{key}}" value="2">:{{value.option2}}<br> <input type="radio" id="3" name="{{key}}" value="3">:{{value.option3}}<br> <input type="radio" id="4" name="{{key}}" value="4">:{{value.option4}}<br> {% … -
Django ManyToMany Field admin display highest value
I want to know how I can display the "highest value" from my ManyToMany Field in the admin. This is my models.py file: class Personal(models.Model): lastname = models.CharField(max_length = 100) firstname = models.CharField(max_length = 100) degree = models.ManyToManyField('Degree') def __str__(self): return self.lastname class Degree(models.Model): name_degree = models.CharField(verbose_name = 'Degree', max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name_degree In my backed, I have created different types of Degree's, all with a "ranking". In my case, the highest degree you can have is "Doctoral Degree", with a rank of "6". So if a User is creating himself in "Personal" he will have the option to select all the Degree's he has achieved. But for my Personal list, I just to want to see the highest one, e.g. if the User selects "Bachelor's Degree" and "Master's Degree", the Personal list should only contain "Master's Degree", because 5 > 4. Someone with an idea on how my admin.py file should look like? class PersonalAdmin(admin.ModelAdmin): list_display = ('lastname', 'firstname', ) # 'degree' -
NoReverseMatch at / 'learning_logs' is not a registered namespace
I think i tired everything in trying to solve this problem. I'm getting a NoReverseMatch i understand its from my "urls" but that's basically it, I was using url() instead of path().at the end of it all i just made a mess of my code. view.py from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic as TopicModel from .forms import TopicForms # Create your views here. def index(request): """"the home page for learning app""" return render(request,'learning_logs/index.html') def topics(request): topics = TopicModel.objects.order_by('date_added') context = {'topics' : topics} return render(request, 'learning_logs/topics.html',context) def topic(request, topic_id): """show a single topic ans all its entries""" topic = TopicModel.objects.get(id=topic_id) entries = topic.entry_set.order_by('date_added') context = {'topic':topic, 'entries': entries} return render(request,'learning_logs/topic.html',context) def new_topic(request): """add a new topic""" if request.method != 'POST': #no data submitted ; create a black form form = TopicForms else: #POST data submited ; process data if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_log:topics')) context = {'form': form } return render(request,'learning_log/new_topic.html', context) urls.py #defins URL patterns for learning log from django.conf.urls import url from . import views from django.urls import path app_name = 'learning_log' urlpatterns = [ #home page path('', views.index, name ='index'), #url(r'^$', views.index, name='index.html'), #show topics path('topics/',views.topics, name ='topics'), … -
Get the previous values of a multi-step form to render the future form in Django
I am making a project in Django but Im not using Django built-in forms. Rather, I have my way with html and bootstrap to render forms. On a page, I want to create a quiz. I am doing this via a multi-step form where I input the number of questions on the first form. Then based upon this field, when I hit next, I want to have the same number of the fields for questions and corresponding answers to appear so that I can set them. Is there a way to dynamically do this? Your help is much appreciated Thank you n here is my code snippet {% block content %} <div class="row"> <h2 style="color: darkblue;" class="text-center">Add a Quiz</h2> </div> <form action="" id="add_test_form" method="POST"> <!--This form will contain the quiz information--> {% csrf_token %} <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Name of test</label> <input type="text" class="form-control" name="test_name" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Description</label> <textarea type="text" class="form-control" name="test_desc" rows="8" required></textarea> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Number of questions</label> <input type="number" class="form-control" name="test_num_questions" min="1" oninput="validity.valid||(value='')" required> </div> </div> </div> <div class="row"> <div class="form-row"> <div class="form-group col-md-6"> <label>Time( Duration) in minutes</label> … -
'WSGIRequest' object has no attribute 'template' (Attribute Error while rendering a class based view in django)
What my view does, is takes an even from id, and returns an html page containing a table of all the details. It is a simple enough view: class Edetails(View, SuperuserRequiredMixin): template = 'events/details.html' def get(request, self, pk): event = Event.objects.get(id=pk) count = event.participants.count() participants = event.participants.all() ctx = { 'count': count, 'participants': participants, 'pk': pk } return render(request, self.template, ctx) However, when i click on the link to send a get request to the view: <a href="{% url 'events:Edetails' event.id %}">View Participants</a> I get this error message: AttributeError at /Edetails2 'WSGIRequest' object has no attribute 'template' I don't understand what this means. How can i fix this? -
Hello hope all of you are well i want to select motherboard on the basis of socket and chipset supported by CPU but it can fetch all motherboard
**basically, i want to develop a website like pc part picker in Django I want to select a motherboard on the basis of socket and chipset supported by CPU problem is it can fetch all motherboard I want to select only those motherboard having the same socket and chipset stored in session problem in build_mobo **here are models**** class vendor(models.Model): vendor_name=models.CharField(max_length=250) def __str__(self): return self.vendor_name class socket(models.Model): socket_type = models.CharField(max_length=250) def __str__(self): return self.socket_type class chipset(models.Model): cpu_chipset=models.CharField(max_length=250) def __str__(self): return self.cpu_chipset class CPU(models.Model): image = models.ImageField(upload_to="uploads/product/") vendor = models.ForeignKey(vendor , on_delete=models.CASCADE) cpu_name=models.CharField(max_length=250) cpu_price = models.CharField(max_length=250 , default="") generation = models.CharField(max_length=250) socket= models.ForeignKey(socket ,on_delete=models.CASCADE) chipset =models.ManyToManyField(chipset) def __str__(self): return self.cpu_name class Motherboard(models.Model): mobo_name= models.CharField(max_length=250) chipset = models.ForeignKey(chipset , on_delete=models.CASCADE) socket = models.ForeignKey(socket ,on_delete=models.CASCADE) vendor = models.ForeignKey(vendor , on_delete=models.CASCADE) DIMM_sockets = models.CharField(max_length=250 ,default="single", choices=(("dual","dual"), ("single","single"),("4","4"))) Supported_ram= models.CharField(max_length=250 ,default="ddr3", choices=(("ddr3","ddr3"), ("ddr4","ddr4"))) Onboard_Graphics= models.CharField(max_length=250,blank=True,null=True) Expensions_socket_version= models.CharField(max_length=250 ,default="version 1", choices=(("version 1","version 1"), ("version 2","version 2"), ("version 3","version 3"))) Audio =models.CharField(max_length=250,blank=True,null=True) LAN =models.CharField(max_length=250 ,blank=True,null=True) Storage_Interface =models.TextField(max_length=250 ,blank=True,null=True) USB =models.TextField(max_length=250 ,blank=True,null=True) def __str__(self): return self.mobo_name my view is : def build_cpu(request): data = CPU.objects.all() d = {'data1': data} return render(request, 'build/cpu.html', d) def build_home(request): if request.method == 'POST': cpu_id = request.POST['cid'] cpu_nam = request.POST['nammm'] dat = CPU.objects.get(cpu_name=cpu_nam) … -
Issues with Django Translations when deploying Webapp to Azure (localhost works)
Azure: Linux Webapp Deployment towards Azure via Azure Devops Pipeline on localhost everything works but on the Azure site it seems it does not get translated -
django request authentication every app after deployment in google cloud
after I have hosted my django app on google cloud, I keep asking for login every time I click on an app link. Does anyone know why? -
Trying to open select2 on page load gives the error “The select2('open') method was called on an element that is not using Select2.”
Trying to open the select2 on page load using document.ready doesn't work because "autocomplete_light.js initialize function" is tied to same event and at document.ready, the componente isn't initialized yet. So, doing as below doesn't work: $(document).ready(function () { $('#select2_field').select2('open') //OR $('#select2_field').open() }); The problem is that django autocomplete_light initializes the field on document.ready too. I need to open and focus the field on page load, same event. When I try to do so, it gives the error: The select2('open') method was called on an element that is not using Select2. If I access the method on another event, after document.ready, it works. So, the question is, how can I open the select2 on page load, after it has been initialized by autocomplete light? Autocomplete light doesn't have any callback that I could use. -
PyCharm with django template cannot recognize javascript without <script> tag
In order to centralize on "document ready" javascript bits, in my Django base template I have a main.html something like this : ... <script type="text/javascript"> <!-- $(document).ready(function () { {% block jqueryDocReady %}{% endblock jqueryDocReady %} ... some global init ... }); //--> </script> In views I use a new template that inheriates from the base template and add some javascript bits : {% extends ".../main.html" %} ... {% block jqueryDocReady %} {{ block.super }} some_init_vars = {{ context_var }}; ... and some little view specific javascript code ... {% endblock %} Here comes my problem with PyCharm : the javascript syntax coloration does not work in view specific code : some_init_vars = {{ context_var }}; ... and some little view specific javascript code ... The reason is because I cannot add here <script></script> tags as there are already present in base template. I do not want to create many little .js file for every little view-specific code. How can I make Pycharm color javascript code bits without any script tags or how can I reorganize my code to be nicer for Pycharm while being still concise ? -
Unresolved reference 'graphene_django'
I just started working with GraphQL, Django and Graphene. I was attempting to import GraphQLView and DjangoObjectType from graphene_django but it always says unresolved reference I did already installed the needed modules with pip install graphene-django==2.8.2, and the Virtual environment is up and running. #settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'books', 'graphene_django', ] I couldn't get graphene_django to import properly. What are the possible fixes to this? -
Django: Customize Admin page or create admin app
I want to create a login page and an admin page for users (with different permissions) for a web project. In it, models from different apps can be edited. However, the linked models should be edited in different structures, e.g. model in "Settings" for an app. Should I modify and adapt the Django Admin interface more for this or create an 'Admin' app in which I regulate this through forms? -
Django : Git ignored files are deleted automatically after every git push to the server
I have a local repo that has a live remote to our Django server, where I have a git post-recieve hook to deploy pushed files. The problem is, the files under gitignore are deleted automatically as soon as a new commit is pushed to the server. The files are namely local_settings.py, db.sqlite3 and the /media directory. For obvious reasons, I want those files to be utilized off the server itself. After a commit, I manually added those files/folders back to the website directory, and everything works fine, until I push another set of updates to the server. Whenever this happens, the updates come out fine but local_settings.py, db.sqlite3 and the /media directory is auto-deleted somehow and nowhere to be seen. This is making my deployment a nightmare and I've been struggling with it for the past 3 days. Any help/insight into this will be highly appreciated, thank you! -
How to override foreign key null values in django serializer?
I'm serializing a query set to json format using natural_keys. Reference: docs I'm able to serialize data successfully. In case, there are any foreign keys, then I'm also able to add it's object instead of foreign key. For example: class Parent(models.Model): name = models.CharField() def get_natural_keys(self): return( {'name': self.name, 'pk': self.pk} ) class Child(models.Model): name = models.CharField() parent = models.ForeignKey(Parent, null=True) And while querying data: child = serializers.serialize('json', Child.objects.all(), user_natural_foreign_keys=True, use_natural_primary_keys=True) This will return json: { "model": 'proj.child' "pk": 1, "fields": { "name": "child name", "parent": {"id": 1, "name": "parent name"} } } Till this point every thing is fine. My issue is that when parent foreign key is null in child, it returns None in parent: fields: { "name": "child name", "parent": None } How I am expecting is: fields: { "name": "child name", "parent": {"id": None. "name": None} } How can I override the None value to another dictionary? -
Django custom dynamic form issue
I am trying to build a form that consists of dynamic adding of lesson availability to the form, the lesson availability has the foreign key of the lesson and the form for lesson availability is generated dynamically using JavaScript The problem is the model contains static values like: ''' lesson_virtual_id = models.Charfield(max_length = 100) ''' And the output of the forms comes like this: ''' lesson_virtual_id1': ['123456'], 'lesson_password1': ['password'], 'lesson_language1': [''], 'lesson_virtual_id2': ['123456'], 'lesson_password2': ['password'], 'lesson_language2': [''], ''' The dynamic html form in javascript file looks like this: ''' <div class="row accordion add-collapsed avail-${acount} " id="faq"> <div class="col-12 row card"> <div class="ml-3 d-flex"> <div class="col-sm-11 card-header" id="aqhead${acount}"> <a href="#" id="demo${acount}" class="btn btn-header-link collapsed" data-toggle="collapse" data-target="#faq${acount}" aria-controls="faq${acount}" >Lesson at</a> </div> <span class="col-sm-1 m-3"> <i style="color:#f10909;" class="fas fa-trash-alt" onclick="delete_collapsed(${acount});"></i> </span> </div> <div id="faq${acount}" class="col-sm-11 collapse hide" aria-labelledby="faqhead${acount}" data-parent="#faq"> <div class="card-body"> <div class="form-group"> <label>Lesson Type</label> <div class="col-12 d-flex"> <div class="form-check form-check-inline col-6"> <input class="form-check-input lesson_type${acount}" type="radio" name="lesson_type_radio${acount}" id="inlineRadio_${acount}" value="Live Virtual" onclick="lesson_type(${acount});"> <label class="form-check-label" for="inlineRadio_${acount}">Live Virtual</label></div> <div class="form-check form-check-inline col-6"> <input class="form-check-input lesson_type${acount}" type="radio" name="lesson_type_radio${acount}" id="inlineRadio2_${acount}" value="In-Person" onclick="lesson_type(${acount});"> <label class="form-check-label" for="inlineRadio2_${acount}">In-Person</label></div> </div> </div> <div class="form-group"> <input type="hidden" class="form-control lesson_text${acount}" name="lesson_text[]" id="lesson_text${acount}" readonly></div> <div class="form-group venue${acount}" style="display:none;"> <label>Lesson Venue</label> <div class="col-12 d-flex"> <div class="form-check form-check-inline … -
Django Changes in env lib site-packages don't apply
I meet a problem with a package : django-ckeditor. I have installed it with pip in my venv. And now I want to add just 1 or 2 modifications in the views file of ckeditor. The problem is : anything I write in this file: env\Lib\site-packages\ckeditor_uploader\views.py is not applying when I restart server. Look class ImageUploadView(generic.View): http_method_names = ["post"] def post(self, request, **kwargs): print("hello") I never get anything when I do this post request. Actually whatever I write (I removed all the lines and add 'azerrty' in my code) the server will run correctly... Does someone know why changes in my venv are not considered ? And how to solve this ? I tried to deactivate the venv and activate it again it didn't change anything -
django filters with pagination: showing same page after pressing next url
When i search for something(like tom), it works well for first page. But if I click next page url, it shows the same result, nothing changes, but in url, it becomes http://127.0.0.1:8000/search/?caption=tom to http://127.0.0.1:8000/search/?caption=tom&?page=2 filters.py: class VideoFilter(django_filters.FilterSet): class Meta: model = Video fields = ['caption'] filter_overrides = { models.CharField: { 'filter_class': django_filters.CharFilter, 'extra': lambda f: { 'lookup_expr': 'icontains', }, }, } views.py: def search(request): queryset = Video.objects.all() filterset = VideoFilter(request.GET, queryset=queryset) if filterset.is_valid(): queryset = filterset.qs paginator = Paginator(queryset, 2) page_number = request.GET.get('page') print(page_number)# always prints **none** queryset = paginator.get_page(page_number) return render(request, 'search.html',{ 'result': queryset, 'caption': request.GET['caption'], }) search.html: {% extends 'navbar.html' %} {% block body %} <!-- more code --> {% if result.has_next %} <a href="?caption={{caption}}&?page={{result.next_page_number}}"><button>See more results</button></a> {% endif %} {% endblock body %} navbar.html: <!-- more code --> <form action="/search/" method="GET"> <!-- working without csrf_token --> <input type="text" placeholder="Search" id="search" name="caption" required /> <button type="submit">Search</button> </form> where is the problem? how do i visit next page? -
How can I use custom web fonts in django cms icons
My question is how do how does the `/admin/djangocms_icon/includes/assets.html` file look like? Can someone give a sample supposing I am using font awesome 5? Below are the configuration settings that I followed on github. Configuration This addon provides a `default` template for all instances. You can provide additional template choices by adding a `DJANGOCMS_ICON_TEMPLATES` setting:: DJANGOCMS_ICON_TEMPLATES = [ ('svg', 'SVG template'), ] Web Font Icons ############## The django CMS Icon plugin ships with Font Awesome 4 as default. This can be changed by overriding the following setting:: DJANGOCMS_ICON_SETS = [ ('fontawesome4', 'fa', 'Font Awesome 4'), ] To use Font Awesome 5 in the above example; see the options below from the `DJANGOCMS_ICON_SETS` listed. In addition you need to load the resources for your fonts in `/admin/djangocms_icon/includes/assets.html`. Add this file to your project in order for the icon picker to pick up your custom icons in the admin. The icon picker supports `numerous font libraries <http://victor-valencia.github.io/bootstrap-iconpicker/>` out of the box. You can also add multiple font sets like this:: DJANGOCMS_ICON_SETS = [ ('elusiveicon', 'el', 'Elusive Icons'), ('flagicon', 'flag-icon', 'Flag Icons'), ('fontawesome4', 'fa', 'Font Awesome 4'), ('fontawesome5regular', 'far', 'Font Awesome 5 Regular'), ('fontawesome5solid', 'fas', 'Font Awesome 5 Solid'), ('fontawesome5brands', 'fab', 'Font Awesome … -
Django unit test is not finding any test
I want to run a unit test on test_models.py the contents of the file is below: from django.test import TestCase from django.contrib.auth import get_user_model class ModelTest(TestCase): def test_create_user_with_email_successful(self): email = 'superuser@super.com' password = '9876543210' user = get_user_model().objests.create_user( email=email, password=password ) self.assertEqual(user.email, email) self.assertTrue(user.check_password(password)) after i run python manage.py test I get this: System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK the file structure of my project is in the picture -
How do I access a Django template variable item(e.g an object in a list) using a variable
I have a for loop looping over a list supplied to the template. Now I want to use the first item on the list to on the first loop iteration, the second during the second one and so on. To access items in a list I would expect to use foo['bar'] or foo.bar. Question is how do I do this when bar is an attribute like {{ forloop.counter0 }}. {% for data in some_data %} <td>{{ some_list.{{ forloop.counter0 }} }}.</td> <!-- Cannot do this, Problem here --> {% endfor %} -
Alternative way of querying through a models' method field
I have this model about Invoices which has a property method which refers to another model in order to get the cancelation date of the invoice, like so: class Invoice(models.Model): # (...) @property def cancel_date(self): if self.canceled: return self.records.filter(change_type = 'cancel').first().date else: return None And in one of my views, i need to query every invoice that has been canceled after max_date or hasn't been canceled at all. Like so: def ExampleView(request): # (...) qs = Invoice.objects if r.get('maxDate'): max_date = datetime.strptime(r.get('maxDate'), r'%Y-%m-%d') ids = list(map(lambda i: i.pk, filter(lambda i: (i.cancel_date == None) or (i.cancel_date > max_date), qs))) qs = qs.filter(pk__in = ids) #Error -> django.db.utils.OperationalError: too many SQL variables However, ids might give me a huge list of ids which causes the error too many SQL variables. What's the smartest approach here? -
How to make a reserved button?
How can I create a button that when pressed, the car is reserved? Im trying to use a form with method GET but the button dont send nothing. Code: html: <from> <button onclick="enviar(True=true)" type="submit" name="id_coche" value="{{ car.matricula }}" >Reservar</button> </from> <script> function enviar(True) { let url = "" $.ajax({ method: 'GET', url: url, data: {}, success: True }); } </script> Views.py:### class CocheDetalles(DetailView): model = Coche template_name="wallacar_app/detalles.html" #if request.method == "GET": #Coche.objects.update(reserved=True) def get_context_data(self,object): context = super(CocheDetalles, self).get_context_data() context['coche'] = Coche.objects.filter(matricula=self.object).all() return context Im using Django 3.1.7 and jQuery. -
'QuerySet' object has no attribute 'user'
I am trying to query from pending payments and then when a user requests for a payment i also want to be checking from the orders that corresponds to a logged in user. This is the code that fetches the withdraw requests: pending_requests = WithdrawRequest.objects.filter(status='pending') Code that fetches the totals orders corresponding to the user from pending_requests variable above which is pending_requests.user: #amount query AccBalance = OrderData.objects.filter(payment_to=pending_requests.user, payment_status='approved').aggregate(totals=Sum(F('item__price')*F('quantity'))) The problem is i am getting this error: 'QuerySet' object has no attribute 'user' My full view.py code: def withdraw_requests(request): pending_requests = WithdrawRequest.objects.filter(status='pending') #amount query AccBalance = OrderData.objects.filter(payment_to=pending_requests.user, payment_status='approved').aggregate(totals=Sum(F('item__price')*F('quantity'))) context = {'AccBalance':AccBalance,'pending_requests':pending_requests} return render(request, 'accounts/withdraw_requests.html', context) -
How to update a record in django?
I try to update my record but in place of updating it displays a message saying the record already exists. here is the logic I m executing : @login_required def cylinderUpdateView(request,pk): if not request.user.is_superuser: return redirect('index') obj=CylinderEntry.objects.get(id=pk) form=CylinderEntryForm(instance=obj) if request.method=='POST': form=CylinderEntryForm(data=request.POST) if form.is_valid(): obj=form.save(commit=False) obj=form.save() return redirect(cylinderListView) return render(request,'entry/cylinderentry_form.html',locals())