Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Models Choices
I have a tuple of choices for a model like this and I want to use the choices to be displayed in a Navbar, this is what I currently have: models.py OPCIONES_EVENTO = ( ('A', 'Aniversario'), ('C', 'Cumpleaños'), ('P', 'Padre'), ('M', 'Madre'), ('B', 'Bautizo') ) class Productos(models.Model): nombre = models.CharField(max_length=200, null=True) precio = models.FloatField() precio_descuento = models.FloatField(blank=True, null=True) categoria = models.CharField(choices=OPCIONES_CATEGORIA, max_length=1) etiqueta = models.CharField(choices=OPCIONES_ETIQUETA, max_length=1) tipo = models.CharField(choices=OPCIONES_TIPO, max_length=1, blank=True, null=True) evento = models.CharField(choices=OPCIONES_EVENTO, max_length=1, blank=True, null=True) imagen = models.ImageField() slug = models.SlugField() descripcion = models.TextField() sku = models.CharField(max_length=20, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Productos" def __str__(self): return self.nombre def get_absolute_url(self): return reverse('detalle-producto', kwargs={'slug': self.slug}) def get_agregar_al_carrito_url(self): return reverse('agregar-al-carrito', kwargs={'slug': self.slug}) def get_quitar_del_carrito_url(self): return reverse('quitar-del-carrito', kwargs={'slug': self.slug}) def get_filtro_evento(self): return reverse('filtro-evento', kwargs={'evento': self.evento}) views.py class FiltroEvento(ListView): template_name = 'filtro-evento.html' model = Productos def get_queryset(self): if self.kwargs['evento'] == 'B': evento = 'B' return Productos.objects.filter(evento=evento) elif self.kwargs['evento'] == 'C': evento = 'C' return Productos.objects.filter(evento=evento) urls.py path('productos/<evento>', views.FiltroEvento.as_view(), name='filtro-evento') This is part of the code for the html template: <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'productos' %}">Todos <span class="sr-only">(current)</span> </a> </li> {% for producto in object_list %} {% if producto.get_evento_display %} … -
How to authenticate user and admin at the same time in a django project
I am new to django and i am trying build a web application. I am using auth functions to authenticate users and using a custom made admin panel. I want to know if it is possible to authenticate user and admin at the same time in the project without using incognito window -
I run my code and I am having error "django.urls.exceptions.NoReverseMatch
This is code I am getting error. I am trying to add fertilizer-name URLs in my template and I am having an error "Django.urls.exceptions.NoReverseMatch: Reverse for 'fertilizer-name' not found. 'fertilizer-name' is not a valid view function or pattern name." urls.py:from django.urls import path from .views import findex,predict_chances,view_results app_name = "fertilizer" urlpatterns=[ path('', findex, name='fertilizer-name'), path('fertilizer/',predict_chances,name='submit_prediction'), path('fertilizer/results/',view_results,name='results'), ] views.py: def findex(request): context={'name':'fertilizer'} return render(request,'fertilizer/index.html',context) templates: <div class="col-md-6 col-sm-12"> <div class="shop-cat-box">`enter code here` <a href="{% url 'fertilizer-name' %}"><img class="img" src="{% static 'images/cyp/3.png' %}" alt="" /></a> </div> -
Django rendering and submitting forms that are passed to from another form
I want to accomplish the following user signs up in a sign up form user email is passed as context to a verification code entry form user is sent a verification code user enters the verification code in the verification code entry form verification code is confirmed on the backend with the email sent from the first form context So what I'm trying to do is that when the user accesses example.com/signup and fill out the form, I then render the verification_code_entry_form, and then they enter their verification code there. Finally once they submit that, they are redirected to login. However the difference between render and redirect is tripping me up. in urls.py path('signup', views.signup_page, name='signup'), path('confirm_account', views.confirm_account, name="confirm_account"), path('send_verification_code', views.send_verification_code, name="send_verification_code"), in views.py def signup_page(request): form = CreateUserForm(request.POST or None) context = { 'form': form } if form.is_valid(): new_user = form.save(commit=False) password = form.cleaned_data.get('password') email = form.cleaned_data.get('email') try: ...backend authentication client work goes here except Exception as e: ...catch exceptions here messages.error( request, f'An unexpected error has occured.' ) return render(request, 'accounts/signup.html', context) else: # Create user and verifications new_user.save() # Save the email in the context to use in the verification form context['email'] = email form = AccountConfirmationForm(request.POST … -
Python install requests-html module
So i'm trying to install requests-html module for python using django framework. I'm currently in a virtual environment downloading this. When i run "pip install requests-html" i get the error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ This thing is asking me to download another IDE? what lol any help would be great, cheers -
How to set up infinite scrolling with ajax in django?
I have the following html file called testing.html. This code is responsible for showing given locations (based on latitude and longitude) in the map. When user zooms in or out the map, ajax request takes boundaries of visible area of the map and sends it to the view named load_coordinates. Based on the data, $("#property-list").html(data);inserts properties.html data into the testing.html. testing.html contains the following codes: div id="property-list"> </div> <script src="https://api-maps.yandex.ru/2.1/?apikey=Your API key&lang=en_US" type="text/javascript"></script> <script type="text/javascript"> var geoObjectsQuery; var map; <script type="text/javascript"> var geoObjectsQuery; var map; ymaps.ready(['Map', 'geoQuery']) .then(function() { map = new ymaps.Map('property-listing-map', { center: [51.4332, 7.6616], zoom: 7, controls: [] }); clusterer = new ymaps.Clusterer({ preset: 'islands#invertedVioletClusterIcons', clusterHideIconOnBalloonOpen: false, geoObjectHideIconOnBalloonOpen: false }); clusterer.events .add(['mouseenter', 'mouseleave'], function (e) { var target = e.get('target'), type = e.get('type'); if (typeof target.getGeoObjects != 'undefined') { // An event occurred on the cluster. if (type == 'mouseenter') { target.options.set('preset', 'islands#invertedPinkClusterIcons'); } else { target.options.set('preset', 'islands#invertedVioletClusterIcons'); } } else { // An event took place on the geo object. if (type == 'mouseenter') { target.options.set('preset', 'islands#pinkIcon'); } else { target.options.set('preset', 'islands#violetIcon'); } } }); var getPointData = function (index) { return { balloonContentBody: '<div class="property_item heading_space">testing</div>', clusterCaption: 'placemark <strong>' + index + '</strong>' }; }, … -
Django collectstatic does not work as expected
In my Django app, it only has access to part of the static files when Debug = False, any idea why? STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'app/static'), ) After I do collect static I can see the files but for same reason it returns 404 -
How can I call a custom Django manage.py command directly from code with specific database connection
i followed this solution to run customer django command programmatically , but it is limited for just one database connection. I have django app configured with multiple database , is it possible to run custom django command using specific database connection? exactly like when we use connections["DB_NAME_CONNECTION"].cursor() to execute an sql query thanks a lot for your help! -
MemoryError while working with Nginx Server
**after reset code from the repository, I am running python manage.py makemigrations app_name, I got that issue. I am new to the Nginx server So please help Thanks in advance ** -
NOT NULL constraint failed: new__store_product.category_id
after i add category field to my model i am facing this error. where is the problem? from django.db import models class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() des = models.TextField() category = models.ForeignKey(Category, on_delete=models.CASCADE,default=1) image = models.ImageField(upload_to='products/pics') def __str__(self): return self.name`enter code here` -
Django: Need some advice with a test to see whether the correct template is being used
I am fairly new to Django and I am trying to write some tests to test whether the correct templates are being used in a fairly simple app of mine for comparing machine translation results between Japanese and English. The app consists of an input page where the user inputs text to be translated and an output page where translation results are presented. I have written the following test code which I would have thought would give me the expected results but it isn't for some reason. There are two test methods here, test_input_page_template() and test_output_page_template(). The assertions in the first method give the expected results but the assertions in the second method do not. Below I have included the test code, the test output, the urls, and the corresponding view. I would be very grateful if somebody could help me understand what I am missing here. As mentioned above, I am fairly new to Django so the problem could easily be in the urls or the view, for example. Many thanks in advance. tests.py class TestTemplates(SimpleTestCase): def test_input_page_template(self): response = self.client.get(reverse("input")) self.assertTemplateUsed(response, "input.html") self.assertTemplateNotUsed(response, "output.html") def test_output_page_template(self): response = self.client.get(reverse("output")) self.assertTemplateUsed(response, "output.html") self.assertTemplateNotUsed(response, "input.html") Output AssertionError: False is not … -
Using mysql functions in django model query
I'm working on a project where i need to get the nearest records from a point using longitude & latitude, i'm new with Django so i'm a little bit confused about the best way to do it. Since i'm coming from a Laravel background i used to calculate the distance when querying the records using Mysql functions like the following round((6371*acos(cos(radians($request->latitude))*cos(radians(latitude))*cos(radians(longitude)-radians($request->longitude))+sin(radians($request->latitude))*sin(radians(latitude))))*1000) AS distance So with that i'm calculating the distance between each record and my point ( which is $request->longitude and $request->latitude in my example ) after calculating it i'm putting it on that distance field , which i can compare it after with the perimeter that i want to set. I'm wondering if there a way to apply this logic in Django or is there another ( better ) way to do it ? -
Grouping context by a field in Django Template
I have the following model in my django app: class TClassList(models.Model): tutor = models.ForeignKey(tutorInfo, null=False, on_delete=models.CASCADE, related_name='+') course = models.ForeignKey(courseList, null=False, on_delete=models.CASCADE, related_name = '+') professor = models.ForeignKey(professorList, null=False, on_delete=models.CASCADE, related_name='+') Entries in the table would look something like this: tutor course professor John Math Smith Alex History Krasinski Patrick Math Li Sarah Math Smith Joe History Krasinski I am trying to have my template do something like this: Math John Smith Patrick Li Sarah Smith History Alex Krasinksi Joe Krasinski I read a post that was using the regroup tag in jinja and I did adapt to that Here's what I have: {% regroup binder by course as binderList %} <ul> {% for i in binderList %} <li> {{i.grouper}} <ul> {% for j in i.list %} <li>{{j.tutor.student.user.first_name}}: {{j.professor}}</li> {% endfor %} </ul> </li> </ul> {% endfor %} However, I can't seem to understand why it's breaking up based on the tutor and it's truncating the the rest. Perhaps because it's a duplicate course? This is the output I get: Math John Smith History Alex Krasinski -
django question related multiple foreign key (models.py)
How can we have multiple foreign key from one module in Django. for example if we blog project we can have multiple fields which I want to call in another model. so how to do it -
save() prohibited to prevent data loss due to unsaved related object 'employee'
I am working on inlineformset_factory. Inlineformset_factory has two model(WorkExperience and Education) related with Employee model using foreign key relation. When I submit the form I am getting a value error. The error is: save() prohibited to prevent data loss due to unsaved related object 'employee' This is my post method: def post(self, request, *args, **kwargs): form = self.form_class(request.POST) # work_form = self.work_form_class(request.POST, prefix='work_form') # education_form = self.education_form_class(request.POST, prefix='education_form') work_formset = self.work_formset_class(request.POST or None, request.FILES, prefix='work_form') education_formset = self.education_formset_class(request.POST or None, request.FILES, prefix='education_form') data = request.POST.copy() # Check form validation if form.is_valid() and work_formset.is_valid() and education_formset.is_valid(): instance = form.save() # Save work experience for work_form in work_formset: work = work_form.save(commit=False) work.employee_id = instance.id work.save() work_formset.save() # Save education experience for education_form in education_formset: education = education_form.save(commit=False) education.employee_id = instance.id education.save() education_formset.save() I dont know where the error. Where is the error that is preventing to save()? -
Django queryset of related objects
Having the following model: class Company(models.Model): name = models.CharField(max_length=10) class Department(models.Model): name = models.CharField(max_length=10) company = models.ForeignKeyField(to=Company) persons = models.ManyToManyField(to=Person, on_delete=models.PROTECT) class Person(models.Model): name = models.CharField(max_length=10) I would like to get a queryset of all persons in a company Using def persons_by_company(company_name): l = [] for d in Department.objects.filter(company__name=company_name): for p in d.persons: l.append(p) return l would be slow does return a list and not a queryset (is not filterable, etc) What would be the way to get a queryset here? -
How to add my already purchased SSL certificate to my free Heroku app?
I already have an SSL certificate that I bought with my domain from Namecheap, but when I go to add the certificate to Heroku it says I need to either have a Hobby or Professional dyno to be able to use SNI SSL? Does this mean you can't have Https:/ websites with the free version of Heroku? Or is there any way to upload my SSL certificate not using SNI SSL? -
Async Django 3.1 with aiohttp client
Is it possible now, after the start of porting django to async to use aiohttp client with django? My case: server receives a request; server sends another request to another server; server decodes the response, saves it into DB, and returns that response to the client; Andrew Svetlov mentioned that aiohttp "was never intended to work with synchronous WSGI" two years ago. (https://github.com/aio-libs/aiohttp/issues/3357) But how the situation looks now? Django seems to almost support async views. Can we use aiohttp with asgi django? I know, I can create an aiohttp server that handles requests, then populates some queue, and queue handler that saves responses into database, but here I am missing a lot from django: ORM, admin, etc. -
Using NATS.io with Django
I'm trying using NATS in a Django project. But can't find exaples how include it. Nats documentations show how include it as simple file https://github.com/nats-io/nats.py I need publish from view. And subscribe to NATS somewere. -
How to dynamically create an entry through many to many field?
I have models.py class Lesson(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return self.title class Course(models.Model): title = models.CharField(max_length=50) description = models.TextField() lessons = models.ManyToManyField(Lesson) #course can have multiple lessons and lesson can belong to multiple courses. def __str__(self): return self.title what I want is when I try to save an instance of Course, I should be able to add new lessons allong with those already present in Lesson Model. The Lesson instance should be created in Lesson model and then many to many reference added to that Course model. ' I have additinal field in forms.py for add new lessons. The input will be quamma separated Lessons. forms.py class CourseForm(forms.ModelForm): add_more = forms.CharField(widget=forms.Textarea) class Meta: model = Course fields = ['title','description','lessons'] labels={ "title": "Course Title" } How to achieve it ? -
Django CMS - General workarounds when problem solving in Django CMS [closed]
I'm working with Django CMS and I like a lot of it, but there does show a hand full of problems when using it. To take an example the toolbar don't push the content down... so it lays over the navigation bar, so I fixed it by make a section in the CSS that I comment out when ever I'm not working on the site, that pushes body down. This it okay if it was just this, but there keeps coming up small problems, how do you guys deal with them? Right now I use JS to fix some of the things, is that the same way you guys do it or do you have you own models file you create every new project that solves the problems there is? -
Django url passing as many parameters as you want delimited by /
How can I define the URL pattern so that I can pass to an URL as many parameters as I want? I really researched the documentation and other stackoverflow questions but I didn't found something similar to that. I need this to work as a filter for an ecommerce website. I would like to achieve something like this: urlpatterns = [ path('test/<str:var1>-<str:var2>/<str:var3>-<str:var4>/...', views.test, name='test'), ] And in my view function I would define it like that: def test(request, *args, **kwargs): # Do whatever you want with kwargs return HttpResponse('Test') -
SMTPAuthenticationError at /accounts/signup/ allauth django on sending confirmation email
Hi there I'm encountering an issue on my app in production whereby I'm using allauth to handle my authentication, when i try to signup I get redirected to an error page showing an error in sending a confirmation email on signing up Looking at it I thought it might be due to having my google account setting (since I'm using google for smtp host ) for allowing less secure apps to be off but it is on so I'm stuck on how to solve this. I'm thinking of removing email from signup process since no confirmation email will be sent in that case Note that the redirect works perfectly fine on my development server -
API endpoint to return Django model choices
I have a program with a Django backend (Django + Django RestFramework) with a React frontend. In my React frontend I need to create a dropdown to display a list of options that are valid choices for my Django model ("Foo," "Bar," and "Baz"). models.py from django.db import models from model_utils import Choices from model_utils.fields import StatusField from model_utils.models import TimeStampedModel class MyCustomModel(TimeStampedModel): STATUS = Choices("Foo", "Bar", "Baz") details = models.TextField() status = StatusField() serializers.py from rest_framework import serializers from custom.models import MyCustomModel class MyCustomModelSerializer(serializers.ModelSerializer): class Meta: model = MyCustomModel fields = "__all__" views.py from rest_framework import generics from custom.models import MyCustomModel from custom.serializers import MyCustomModelSerializer class DetailsView(generics.ListCreateAPIView): queryset = MyCustomModel.objects.all() serializer_class = MyCustomModelSerializer urls.py from django.urls import path from custom.views import DetailsView app_name = "custom" urlpatterns = [ path("api/custom/details/", DetailsView.as_view(), name="details"), path("api/custom/details/statuses/", DetailStatusesView.as_view(), name="detailStatuses"), # <-- how to implement this? ] Given what I have already layed out above...I want to implement the view so that when I go to my "detailStatuses" endpoint, I am returned a response like (which is just a list of values defined in MyCustomModel): { "statuses": [ "Foo", "Bar", "Baz" ] } -
Django Model with API as data source
I want to create a new model which uses the https://developer.microsoft.com/en-us/graph/graph-explorer api as a data source as i want to have additional info on the user. Using a computed property on the model does not work as it is going to query for each instance. So i want to have the model relate to a new model which has the api as it´s data source. I could not find anything on this topic