Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django update model and preventing full table lock
Im using django 4.0.0. I have a model with an touched column (DateTimeField) to specify when a specific row was "touched" (like the unix command). I want to write a management command that updates this column to now() like so MyModel.objects.all().update(touched=now()) but the numbers of rows is large and i DON'T want to have a full table lock for this. Is there any way to have django update the queryset in multiple batches - each batch in a DIFFERENT TRANSACTION? or is there anyway to split my queryset to do this manually? -
How to implement a mapbox search box
I am struggling to implement a single map box search box into my project. I have a form and an input box that I would like to show POI suggestions. I do not want the mapbox search box to make my webpage scroll and I have tried to control it with the html/css but I believe I have to control the search box itself but I do not know how to do this. Please help I have tried to copy this example: https://docs.mapbox.com/mapbox-search-js/example/theming/ But it still is not working because I have to use "autocomplete=street-address" this means there is no POI suggestions being shown only addresses. Finally after I have got the input of the user I would like what they click as a suggestion to be passed to the API so my backend function can get the information such as latitude and longitude -
Django admin StackedInline throws (admin.E202) 'accounts.CustomUser' has no field named 'user' error
I have a CustomUser model, and a Retailer model that holds the additional details of retailer user type. The Retailer model has a OneToOne relation to CustomUser model. There is no public user registration or signup, accounts are created by superuser. In the Django admin site, I am trying to leverage admin.StackedInline in the retailer admin page to enable superusers to create new retailer users directly from the retailer admin page. This eliminates the need to create a new user object separately in the CustomUser model admin page and then associate it with a retailer object using the default dropdown in the retailer model admin page. However, I got the below error: MODELS.PY class CustomUser(AbstractUser): """ Extended custom user model. """ uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None # type: ignore first_name = None # type: ignore last_name = None # type: ignore name = models.CharField(_("Name of User"), max_length=150) email = models.EmailField(_("Email address of User"), unique=True, blank=False) date_modified = models.DateTimeField(auto_now=True) # Flags for user types is_retailer = models.BooleanField( _("Retailer status"), default=False, help_text=_("Designates whether the user should treated as retailer"), ) is_shop_owner = models.BooleanField( _("Shop owner status"), default=False, help_text=_("Designates whether the user should treated as shop owner"), ) USERNAME_FIELD = … -
How to upload image to cloudinary without creating a model in Django
I am building a website using Django. There is a Website and there is a server. Website communicates to server using API. I dont want the website to use any database (I want all data to be stored at the server). I want to upload images to cloudinary however couldn't figure out how to upload an image to cloudinary without creating a model in website. My website has an image upload location and when a user uploads an image, i want to upload that image to cloudinary directly and then retrieve the url of the image and send this url to server with api. Sending to server and uploading is fine, i can do that. But how can i upload to cloudinary and retrieve the url of the uploaded image in the same view function without creating a model or storing any data on the database (i will store it on the server's database) Thanks. I was able to upload images to cloudinary and retrieve the url however i was only able to do this by creating a model and saving it to the database. I don't want to create a model and save to the database. I just want … -
How to mock test a function inside save method
I want to send an email each time the status of an object was equal to 13. def save(self, *args, **kwargs): from user_profile.models import SopResumeBuy if skip_sop_resume := kwargs.get('skip_sop_resume'): del kwargs['skip_sop_resume'] if(self.status == 13): email_sender( "subject", f"email body", ) ...... the save method will call another email_sender which is a function inside another file. I want to make sure that the email will be sent.How can i mock the process of sending email? -
What causes a blank white screen in react app on the local host 3000
I am working on a web app in Django and React and when I try to run the react app on the localhost 3000, nothing is showing on the screen. It shows only a blank white screen, and the following error Failed to compile. .\src\api\api.js Cannot find file '../config.json' in '.\src\api'. What might be the problem -
Data given in django model form is not getting displayed in another page
#my Models.py file from django.db import models # Create your models here. class EmpModel(models.Model): empName = models.CharField(max_length = 20) empJob = models.CharField(max_length = 20) def __str__(self): return self.empID # myForms.py file from django.forms import ModelForm from myWebApp.models import EmpModel class EmpModelForm(ModelForm): class Meta: model = EmpModel fields = [ "empName", "empJob"] #myViews.py File from django.shortcuts import render from django.db import models from myWebApp.models import EmpModel from django.template import loader from django.http import HttpResponse from django.forms import modelformset_factory # Create your views here. from .forms import EmpModelForm def empDetails(request): if request.method == "POST": form = EmpModelForm(request.POST) if form.is_valid(): empFormSave = form.save() empInfoData = EmpModel.objects.all() return render(request, "empInfoData.html", {"empInfoData" : empInfoData}) else: form_class = EmpModelForm return render(request, "empInfo.html", {"form" : form_class}) #myCollectedDateDisplay Page <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>Employee Information Submitted</title> </head> <body> <h2>Employee Data available in the system</h2> <p>Employee Name : {{ empInfoData.empName }}</p> <<p>Employee Job : {{ empInfoData.empJob }}</p> </body> </html> Initially I had many modelfields like positiveinteger, datetime, etc.. I was getting integrity error. So, I removed and kept only charfield. The integrity error is resolved and page is being displayed but data is showing empty I have done "python manage.py makemigrations" python … -
How can I connect google pay to my django project?
I am making a django project and I want to add a google pay system so that I can take payments and then provide them with the course. I can't find anything on internet I even asked ChatGPT and Bard but they did'nt told properly so can't do anything. -
I am integrating SAML with django using djangosaml2 and idp as okta, configured my setting.py file with SAML_CONFIG,
My settings.py is like import os BASEDIR = os.path.dirname(os.path.abspath(__file__)) SAML_CONFIG = { "strict": True, "debug": True , "service" :{ "sp": { 'name': 'XXX', 'allow_unsolicited': True, 'want_assertions_signed': True, # assertion signing (default=True) 'want_response_signed': True, "want_assertions_or_response_signed": True, # is response signing required 'name_id_format': "urn:oasis:names:tc:SAML:1.1:nameid-format:basic", "entityId": "https://localhost:8002/metadata/", "assertionConsumerService": { "url": "https://localhost:8002/?acs", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" }, "singleLogoutService": { "url": "https://localhost:8002/?sls", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" }, "NameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", "x509cert": "", "privateKey": "" }, "idp": { # "entityId": "https://dev-92033760.okta.com/app/exv13qURtCj35d7/sso/saml/metadata", "entityId": "http://www.okta.com/3qURtCj35d7", "singleSignOnService": { "url": "https://dev-9203760.okta.com/app/dev-92033760_saml4july_1/exRtCj35d7/sso/saml", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" }, "singleLogoutService": { "url": "https://dev-9233760.okta.com/app/dev-92033760_saml4july_1/exka35d7/sso/saml", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" }, }, }, 'metadata': { 'local': [os.path.join(BASEDIR, 'remote_metadata.xml')], } } but getting below after successful redirection from okta Authentication Error. Access Denied. and on logs getting Traceback (most recent call last): File "/home/zec/label-studio-project/djangosaml2/djangosaml2_venv/lib/python3.8/site-packages/djangosaml2/views.py", line 469, in post response = client.parse_authn_request_response( File "/home/zec/label-studio-project/djangosaml2/djangosaml2_venv/lib/python3.8/site-packages/saml2/client_base.py", line 773, in parse_authn_request_response raise SAMLError("Missing entity_id specification") saml2.SAMLError: Missing entity_id specification Forbidden: /saml2/acs/ -
How can I get the right Lag using Subquery, Django ORM
Using Django 4.2, MySQL 8.x I am using one model which refers to itself with field name supertask. self.accumulative indicates that proportion field is recorded in accumulative manner. If True, I would like to get lag to get proper value. For example, say task A has subtasks B, C, and D, with 2, 3, and 4 for their proportion. A.accumulative is True. So, I would like to use F('proportion') - F('lag') for calculating weighted_achievement. However, I get 0 for lags (supposed to have 2, 1, and 1, respectively). Here's the code: def assess_achievement(self): if self.subtasks.exists(): subtasks = self.subtasks.order_by('proportion') print(subtasks.query) proportion = F('proportion') proportion_total = Sum('proportion', output_field=FloatField()) if self.accumulative: subquery = Subquery( self.subtasks.annotate( lag=Window( expression=Lag('proportion', offset=1, default=0), order_by=F('proportion').asc(), partition_by=F('proportion') ) ).values('lag')[:1] ) subtasks = subtasks.annotate(lag=subquery) print(subquery.query) for i in subtasks: print(i.proportion, i.lag) # 0 proportion -= F('lag') proportion_total = Max('proportion', output_field=FloatField()) weighted_achievement_total = subtasks.annotate( weighted_achievement=Case( # pseudo_achievement When(completed=True, then=proportion), default=F('achievement')*proportion, output_field=FloatField(), ) ).values('weighted_achievement').aggregate( weighted_achievement_total=Sum( 'weighted_achievement', output_field=FloatField() ) ).get('weighted_achievement_total', 0) Why can't this code get the right lag and how can I fix it? -
Does subprocess.Popen.wait deadlock when using file type for stdout?
Any help is appreciated. I have a custom Django command and a method like the one below: def read_status_to_list(self) -> List[str]: with open('git.txt', 'w+') as temp: status = subprocess.Popen(['git', 'status'], stdout=temp) status.wait() statuses = [line.split()[-1] for line in temp.readlines() if 'modified:' in line ] # remove file when done if os.path.isfile('git.txt'): os.remove('git.txt') return statuses However, statuses is always empty even when git status produces a number of modified modules not added yet. I noticed a warning in the wait method: Warning: This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. Is this warning related to the problem, and how can I successfully complete this task using subprocess? Thank you. -
Django Interview Question for showing the result in coding
While showing my project by sharing the screen, I explained my project which is on Student Management System to interviewer but he was kept asking me about show me the result in code. I'm fresher and I haven't used python Django much so can anyone explain me what result should I show to the interviewer? I have done that project by watching tutorials on Student Management System. What do they expect us to show? YouTube Link - https://youtu.be/FMPpaTFdL2k I explained him the overall working of code. I showed him backend admin panal and also python code fies urls settings models views. But he was keep repeating show me the result. Please explain me someone how can I show the result. -
how to filter the data from django database for a week?
I'm filtering the data from django database using datetime__range filter providing the dates start_of_week and end_of_week and I have another list in python that contains the dates of that week so when I got the data from the range filter I count it for each day using the date from the week but for some users the result I got contain the data of one day earlier so it shows error because the result contain I date earlier of start_of_week date which was not in week_dates list so it shows key error. How Should I filter the data so that I got proper data between the range. I'm adding the models.py and admin.py and the screenshot of terminal. `the model of User_details in models.py SUGESSTION_CHOICES = ( (0,'Pending Verification'), (1, 'User Accepts Prediction'), (2,'User Suggestion Incorrect'), (3,'Actual Prediction Incorrect'), (4,'Unsupported Breed'), (5,'In Progress'), (6,'Model Successfully Trained'), ) PREDICTION_CHOICES = ( (0,'By Image'), (1, 'By Video') ) PREDICTION_STATUS = ( (0,'Predicted Sucessfully'), (1, 'Not Able To Predict'), (2, 'Junk'), ) class History(models.Model): user= models.ForeignKey(User_details, related_name='history', on_delete=models.CASCADE) image=models.ImageField(upload_to=get_upload_path,null=True) predictions= models.TextField(default=dict(),null=True,verbose_name="Predictions") predictions_type=models.IntegerField(choices=PREDICTION_CHOICES, default=0,verbose_name="Prediction Type") predictions_status=models.IntegerField(choices=PREDICTION_STATUS, default=0,verbose_name="Prediction Status") predicted_breed_id = models.PositiveIntegerField(null=True,blank=True,verbose_name="Predicted Breed Id") moods= models.TextField(default=dict(),null=True,verbose_name="Moods") user_platform= models.CharField(max_length=50,default='',null=True,verbose_name="User Platform") user_device= models.CharField(max_length=50,default='',null=True,verbose_name="User Device ID") app_version= models.CharField(max_length=50,default='',null=True,verbose_name="App … -
Form in Django not saving my article to database
I am making a blog/articles page in django, and whenever I try to enter some input, it doesn't save to the database. I have tried re-running the server, refreshing, still it doesn't save. I am getting no errors, 200 code meaning it's all OK. views.py @login_required(login_url="/accounts/login/") def new_article(req): if req.method == 'POST': form = forms.CreateArticle(req.POST, req.FILES) if form.is_valid(): #save article to database instance = form.save(commit=False) instance.author = req.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(req, 'articles/createArticle.html', {'form': form}) createArticle.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Article Home Page</title> <link rel="stylesheet" href="/static/styles.css"> </head> <body> <a href="{% url 'articles:list'%}"><img src="/static/logo.png" alt="TBD"/></a> <nav> <ul> <li> <form class="logout-link" action="/accounts/logout/" method="post"> {% csrf_token %} <button type="submit">Log Out</button> </form> </li> </ul> </nav> <div class="create-article"> <h2>Write your own Article!!</h2> {% csrf_token %} <form class="newArticleForm" action="/articles/create/" method="post" enctype="multipart/form-data"> {{ form }} </form> <input type="submit" value="Create"> </div> </body> </html> models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Articles(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, default = None, on_delete=models.CASCADE) def __str__(self): return self.title def snippet(self): return self.body[:50]+'...' I am following Net Ninja Django Tutorial and have been … -
AbstractUser django
abstractuserI created user AbstractUser to be a standalone user and to log in via this user Unfortunately when I create a user and log in through that user it tells me the username and password Error login page for admin django verifies the default username and password and does not authenticate with the user you created AbstractUser What is the solution for the admin django login page to verify the partition created by user django admin. admin2. admin3. forms. models. settings. view. -
Cannot connect MySQL in a Django project docker container
First, I installed Docker v4.20.1 in my Windows 10. I run docker compose successfully and their status are as the following screenshot. my phpmyadmin container can access mysql db successfully as the following screenshot. If I run the django project in my host computer(Windows 10), it also connect mysql db successfully. But If I try to run the django server in the web container, it shows up the error message that it can't connect mysql db correctly. The error logs: root@80c6e906cf7e:/usr/src/app# python caravan/manage.py migrate Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 291, in _open_connection self._cmysql.connect(**cnx_kwargs) _mysql_connector.MySQLInterfaceError: Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/usr/local/lib/python3.10/dist-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/django/base.py", line 399, in get_new_connection cnx = mysql.connector.connect(**conn_params) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/pooling.py", line 293, in connect return CMySQLConnection(*args, **kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 120, in __init__ self.connect(**kwargs) File "/usr/local/lib/python3.10/dist-packages/mysql/connector/abstracts.py", line 1181, in connect self._open_connection() File "/usr/local/lib/python3.10/dist-packages/mysql/connector/connection_cext.py", line 296, in _open_connection raise get_mysql_exception( mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111) The above exception … -
Celery not running new task
I've readded an old Celery task to my Django app running on Heroku, but it's not being run by the worker. The task appears in the tasks when the worker starts, and I can see the scheduler sending it to the worker. However, it is never received by the worker. What can I do to troubleshoot this issue? Other tasks added are running fine and it runs fine on the staging server which is another instance on Heroku. I've tried restarting all the dynos and changing the name of the task and repushing it but that hasn't worked. -
Unable to understand the bug in views.py
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ':pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside <h1></h1> This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the <ul></ul> When I run the debugger for the views.py file, it gives me: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Please suggest solution -
How do I add custom attributes autocomplete to crispy_forms Django
I would like to check how do I add the autocomplete attribute to the crispy_forms. Any help would be appreciated. Thanks. -
How to filter model by foreign key field of FK field?
I have model 'Employee': class Employee(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) lastname = models.CharField(max_length=50) end_user_id = models.CharField(max_length=8, help_text=u"Please enter the end user id, like ABC1WZ1") history = HistoricalRecords() def __str__(self): return self.name + ' ' + self.lastname Employee can be a manager, so I also have model 'Manager': class Manager(models.Model): id = models.AutoField(primary_key=True) manager = models.ForeignKey(Employee, verbose_name='manager', on_delete = models.DO_NOTHING) def __str__(self): return self.manager .name + ' ' + self.manager .lastname And my main model 'MissForm': class MissForm(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) auto_inc_id = models.IntegerField(blank=True, null=True) sender = models.ForeignKey(Employee, verbose_name='sender', on_delete = models.DO_NOTHING, blank=True, null=True) manager = models.ForeignKey(Manager, verbose_name='Manager', on_delete = models.DO_NOTHING, related_name='+', blank=True, null=True ) status_flag = models.PositiveIntegerField(default=1) I am trying to get all instances of MissForm model where manager is a current logined user and status_flag=2( in views.py): login_user_id = request.user.username.upper() # returns smth like ABC1WZ1 forms = MissForm.objects.filter(status_flag=2, manager__manager__end_user_id=login_user_id) But it doesn't work. What I am doing wrong? -
How to display views.py results directly and dynamically on template.html in django?
I have a django website project with exper.html template and views.py as processing backend. I want when we enter parameters or input in the textarea and after that press the submit button, then views.py can process those parameters and generate images and display them directly in the exper.html template file. below is the code for expert.html and views.py exper.html: <div class="container-area text-center"> <form id="myForm" class="row"> {% csrf_token %} <div class="col-md-12"> <label for="input_text"></label><br> <textarea id="input_text" name="input_text" rows="10" cols="100" placeholder="Write Code Here" required></textarea><br><br> </div> <div class="col-md-12 d-flex justify-content-center align-items-center"> <input type="button" value="Run" onclick="submitForm()"> </div> </form> </div> <script> function submitForm() { const form = document.getElementById('myForm'); const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value; const inputText = document.getElementById('input_text').value; const xhr = new XMLHttpRequest(); xhr.open('POST', ''); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('X-CSRFToken', csrfToken); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const response = JSON.parse(xhr.responseText); displayImages(response.data_input_img, response.qam_mod_img); } }; xhr.send('input_text=' + encodeURIComponent(inputText)); } </script> views.py def exper(request): if request.method == 'POST': form = ParameterForm(request.POST) if form.is_valid(): input_text = form.cleaned_data['input_text'] subcarrier = 0 mod_order = 0 for param in input_text.split(): if param.startswith('subcarrier='): subcarrier = int(param.split('=')[1]) elif param.startswith('mod_order='): mod_order = int(param.split('=')[1]) data_in = generate_input_data(subcarrier, mod_order) plt.figure() plt.stem(data_in, use_line_collection=True) plt.title('Data Input') plt.xlabel('Indeks Data') plt.ylabel('Nilai Data') plt.grid(True) plt.savefig('static/files/datainput.png') data_input_img_base64 = … -
prefetch_related() without specifying lookups
I encountered such a queryset in a project : qs.prefetch_related().other().methods() Is there a point having such call to prefetch_related() method without specifying any lookup? -
Django - [wsgi:error] [pid 16542:tid 140650901133056] Truncated or oversized response headers received from daemon process
I have googled and tried each and every option but nothing worked . Below are the version specification which is used . Apache/2.4.37 (AlmaLinux) OpenSSL/1.1.1k mod_wsgi/4.6.4 Python/3.6 and mariadb as the database Using Virtual environment Below are my Virtual Configuration paramters with wsgi WSGIDaemonProcess cosmos processes=6 maximum-requests=300 header-buffer-size=65536 connect-timeout=30 python-path=/opt/cosmos/cosmos_api_v3:/opt/cosmos/cosmosenv/lib/python3.6/site-packages/ WSGIApplicationGroup %{GLOBAL} WSGIProcessGroup cosmos WSGIScriptAlias /api /opt/cosmos/cosmos_api_v3/cosmos/wsgi.py WSGIPassAuthorization On Below are installed python packages Package Version amqp 5.0.6 ansible 2.9.0 asgiref 3.4.1 bcrypt 3.2.0 beautifulsoup4 4.11.2 billiard 3.6.4.0 cached-property 1.5.2 celery 5.1.2 certifi 2021.5.30 cffi 1.15.0 charset-normalizer 2.0.6 click 7.1.2 click-didyoumean 0.3.0 click-plugins 1.1.1 click-repl 0.2.0 coreapi 2.3.3 coreschema 0.0.4 crypto 1.4.1 cryptography 35.0.0 Django 3.2.7 django-auth-ldap 3.0.0 django-celery-beat 2.2.1 django-celery-results 2.2.0 django-cors-headers 3.10.0 django-filter 21.1 django-rest-swagger 2.2.0 django-timezone-field 4.2.1 djangorestframework 3.12.4 djangorestframework-jwt 1.11.0 djangorestframework-simplejwt 4.4.0 docopt 0.6.2 humanfriendly 10.0 idna 3.2 importlib-metadata 4.8.1 itypes 1.2.0 Jinja2 3.0.2 kombu 5.1.0 lxml 4.6.3 MarkupSafe 2.0.1 mysql-connector 2.2.9 Naked 0.1.31 openapi-codec 1.3.2 packaging 21.0 pandas 1.1.5 paramiko 2.8.0 pip 21.3.1 prompt-toolkit 3.0.20 pyasn1 0.4.8 pyasn1-modules 0.2.8 pycparser 2.20 pycryptodome 3.11.0 pyflakes 2.3.1 Pygments 2.10.0 PyJWT 1.7.1 PyMySQL 1.0.2 PyNaCl 1.4.0 pyparsing 3.0.2 python-crontab 2.5.1 python-dateutil 2.8.2 python-dotenv 0.19.2 python-ldap 3.3.1 python-magic 0.4.27 pytz 2021.1 pyvcloud 23.0.3 pyvim 3.0.2 pyvmomi 7.0.2 PyYAML 6.0 … -
I am unable to obtain list of elements from a class created in a python file to display in an HTML file
This is my views.py in which I have created the class Pizza. from django.shortcuts import render from .models import Pizza def index(request): pizzas = Pizza.objects.all() return render(request, 'menu/index.html', {'pizzas ': pizzas}) And this is the html file: <html lang="en"> <head> <meta charset="UTF-8"> <title>Our Pizzas</title> </head> <body> <h1>Our Pizzas</h1> <ul> {% for pizza in pizzas %} <li>{{pizza.name}}</li> {% endfor %} </ul> </body> </html> In the result the page should have given me the names of pizzas stored in the class pizza but it is giving me only what is inside and tags. This is what I get When I inspect the html page it gives me this: enter image description here There is nothing between the and tags. Maybe it is unable to access elements from the class. Please help. -
Authenticating queries in Django Graphene custom nodes with filters and connections?
I'm working on a Django project using Graphene for GraphQL API implementation. I have a custom node called PoemNode which extends DjangoObjectType. I want to authenticate queries made to this node and also include filtering and pagination capabilities using filterset_class and connection_class respectively. I have already set up the authentication backend in Django and have the necessary packages installed. However, I'm unsure how to integrate the authentication logic into my custom node and how to use the filterset_class and connection_class for querying. class PoemNode(DjangoObjectType): class Meta: model = Poem interfaces = (Node,) filterset_class = PoemFilter connection_class = CountableConnectionBase Can anyone guide me on how to authenticate queries for the PoemNode and utilize the filterset_class and connection_class for querying with filtering and pagination capabilities? Thank you in advance for your help!