Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update a value that is the sum of two range values
I recently started to work on Django and JavaScript, and currently working on Range items. I successfully managed to have two functioning scales and to update their value next to them each time the user is modifying them. <p>You have <span id="demo1"></span> spent dollars on this item.</p> <div class="input-group"> <p class="input-group-text">0<input type="range" id="myRange1" name="myRange" min="0" max = "120" step="5" class="form-range"></p> <p class="input-group-text"> 120</p> </div> var slider1 = document.getElementById("myRange1"); var output1 = document.getElementById("demo1"); output1.innerHTML = slider1.value; slider1.oninput = function() { output1.innerHTML = this.value; } <p>You are spending<span id="demo2"></span> dollars on this item.</p> <div class="input-group"> <p class="input-group-text">0<input type="range" id="myRange2" name="myRange" min="0" max = "120" step="5" class="form-range"></p> <p class="input-group-text"> 120</p> </div> var slider2 = document.getElementById("myRange2"); var output2 = document.getElementById("demo2"); output2.innerHTML = slider2.value; slider2.oninput = function() { output2.innerHTML = this.value; } Now, what I am trying to get is to have a value that is the sum of the two values, and that is updating as soon as the user is modifying one of the two scales. I tried the following: <p>You have spent <span id="demo_total"></span> dollars in total.</p> var value_total = 0 var output_total = document.getElementById("demo_total"); output_total.innerHTML = 120 // Display the default slider value value_total.value = function() { output_total.innerHTML = parseInt(output1.innerHTML) + … -
How do I get the client Remote Port number in a Django?
I know I can use request.META['REMOTE_ADDR'] to get the client's IP in my django view function. However, I have no idea how to get the client remote port number. For example, you can see your own remote port number on the site below: https://www.myip.com/ Remote Port MY VIEW PY: if request.user.is_authenticated: gelenIleti = request.META.get('HTTP_X_FORWARDED_FOR') if gelenIleti: ip = gelenIleti.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') portNumarasi = request.META['SERVER_PORT'] logger.info(' ' + 'LOG KAYDI :' + ' ' + ' KULLANICI : ' + request.user.username + ' ' + ' IP : ' + ip + ' ' + ' SERVER PORT : ' + portNumarasi) -
What do I set date_field to in DayArchiveView for django-recurrence?
I have a model for booking slots and a DayArchiveView in django. I am using django-recurrences to make my events recurrent https://django-recurrence.readthedocs.io/en/latest/index.html views.py class ClubBookingArchiveView(DayArchiveView): queryset = BookingSlot.objects.all() date_field = "recurrences" #what should I put here? allow_future = True allow_empty = True models.py class BookingSlot(models.Model): start_time = models.TimeField("Start Time") end_time = models.TimeField("End Time") recurrences = RecurrenceField() I am wondering what I should set the date_field to in my DayArchiveView. Or if anyone can think of anyway I can get around this, is there like a get_date_field() I can override or something, or will I have to generate a view completely from scratch? -
Can't write to a file with Django in Nginx
I have deployed a Django web app using uWSGI and Nginx, but the app runs into an error when trying to create a file inside a specified folder. Inside my views file, I specify a function which writes to a file using "with open". This function writes the file to a folder named 'output' inside the Django project folder. When I run the Django server, all the functionality works well, but, when I run the Nginx server, it gives me an error exactly where the "with open" is. I have already tried to switch the ownership of the 'output' folder, but it did not work. Also tried to run 'sudo chmod -R www-data:www-data' with my whole project folder as an attribute, but I had no success. I would please like to have more insight on how to fix this issue. The problem is likely about my permissions, but I have tried everything in my knowledge to fix it but it did not work. In attachment, I am sending an image of the output of the 'ls -la' command inside my Django project folder. Also, the guide I have followed can be found here: https://tonyteaches.tech/django-nginx-uwsgi-tutorial/. output of the ls -la command … -
How to use django-select2 in wagtail?
I have a model with many-to-many relation. And for wagtail I used the following: from django_select2.forms import Select2MultipleWidget from wagtail.admin.edit_handlers import FieldPanel panels = [ FieldPanel('field_name', widget=Select2MultipleWidget ] But select2 is not showing up. What can be done? -
Django Models get value from a foreign key
I have the following model: class Check (models.Model): user_id = models.ForeignKey(Client, on_delete=models.CASCADE) client = Client.objects.get(pk=1) #change id according to user_id client_birth = client.birth client_gender = client.gender What I need is to get those birth and gender values from model Client, but according to the value id set on user_id. Is that possible? -
I cannot install Django in my Virtual Environment
I wanted to install Django in my virtual environment (which was completely working), but got this whole lot of errors. Anyone know what to do? I just typed this in PowerShell: pipenv install django And got this: Error: An error occurred while installing django! Error text: Collecting django Using cached Django-3.1.7-py3-none-any.whl (7.8 MB) ERROR: THESE PACKAGES DO NOT MATCH THE HASHES FROM Pipfile.lock!. If you have updated the package versions, please update the hashes. Otherwise, examine the package contents carefully; someone may have tampered with them. django from https://files.pythonhosted.org/packages/b8/6f/9a4415cc4fe9228e26ea53cf2005961799b2abb8da0411e519fdb74754fa/Django-3.1.7-py3-none-any.whl#sha256=baf099db36ad31f970775d0be5587cc58a6256a6771a44eb795b554d45f211b8 (from -r c:\users\vojtěch\appdata\local\temp\pipenv-e9otm_0m-requirements\pipenv-sj4h6g3_-requirement.txt (line 1)): Expected sha256 baf099db36ad31f970775d0be5587cc58a6256a6771a44eb795b554d45f211b8 Got 764ad5e659cd3a7740b314806b39c67501c6136a21d23652515df3bfb4023d76 -
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