Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add quantity to products in cart django
so I am trying to add a option to set quantity for my products before I add them to the cart and while they are inside the cart something like thisexample my models.py class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user=None): user_obj = None if user is not None: if user.is_authenticated: user_obj = user return self.model.objects.create(user=user_obj) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) products = models.ManyToManyField(Product, blank=True) total = models. DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return str(self.id) def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs): if action == 'post_add' or action == 'post_remove' or action == 'post_clear': products = instance.products.all() total = 0 for x in products: total += x.price if instance.subtotal != total: instance.subtotal = total instance.save() m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through) def pre_save_cart_receiver(sender, instance, *args, **kwargs): if instance.subtotal > 0: instance.total = Decimal(instance.subtotal) * Decimal(1.08) # 8% tax else: instance.total = 0.00 pre_save.connect(pre_save_cart_receiver, sender=Cart) this is my views.py … -
How to align components in the bootstrap Navbar Properly?
I am developing an e-commerce website, but I cannot align the components in my navbar properly. I just copied the navbar code from the bootstrap site and pasted it inside my main.html file. Here is the navbar code: Ecom <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'store' %}">Store<span class="sr-only"></span></a> </li> </ul> <div class="form-inline my-2 my-lg-0 "> <a href="#"class="btn btn-warning">Login</a> <a href="{% url 'cart' %}"> f <img id="cart-icon" src="{% static 'images/cart.png' %}"> </a> <p id="cart-total">0</p> </div> </div> </nav> Below is the Navbar image (all components are jumbled):- I want to align the login button and cart image symbol to right and also reduce the size of the navbar and login button -
Pylint does not acknowledge a module
I'm new to Django and haven't used much of the Python tooling. The following line of code is being flagged by Pylint, despite working without issue. # main/management/commands/send_policy_notifications.py from main import models No name 'models' in module 'main'pylint(no-name-in-module) The file structure follows: . ├── Pipfile ├── Pipfile.lock ├── .env ├── .pylintrc ├── main │ ├── __init__.py │ ├── access_conditions.py │ ├── admin.py │ ├── apps.py │ ├── authentication.py │ ├── flags.py │ ├── management │ │ └── commands │ │ └── send_policy_notifications.py │ ├── tests.py │ ├── urls.py │ └── views.py └── manage.py How can I configure Pylint to acknowledge that main contains models? I'm using Visual Studio Code. -
How to use link in Django template
I am a beginner in Django . I have done a project . I use bootstrap in this but css is not working <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" There is any way to convert this link in Django format ? -
How to fix exeption when I try to create a record in DB in admin panel: 'InMemoryUploadedFile' object has no attribute '_committed'?
How to fix exeption when I try to create a record in DB in admin panel: 'InMemoryUploadedFile' object has no attribute '_committed'? I am new to django and have absolutely no idea where to dig. The first attemp was succesfull, but that was before adding a bunch of code to the project. Without an ImageField everything works well. I catch exeption only when I try to save image model.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User class TripPost(models.Model): title = models.CharField(max_length=150) location = models.CharField(max_length=150) body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) add_inform = models.CharField(max_length=80, blank=True) image = models.ImageField(upload_to='trips/%Y/%m/', blank=True) def __str__(self): return '{}'.format(self.title) admin.py from django.contrib import admin from .models import TripPost admin.site.register(TripPost) media path from setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.contrib import admin from django.urls import path from .views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('trips', TripsGet.as_view(), name='trips_url'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Exeption in CMD File "E:\lab1-15\venv\lib\site-packages\django\db\models\base.py", line 780, i n save_base updated = self._save_table( File "E:\lab1-15\venv\lib\site-packages\django\db\models\base.py", line 850, i n _save_table values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, F alse))) File "E:\lab1-15\venv\lib\site-packages\django\db\models\base.py", line … -
Why is this Django Template not receiving the context?
I'm using a simple view to render an 'index.html' page, and pass a JSON in the context variable. def index(request): """Homepage. Calls are made to other classes from here.""" ytv = YoutubeVideos() user = request.GET.get('user', '') videos = {'name': 'filler data here'} if user != '': videos = ytv.get(request=request, channel_data=1) print(videos) return render(request, 'index.html', context=videos) return render(request, 'index.html', context=videos) I've confirmed it is going through the first return, with the videos context containing JSON data. It is printing in the console. I also have the index.html file, which contains: ... {{videos|json_script:'name'}} <script> 'use strict'; var videos = JSON.parse(document.getElementById('name').textContent); ... I've tried several variations on the way to get the JSON data in the Javascript including: <input type="hidden" id="myVar" name="videos" value="{{ videos }}"> Then getting the value in javascript this way, var myVar = document.getElementById("myVar").value; The problem is when the html is rendered it becomes this (screenshot of Source): Basically, the variable looks like it doesn't exist when it gets rendered. Any help would be appreciated. -
How can I link the column of a model to another using Django ForeignKey
I have the below models class Supplier(models.Model): supplierName = models.CharField(max_length=64) zone = models.IntegerField() class Contact(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.SET("Company Deleted"), related_name="supplierC") name = models.CharField(max_length=64) On the html <select name="supplier" id="supplier"> <option value="1">Supplier 1</option> <option value="2">Supplier 2</option> </select> If I select supplier 1,and post the form to the view, I will have to first get the Supplier whose id = 1, then use the obtained query to fill the database for contact def contactForm(request): if request.method == "POST": supplier = Supplier.objects.get(pk=request.POST['supplier']) mydata ={} mydata['supplier'] = supplier mydata['name'] = request.POST['contact-name'] new_contact = Contact(**mydata) new_contact.save() Is there a way to avoid supplier = Supplier.objects.get(pk=request.POST['supplier']) For instance in our model do something like supplier = models.ForeignKey(Supplier.id, on_delete=models.SET("Company Deleted"), Where by in while creating the new record for Contact, we do directly as shown below def contactForm(request): if request.method == "POST": mydata ={} mydata['supplier'] = request.POST['supplier'] mydata['name'] = request.POST['contact-name'] new_contact = Contact(**mydata) new_contact.save() Any help? -
Django always failed when login as user, while superuser (admin) always success
So, I've tried a couple of times to register and back to login. Always failed to log in except for superuser or admin. Already checked in Django admin that the user that I have registered already there. There is no error message in the terminal when login or register a user. Except for the error message that I've created in views.py if log in unsuccessful. So, let's take a look into my code. First views.py from django.contrib.auth import authenticate, login, logout def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authenticate successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: context = { "message": "Invalid username and/or password" } return render(request, "page/login.html", context) else: return render(request, "page/login.html") And below is the template. <div class="login-register"> <div class="head"> Log in to Explore </div> <form action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="form-floating mb-3"> <input type="text" class="form-control" id="username" name="username" placeholder="Username""> <label for="username">Username</label> </div> <div class="form-floating mb-3"> <input type="password" class="form-control" id="password" name="password" placeholder="Password"> <label for="password">Password</label> </div> <div class="d-grid gap-2"> <input class="btn btn-outline-success" type="submit" value="Login"> </div> <div id="log-reg"> <a href="{% url 'register' %}">Sign Up</a> … -
Order a dict in python when keys are list
I need to order the following dict in asc order depends on the 'progreso' value. How can I do it? {10: [{'titulo': 'Apropiación Digital'}, {'progreso': '50'}, {'estado': 'En curso'}], 13: [{'titulo': 'Así se ve mi negocio'}, {'progreso': '0'}, {'estado': 'En espera'}], 8: [{'titulo': 'Bioseguridad'}, {'progreso': '50'}, {'estado': 'En curso'}], 15: [{'titulo': 'Desarrollo de oportunidades de negocio'}, {'progreso': '0'}, {'estado': 'En espera'}], 9: [{'titulo': 'Formalización'}, {'progreso': '0'}, {'estado': 'En espera'}], 11: [{'titulo': 'Hagamos cuentas'}, {'progreso': '50'}, {'estado': 'En curso'}], 7: [{'titulo': 'Mujer emprendedora'}, {'progreso': '100'}, {'estado': 'Finalizado'}, {'puntaje': 100}, {'fecha': datetime.datetime(2021, 3, 31, 15, 19, 20)}, {'puntos': 170}], 12: [{'titulo': 'Precio y competencia'}, {'progreso': '0'}, {'estado': 'En espera'}], 14: [{'titulo': 'Servicio al cliente'}, {'progreso': '0'}, {'estado': 'En espera'}], 16: [{'titulo': 'Test'}, {'progreso': '0'}, {'estado': 'En espera'}]} -
Authorizing user for further part but if info is wrong notify him that his/her acc is deleted
I'm new to the Django framework. after the user is logged in he fills a form and that data is sent to admin which can be done through modelform. what I actually want to do is this data should be viewed by admin and if the info provided in the form is wrong/misguided then the admin deletes his/her account notifying him to fill the valid info in form. How can it be done? -
Getting error I don't understand in my template
error: 'Manager' object is not iterable This is what it shows: 51 <div class="row"> 52 <div class="ads"> 53 {% for ad in ad_item %} 54 {% ifequal ad.redirect 'False' %} 55 <img src="{{ ad.pic }}"></img> 56 {% endifequal %} 57 {% ifnotequal ad.redirect 'False' %} 58 <a href="{{ ad.redirect }}"><img src="{{ ad.pic }}"></img></a> 59 {% endifnotequal %} 60 {% endfor %} 61 </div> 62 </div> This is my view: from django.shortcuts import render, get_object_or_404 from django.views.generic.list import ListView from videos.models import video, ad from django.template import RequestContext def show_vid (request, pk, pkv): video_ = get_object_or_404(video, pk=pk) ad_item = ad.objects return render (request, 'video.html', {'video_': video_, 'ad_item': ad_item}) This is my template: <div class="row"> <div class="ads"> {% for ad in ad_item %} {% ifequal ad.redirect 'False' %} <img src="{{ ad.pic }}"></img> {% endifequal %} {% ifnotequal ad.redirect 'False' %} <a href="{{ ad.redirect }}"><img src="{{ ad.pic }}"></img></a> {% endifnotequal %} {% endfor %} </div> </div> What's the error, and what do I need to fix? -
How to ensure async operation executed during transaction has access to data written within transaction?
I have transaction within which I send pub/sub message. Pub/sub message handler should read data written during transaction. It seems like sometimes pub/sub handler is being executed before transaction completion which results in missing data. How can I ensure that pub/sub handler has required data? I am using python + django and it provides on_commit handler which is performed after transaction committed. But if I send pub/sub message from there then it is possible that transaction commits but for whatever reason sending pub/sub message fails and then I end up in a state when database is updated but pub/sub handler was never executed. Any other mechanism I can use for this? -
django.db.utils.OperationalError: no such function: JSON_VALID
I literally don't know how deal with it and how it is happening I am getting this error when i run python manage.py migrate migrations was without error Mycode models.py from django.db import models import uuid from django.contrib.auth.models import User # Create your models here. class Orders(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) products = models.CharField(max_length=6000) zip_code = models.IntegerField() address = models.CharField(max_length=600) city = models.CharField(max_length=600) state = models.CharField(max_length=600) email = models.EmailField() date = models.DateTimeField(auto_now=True) views.py from django.core import serializers @login_required def checkout(request): user = User.objects.get(pk=request.user.id) cartItems = Cart.objects.filter(user=user) cartJson = serializers.serialize('json', cartItems) print(cartJson) price = 0 for cartItem in cartItems: price = price + cartItem.cart_item.price * cartItem.quantity message = "" if request.method=="POST": products = request.POST['products'] email = request.POST['email'] address = request.POST['address'] city = request.POST['city'] state = request.POST['state'] zip_code = request.POST['zip'] order = Orders(products=products, user=user, email=email, address=address, city=city, state=state, zip_code=zip_code) order.save() message = "Order Successfully Placed" cartItems.delete() context = { 'message' : message, 'cartItems' : cartItems, 'price' : price } return render(request, 'ecom/checkout.html', context) If you are able to solve the issue then answer and along with it also tell me any issue in my code or any bad practice in my code If at all answerer 😂! … -
Local host not opening up another page withing local host
i have a local host that i am running my mock website on and i am using python and django as well. i wanted the local host open another link which is the other page i have set up but how would i able to let the page that runs on local host to open the other link which should open up another page to the sign up page! would i need another local host server to open the other page? i have already tried redirect the other page to another local host number but still no avail. i hope i made myself clear any help would do. -
Use same login credentials for both app where Django is backend, more like SSO
I have a web app, which uses Django as a backend. Due to special requirement, we had to build a UI on the Django side as well. More like the existing Django Admin with limited functionality. We have two web app, one of which is developed using angular and the other using simple ajax and jinja template on Django. Now I need to redirect from the Web app at a click off button from the Angular app to the Django based web app passing the credentials as well side by side. We are trying to inhibit more of a single sign-on like feature. Is there a simple and efficient way to pass the credentials? Should I take the credentials from local storage where the other app has stored the credentials? -
How to setup OIDC for Django / Django-Rest-Framework
I need to build a Django web-app. My web-app needs to support authentication and authorization using OpenID Connect. It is my first time doing this. I have a service which requires clientId and clientSecret and the typical endpoint urls. I have no idea what library to use and how to configure it. I'm using Django 3.1.7. I'm open to answer questions if I missed something -
How do I count() only the distinct values on a specific field when returning a queryset
I have a function that returns a queryset that is a list of records that I would like to return the count() of the records which it does BUT I want to only count the distinct values from a specific field. I can easily do this in a SQLite query but cant seem to get it in Django. Here is the SQLite Query that works BUT I need to do this in a Django View: SELECT DISTINCT Host FROM inventory_scandata WHERE Project_Assigned LIKE '%Hooli%' AND Environment LIKE '%PROD%' Here is my current function that returns the non-distinct count: def HooliProject(request): prodAssets = ScanData.objects.filter(Q(Project_Assigned__icontains="Hooli_1") & (Q(Environment__icontains="PROD"))) prodAssetsHosts = prodAssets.distinct() prodAssetsDistinct = prodAssetsHosts.distinct() prodAssetsCount = prodAssetsDistinct.count() context = { 'prodAssets': prodAssets, 'prodAssetsCount': prodAssetsCount } return render(request, 'HooliProject.html', context) -
How to change language in Swagger-ui docs (Multi-lingual support)
Is there a way of changing swagger UI documentation to any language in Django -
Django SMTP not working even port is open
Hi I am using Django Version 3.1 and using send_mail() fnction of django. It is working perfectly fine locally and emails are being sent. But When i try it on VM instance of GCP it do not send emails instead i get error of Network Unreachable. all ingress and engress traffic is allowed in my instance i even then made a new rule for port 587 but still cant send email. All other python requests are working fine. I tested with telnet and my port is open as well. Any Help will be really appreciated. -
Profile() got an unexpected keyword argument 'user' while extending django's User model
Here I have extended django's user model with profile model and i want to add this fields to user model. Following are the files. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user_ref = models.OneToOneField(User, on_delete=models.CASCADE) pr1_points = models.IntegerField(default=0) pr2_points = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): user = instance if created: profile = Profile(user=user) profile.save() @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() register function in views.py is as follows : ''' def postregister(request): if request.POST: first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') if password1 == password2: if User.objects.filter(username=username).exists(): messages.error(request, 'Username is Taken Please Try Again') return render(request,'signup.html') elif User.objects.filter(email=email).exists(): messages.error(request, 'Email is Taken Please Try Again') return render(request,'signup.html') else: user = User.objects.create_user(username=username, first_name=first_name, last_name=last_name, email=email, password=password1) user.save() print('You are registered successfully, Please sign to continue.') return redirect('login') else: messages.error(request, 'Password is not matching Please Try Again') return render(request,'signup.html') else: return redirect('register') ''' so while creating new user it is giving error as: Profile() got an unexpected keyword argument 'user'. SO please anyone know the answer help me with this. -
Django pass a url kwarg into a form.Form
I'm trying to get initial values for a form.Form class form from url. urls.py path('nueva/<client_id>/', new_check_view, name='nueva valoración'), views.py def new_check_view(request, client_id): my_form = NewCheckForm() # print (client_id) if request.method == "POST": my_form = NewCheckForm(request.POST) if my_form.is_valid(): Check.objects.create(**my_form.cleaned_data) else: print(my_form.errors) context = { "form": my_form } return render (request, 'checks/new-check.html', context) forms.py class NewCheckForm(forms.Form): user_id = forms.ModelChoiceField( label='Nombre', queryset= Client.objects.all(), initial=client_id, ) However, I don't get how to pass that kwargs from the view to the class form. -
update view don't save the bank
I wanted to know how I do it here to update this form in the bank, I am using 2 forms with different models and every time I try to save the information they are not exchanged and I get an invalid form error. class PacienteUpdateView(UpdateView): queryset = Endereco_pacientes.objects.all().select_related('cpf') form_class = PacientesModelForm second_form_class = EnderecoPacientesModelForm template_name = 'pacientes/pacientesForm.html' #get_success_url = '.' def get_context_data(self, **kwargs): context = super(PacienteUpdateView, self).get_context_data(**kwargs) context['form'] = self.form_class(instance=self.object.cpf) context['form2'] = self.second_form_class(instance=self.object) print(context['form']) return context I can already display the information in HTML, but I cannot update I thank the attention -
Django Management Command Generating Model Entries Corrupts File if File Is the Same on Each Entry
I have a custom management command in Django that generates an email to be added to the "django-mail-queue" app MailerMessage model. This tool reads from an existing table for information. However I am having issues with attachments where the first one, the attachment is fine, but the second one the attachment is corrupted. My belief is that Django is queuing up all the SQL commands and executing them all at once and thus reading the attachment file all at the same time for every entry. I think this is causing a race condition that is corrupting the second attachment. This is the code for send_to_user in send_to_users: msg = MailerMessage() msg.subject = campaign.subject msg.from_address = from_address msg.to_address = send_to_user.email msg.html_content = f"some content" # ATTACH THE ATTACHMENTS if attachments: for attachment in attachments: msg.add_attachment(attachment=attachment.file_attachment) msg.save() How do I get it to save directly without causing this race condition? Shouldn't msg.save() save to the database right away at the end of the for loop and then process the next one? -
Convert Base64 format Images to single pdf file and store it to django model
I have several images in data: format I need to convert them into a single pdf file in landscape mode and store them in Django model filefield. How can I achieve this in Python? -
How do I fitler the intial table using django-tables2 and django-filter?
I'm using django-tables2 and django-filter to list employees from a model. I'm having trouble filtering the initial table rendered. It's including all records. I want the initial table to only include employees where status=1. Then, have the filter take over. views.py from .models import Employee from .tables import EmployeeTable from .filters import EmployeeFilter from .forms import EmployeeSearchForm class EmployeeListView(SingleTableMixin, FilterView): model = Employee table_class = EmployeeTable template_name = 'employees/employee_list.html' filterset_class = EmployeeFilter def get_table_data(self): return Employee.objects.filter(status=1) filters.py: from django.db.models import Value, Q from django import forms from .models import Employee class EmployeeFilter(django_filters.FilterSet): search = django_filters.CharFilter(label='Search', method='search_filter') inactive = django_filters.BooleanFilter(widget=forms.CheckboxInput, label='Inactive', method='include_inactive') def search_filter(self, queryset, name, value): return queryset.annotate(fullname=Concat('first_name', Value(' '), 'last_name')).filter( Q(fullname__icontains=value) | Q(g_number__icontains=value) ) def include_inactive(self, queryset, name, value): expression = Q(status__in=[1,2,5]) if value else Q(status__in=[1,5]) return queryset.filter(expression) class Meta: model = Employee fields = ['search', 'inactive'] tables.py: from django.utils.html import format_html from django.urls import reverse import django_tables2 as tables from .models import Employee class EmployeeTable(tables.Table): full_name = tables.Column(order_by=("first_name", "last_name")) g_number = tables.Column(linkify=True) selection = tables.columns.CheckBoxColumn( accessor='pk', attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False ) term = tables.Column(verbose_name=("Action"), empty_values=()) class Meta: model = Employee template_name = "django_tables2/bootstrap.html" fields = ("selection", "g_number","full_name", 'org', 'job', 'status', 'term') attrs = { "class": …