Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A form field is None in django and has an initial value
Hello I have this django's form: class userRequest(forms.Form): def __init__(self, *args, **kwargs): super(userRequest, self).__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Origin'}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Origin'}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Dest'}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Dest'}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'destination_address'})) date=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id'})) maxPrice=forms.FloatField(label='Max price:',widget=forms.NumberInput(attrs={'class':'data_aux data order','step': '0.1'}),required=False) CHOICES_ORDERTYPE =( ('NONE', 'NONE'), ('ASC', 'ASC'), ('DESC', 'DESC'), ) OrderType = forms.ChoiceField(label='Order',choices = CHOICES_ORDERTYPE,initial='NONE',required=False,widget=forms.Select(attrs={'class':'data order'})) CHOICES_ORDERBY =( ('PRICE', 'PRICE'), ('DURATION', 'DURATION'), ) OrderBy = forms.ChoiceField(label='Order by',choices = CHOICES_ORDERBY,initial='PRICE',required=False,widget=forms.Select(attrs={'class':'data order'})) And When I print the form in the post method I obtain that lat_Origin, lon_Origin, lat_Dest and lon_Dest are None: if request.method == 'POST': form = userRequest(request.POST) if form.is_valid(): print(form.cleaned_data) else: form = userRequest() {'lat_Origin': None, 'lon_Origin': None, 'lat_Dest': None, 'lon_Dest': None, 'origin_address': 'Lugar Diseminado, 82, 45312 Cabañas de Yepes, Toledo, España', 'destination_address': 'Calle San Roque, 28, 50324 Santa Cruz de Grío, Zaragoza, España', 'date': datetime.date(2021, 6, 12), 'maxPrice': 0.5, 'OrderType': 'NONE', 'OrderBy': 'PRICE'} I don't know how to fix this problem. Thank you -
Django ORM, Q statements and customized sorting
I am simplifying this for clarity. Let's say I had this function that finds Document records based on a requestedColor. def find_docs(requestedColor): docs = Document.objects.filter(Q(color=requestedColor) | Q(other_color=requestedColor)) I'd like to order the results so that Document found using color will appear before objects found with other_color. Is there a way to do this within the ORM query? I could not find a way to do that. Pointers will be appreciated. -
When running docker-compose, I get a permission error
I am new to deployment using docker so I believe that I am missing something vital here. I am trying to launch my app using docker/nginx and I have gotten to a stage where I am able to run the dev-environment as a container, but when I go to run the yml that I would use for deployment I get a PermissionError: [Errno 13] Permission denied: 'app/vol' Error. That is to say I can run docker-compose -f docker-compose.yml up --build and that provides me access to my app in the dev environment, but running docker-compose -f docker-compose-deploy.yml up --build causes the shown error message. This is from following along a tutorial online but adding extra dependencies and content to the Django project. I have made a version identical to the tutorial and that works, and when I check what I have against that version, nothing seems to differ. Any help would be massively appreciated. Terminal Error Output: proxy_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration proxy_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ proxy_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh proxy_1 | 10-listen-on-ipv6-by-default.sh: info: can not modify /etc/nginx/conf.d/default.conf (read-only file system?) proxy_1 | /docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh proxy_1 … -
DRF: What is the difference between serializer.save() in views.py vs instance.save() in serializers.py
I am confused regarding the DRF Serializer Documentation: For serializers, it was mentioned that, If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if Comment was a Django model, the methods might look like this: def create(self, validated_data): return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance From serializers.py code, it seems that .save() will update the instance in the database. However, it was later mentioned, Now when deserializing data, we can call .save() to return an object instance, based on the validated data. comment = serializer.save() Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance. serializer = CommentSerializer(data=data) # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) It seems that calling serializer.save() in views.py will update the 'comment' instance in the database. Calling instance.save() in serializers.py will also update the 'comment' instance in the database. My question is if there is a difference between the … -
How can I redirect to another page when someone send something back to me via callback url
Is there anyway to get the callback url parameter in current page? For example, currently I am in pageA, pageA have a qr code. When I scan the qrcode, another API partner will send back an authorization code as a parameter in my callback url. So how can I redirect to pageB when API partner send back an authorization code to my callback url? -
Django filter that also grabs a reverse ForeignKey, or better way to combine associated database info?
I am working on some backend django work that requires me to grab an Employee by filtering, but I also need to grab the EmployeeAddress object that is associated to the Employee. I was wondering if this was possible within a single query. I need the employees address, and employee info to be in a combined single dictionary, to access on the front end side with JS. I have models as such, Class Employee(models.model): first_name last_name email Class EmployeeAddress(models.model): employee = models.ForeignKey(Employee): street city state I have a view, that kinda does the job, but having trouble merging merging the two separate QuerySets into a single listed dictionary with all values. I was hoping there was just a way to get the EmployeeAddress without even writing the second query, and just grabbing that associated data in the first employee_list query? def employee_ajax_list(request): email = request.GET.get('email', None) employee_list = Employee.objects.filter(email=email) employee_address = EmployeeAddress.objects.filter(employee_id__in=employee_list).values( 'street', 'city', 'state',) # this chain kinda works, but splits them into 2 separate dictionaries? employee_info = list(chain(employee_list.values(), employee_address)) data = { 'employee_list': employee_info } return JsonResponse(data) Just looking on some advice to make this work a little smoother! -
request.POST.get('submit_target') empty
When i work with django form i use in my view request.POST.get('submit_target') to do something on variable if they are submitted. But when i use a HTML form i can't do that and request.POST.get('submit_target') is empty? it does not pass in if $(document).ready(function(){ console.log('fichier js ok'); $('.form_norefresh').submit(function(e){ e.preventDefault(); // avoid to execute the actual submit of the form. var post_url = $(this).attr("action"); var request_method = $(this).attr("method"); var form_data = $(this).serialize(); $.ajax({ url : post_url, type: request_method, data : form_data, }).done(function(resp){console.log('Submission was successful')}); return false; }); }) def accueil(request): if request.method == 'POST': if request.POST.get('submit_target') : import GV GV.target = request.POST.get('Key_target') if request.POST.get('submit_target'): import GV GV.weight = request.POST.get('Key_weight') return render(request, 'base.html', locals()) Target : <form class="form_norefresh" id="form_target" action="{% url 'accueil' %}" method="POST"> {% csrf_token %} <select name="Key_target" id="Key_target"> {% for column in columns_list_target %} <option> {{ column }} </option> {% endfor %}} </select> <input type="submit" name="submit_target" class="btn btn-primary" value="ok"/> </form> Weight : <form class="form_norefresh" id="form_weight" action="{% url 'accueil' %}" method="POST"> {% csrf_token %} <select name="Key_weight" id="Key_weight"> {% for column in columns_list_weight %} <option> {{column}} </option> {% endfor %}} </select> <input type="submit" name="submit_weight" class="btn btn-primary" value="ok"/> </form> -
Save page data after GET request?
Here is a GIF explaining the problem. Queries to the database are made with GET requests. When I make a GET request to pull additional data, all the checkboxes get unchecked. How can I save the checkbox state (session data, local storage) after those GET requests? -
Fastest way to get a not required specific record in database using Django
What would be the fastest way to get a specific record, that can or cannot exists, using Django. Some possible approaches: results = ModelExample.objects.filter(label="example1") if(results.exists()) item = results.first() results = ModelExample.objects.filter(label="example1") if(len(results) > 0) item = results.first() -
filter staff user in combo box in django admin
i want to show only staff user in combo box django admin how i most do it. Article(models.Model): author = models.Foreignkey(User) ... # other fields I want only staff use show in django admin combo box. -
Trouble with hosting a django app on digital ocean
When I visit http://[ip address], I get a 502 bad request error. /etc/systemd/system/gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=mainuser Group=www-data WorkingDirectory=/home/mainuser/Personal_Web ExecStart=/home/mainuser/Personal_Web/vr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myapp file: server { listen 80; server_name [ip address]; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/mainuser/Personal_Web; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When I run sudo tail -F /var/log/nginx/error.log, I get a connect() to unix:/run/gunicorn.sock failed (111: Connection refused) while connecting to upstream error. Im not sure why im getting this or how to fix it? -
Which should i choose? [closed]
I am learning beginner python from youtube. I want to develop a simple website or a web app. Which of the two, Django or Flask should I choose after learning python? ps: I am pursuing a beginner course on youtube -
Reverse lookup on a Django asymmetric 1:N relationship
In Django, what is the query manager associated for reverse lookup of a 1:N relationship? Let's say I have a simple Django model: class Entity(models.Model): name = models.CharField(max_length=100, primary_key=True) score = models.IntegerField(default=0) parent = models.ForeignKey("self", null=True, default=None, on_delete=models.CASCADE) and a few objects defined as follows: a = Entity.objects.create(name="A", score=5) b = Entity.objects.create(name="B", score=10, parent=a) c = Entity.objects.create(name="C", score=11, parent=a) If I want to find out all entities that have a score of less than 10, or any entities that have a parent whose score is less than 10, it is easy: Entity.objects.filter(Q(score < 5) | Q(parent__score < 5)) The above will match exactly one entity, "a", as expected. However, if I want to know all top-level (parent == None) entities whose score is more than 10, or who have children whose score is more than 10, how do I define the query? Entity.objects.filter(parent=None).(Q(score > 10) | Q(?__score > 10)) I need the matched answer to be the parent, not the child (and I need a queryset so I can refine it as needed). And if I exclude the non-parent entities then I cannot figure out the query to write. What should I write in place of the ? above so … -
django: needs to have a value for field "id" before this many-to-many relationship can be used
When saving a new entry into a Issue model for field cylinder, Django throws ValueError: "<IssueCylinder: anyone>" needs to have a value for field "id" before this many-to-many relationship can be used. I understand this is because I need to save the first model before I can use the id of the new record in the second model, but I’m struggling with how to actually make it do this. I’ve looked at examples but I can’t really relate them to my models. Your help will be nice for me. Here are that codes: views:- def issue(request): form=IssueForm() if request.method=='POST': form=IssueForm(data=request.POST,files=request.FILES) if form.is_valid(): confirm=form.save(commit=False) confirm.save() form.save_m2m() return redirect(cylinderListView) return render(request,'cylinderentry_form.html',{'form':form}) models: class CylinderEntry(models.Model): substachoice=[ ('Available','available'), ('Unavailable','unavailable'), ('Issued','issued'), ] cylinderId=models.CharField(max_length=50,primary_key=True) Availability=models.CharField(max_length=40,choices=substachoice,default="Available") EntryDate=models.DateTimeField(default=timezone.now) def __str__(self): return str(self.cylinderId) class IssueCylinder(models.Model): cylinder=models.ManyToManyField('CylinderEntry') userName=models.CharField(max_length=60,null=False) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: if self.cylinder.Availability=='Available': CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('Issued')) super().save(*args,**kwargs) def __str__(self): return str(self.userName) form: class IssueForm(forms.ModelForm): class Meta: model=IssueCylinder fields=['cylinder','userName','issueDate'] cylinder= forms.ModelMultipleChoiceField( queryset=CylinderEntry.objects.all(), widget=forms.CheckboxSelectMultiple ) userName=forms.CharField() issueDate=forms.DateInput() -
Python/Django string too large for String.io?
I am writing a small Django application in which I want to upload a file and use a parser to analyze this file. Unfortunately, files up to a certain size (don't know exactly the limit, but >3Gb anyway) can be parsed, but at a certain size the application just stops and crashes. I expect the program to be able to parse files up to 20 Gb. Here my code: import io def webinterfaceViews(request): context = {"graph": ""} if request.method == "POST": inputForm = BasicInputDataForm(request.POST, request.FILES) if inputForm.is_valid(): try: inputFile = request.FILES['file'].read().decode('UTF-8') streamInputFile = io.StringIO(inputFile) processInputfile(streamInputFile) ... The program never reaches the processInputfile function and returns no error when it is crashing. I am using the io.StringIO() function, because I use another package within the processInputfile function which uses a parser for these kind of files, but only parses files and not strings. So is there a way to fill the io.StringIO() with large strings or do I need to parse the large string myself without using an external parser? Or is there a problem with Django? -
Django CSRF error: is it a symptom or a root cause?
This is more sharing experience rather than a question. So, it might happen for Django to throw a CSRF error accompanied by a 403 Forbidden code. There are numerous posts out there suggesting more or less to add some sort of exception/exemption for the CSRF token/cookie. From my experience though, the CSRF error it is just a symptom and not the root cause. What can be the root cause? This error occurs even before executing any view code. Therefore, there is a high chance it is an API issue. You API path might not be correct. For example, you might ask for /api/x/data/ from the front-end whereas in reality the corresponding back-end api is /api/x/y/data/. I wish Django could throw a better error message. Feel free to share you experience w/ this error. -
automatic and unwanted default behavior in checkout
hello I hope you can help me currently I still have the default behavior which is activated while I would like the visitor to choose an address or create one so I always have the first address that the customer has create and not choose as you can see the default behavior is id = 1 the problem is that in practice whatever the choice I always have id = 1 def orders(request): order=Order.objects.all try: the_id=request.session['cart_id'] cart=Cart.objects.get(id=the_id) except: the_id=None return HttpResponseRedirect(reverse("carts:cart")) try: new_order=Order.objects.get(cart=cart) except: new_order=None return HttpResponseRedirect(reverse("carts:cart")) final_amount=0 shipping_a=request.POST.get("shipping_ad", 1) building_a=request.POST.get("building_ad", 1) if new_order is not None: new_order.sub_total=cart.total try: shop=new_order.shipping_ad=UserAddress.objects.get(id=shipping_a) except: shop=new_order.shipping_ad=None try: build=new_order.building_ad=UserAddress.objects.get(id=building_a) except: build=new_order.building_ad=None new_order.address=build.address new_order.address2=build.address2 new_order.city=build.city new_order.state=build.state new_order.country=build.country new_order.zipcode=build.zipcode new_order.phone=build.phone new_order.status="Finished" new_order.save() final_amount=new_order.get_final_amount if new_order.status=="Finished": new_order.save() del request.session['cart_id'] del request.session['items_total'] context={'order':order} template="orders/user.html" return render(request,template,context) @login_required def checkout(request): try: the_id=request.session['cart_id'] cart=Cart.objects.get(id=the_id) except: the_id=None return HttpResponseRedirect(reverse("carts:cart")) try: new_order=Order.objects.get(cart=cart) except Order.DoesNotExist: new_order=Order(cart=cart) new_order.cart=cart new_order.user=request.user new_order.order_id=id_generator() new_order.save() except: new_order=None return HttpResponseRedirect(reverse("carts:cart")) final_amount=0 if new_order is not None: new_order.sub_total=cart.total new_order.save() final_amount=new_order.get_final_amount try: address_added=request.GET.get("address_added") except: address_added=None if address_added is None: address_form=UserAdressForm() else: address_form=None currents_address=UserAddress.objects.filter(user=request.user) billing_address=UserAddress.objects.get_billing_address(user=request.user) context={'order': new_order ,'address_form':address_form, 'currents_address':currents_address,'billing_address':billing_address} template="orders/checkout.html" return render(request,template,context) -
How to create single Dockerfile for multiple containers without using docker-compose.yml?
Here I have 2 cases: Case 1: I have created a Django project called Counterproj which uses a default db called Sqlite3. I have dockerized this project using Dockerfile and pushed to Azure ACI which worked well in both the cases local and cloud. Case 2: The problem starts here when I migrated from Sqlite3 to PostgreSQL I have dockerized Django project using Dockerfile and docker-compose.yml with the services web and db these are working fine in my local but when I Push to Azure ACI the containers Counterproj_web:test and postgres:test are not able to communicate with each other and the instance is being terminated. Here my query is that can we create a single Dockerfile without using any docker-compose.yml for Django project containerization using PostgreSQL as db. If we can create single dockerfile please suggest me the best way which should run both in local and in cloud. Below are my Dockerfile, docker-compose.yml and database settings for your reference. Dockerfile: #syntax=docker/dockerfile:experimental # Python Version(Base Image) FROM python:3 # Set Envirment variable ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set Working directory WORKDIR /app # Add all the things into app ADD . /app # Instruct docker to install all … -
Linkedin Oauth2 giving null values, while integrating with django
I am trying to integrate login with linkedin, But I am not able to get profile picture, email address,profile url and other important details. here is what I have done till now. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'Client ID' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'Client Secret' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_liteprofile', 'r_emailaddress',] # SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['profile_url', 'email_address', 'headline', 'industry'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('emailAddress', 'email_address'), ('lastName', 'last_name'), ('displayImage', 'profilePictures'), ('publicProfileUrl', 'profile_url'), ] I also trying setting up pipelines like this SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' ) I tried different combinations with _,- etc but nothing works, all giving same output as { "auth_time": 1623340190, "id": "lIkisJgyIT", "expires": 5184000, "first_name": {"localized": {"en_US": "Akash"}, "preferredLocale": {"country": "US", "language": "en"}}, "last_name": {"localized": {"en_US": "Rathor"}, "preferredLocale": {"country": "US", "language": "en"}}, "email_address": null, "profilePictures": null, "profile_url": null, "access_token": "fulltokenid" token_type": null } Also there is one confusion, when I logged in with linkedin on my application and again try to login with linkedin it's seniding and obvious error that user already authenticated, I am not sure how I set up the condition , if user already authenticated then user will not be able to try login again. … -
I am using CreateView in django but getting error- The view blog.views.PostCreateView didn't return an HttpResponse object. It returned None instead
I am having a post model with a user having OneToMany Relationship with inbuilt user model for authentication my urls.py from django.contrib import admin from django.urls import path, include # from views import PostView from . import views urlpatterns = [ path('', views.PostView.as_view(), name='blogHome'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), path('post/new/', views.PostCreateView.as_view(), name='post-create'), path('about/', views.about, name='about') ] my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Post from django.views.generic import ( ListView, DetailView, CreateView ) # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html') class PostView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_published'] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView): model = Post fields = ['title', 'body'] #to add author before validation def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Post Model from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.TextField() date_published = models.DateTimeField(default=timezone.now) def __str__(self): return self.title I am using post_form.html as the template name post_form.html {% extends 'blog/layout.html' %} {% load crispy_forms_tags %} {% block body %} <div class="content-section … -
how to solve two model circular dependency in django
I have a file in django project models.py: from django.db import models class Product(models.Model): id = models.IntegerField(unique=True,primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length= 100000) price = models.FloatField() count = models.IntegerField(default=1) file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True) offer= models.BooleanField(default=False) def __str__(self): return self.title class ProductImage(models.Model): property_id = models.ForeignKey(Product,on_delete=models.CASCADE) image = models.FileField(upload_to='pics') def __str__(self): return '%s-image' % (self.property_id.title) It says that ProductImage is not defined, which is clear because it is defined below. If I tries to move it up above like this: class ProductImage(models.Model): property_id = models.ForeignKey(Product,on_delete=models.CASCADE) image = models.FileField(upload_to='pics') def __str__(self): return '%s-image' % (self.property_id.title) class Product(models.Model): id = models.IntegerField(unique=True,primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length= 100000) price = models.FloatField() count = models.IntegerField(default=1) file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True) offer= models.BooleanField(default=False) def __str__(self): return self.title Now it says Product is not defined . Can any body tell me the remedy? What I have done so far? I tried to make a separate file called img.py and class ProductImage wrote there.Then I tried to import it here. Now it says: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File … -
Navbar not showing properly
The navbar is not showing properly. It's not becoming how it's shown on the bootsrap website. I have copied the following code from the Navbar section in Bootstrap <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> [enter image description here][1] -
Using Django and Charts.js, no data sent to template from view
I'm using charts.js with Django and I have an issue with the data I'm sending from the view to the chart in the template. Here is my code: model.py (only relevant fields): STATUS = ((0,"Tender"), (1,"Live"), (2,"Archived")) class Project(models.Model): project_number = models.CharField(max_length=5, unique=True) project_name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=200, unique=True) project_value = models.DecimalField(max_digits=7, decimal_places=0) project_designer = models.ForeignKey(User, on_delete=models.PROTECT, default=0, related_name='project_designer') project_manager = models.ForeignKey(User, on_delete=models.PROTECT, default=0, related_name='project_manager') is_fire = models.BooleanField(default=False) project_status = models.IntegerField(choices=STATUS, default=0) #progress progress_abdrawings = models.IntegerField(default=0, validators=[MaxValueValidator(100),MinValueValidator(0)]) @property def abdrawings_remaining(self): remaining = 100 - self.progress_abdrawings return remaining class Meta: ordering = ['-project_number'] def __str__(self): return self.project_number views.py (only relevant fields): I only want to display two fields on this chart: progress_abdrawings and abdrawings_remaining def ProjectDetail(request, slug): model = Project template_name = 'detail-project.html' project = get_object_or_404(Project, slug=slug) return render(request, 'detail-project.html',{'project':project}) class ChartView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard.html') class ChartAbProgress(APIView): authentication_classes = [] permission_classes = [] model = Project def get(self, slug): self.slug = slug labels = ['COMPLETED', 'REMAINING'] chartLabel = "FAB DRAWINGS" chartdata = [] queryset = Project.objects.filter(slug=self.slug).order_by('-project_number') for project in queryset: chartdata.append(project.progress_abdrawings) chartdata.append(project.abdrawings_remaining) abProgData = { "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, } return Response(abProgData) url.py (only relevant fields): urlpatterns = [ # The home page path('', views.DashView.as_view(), … -
How can I show in cart items in my index view?
I'm working on an ecommerce app, and I have a template that displays all my products. I want to show how many of the item are in the cart. But I can't seem to figure out how to get that information from my for loop. Code: template {% for product in products %} {{product.title}} - {{product.quantity_in_cart}} {% endfor %} (As of right now, product.quantity_in_cart does nothing. I would like it to show how many of this product are in the cart) view def product_index(request): title = "My Products" products = Product.objects.all() order = get_cart(request) cart = Order.objects.get(id=order.id, complete=False) items = cart.orderitem_set.all() context = { 'title' : title, 'products' : products, 'cart' : cart, 'items': items } return render(request, "store/product_index.html", context) models class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) complete = models.BooleanField(default=False, null=True, blank=False) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Product(models.Model): name = models.CharField(max_length=64) slug = models.SlugField(unique=True, null=True) description = RichTextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField() -
Django and Microsoft azure services
Is it possible to integrate Microsoft azure services like Custom vision in the Django app? I want to build a web app where users can upload images and train a model using those images.