Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - storing total coins for a user as a separate field or calling a method to calculate it every time?
I have a more general model design question. I am making a site where users register, complete tasks and are rewarded with coins, they can withdraw these coins later. Each task has a separate object created in a table but I'm wondering how real world applications store this. Do they have a separate field for the total current coins a user has and add or subtract coins when a new task is completed or a withdrawal is made or do they call a method on the user to add up all the tasks, coins and takeaway all their withdrawals every time it's needed? Each user would likely have up to a few hundred tasks possibly thousands? Thanks! -
How to perform a query by using URL with question mark in Django?
It seems like the original URL querying function has been removed from Django 3.1. Does anyone know how to do it with a new package? The url.py: urlpatterns = [ re_path(r'^portfolio/(?P<title>[\w-]+)/$' , BlogApp_View.displayPortfolio, name='displayPortfolio'), path('portfolio/', BlogApp_View.selectPortfolio, name='selectPortfolio'),] The view.py def displayPortfolio(request): title = request.GET.get('title') portfolio = Article.objects.filter(articleType__name__contains = "Portfolio", title=title) print(title) DICT = {} return render(request, 'Article/', DICT) The problem is now if I visit http://127.0.0.1:8000/Blog/portfolio/?title=A_UAV_Positioning_Approach_Using_LoRa/, it will skip the re_path shows in url.py. Instead, it goes to the path one. I have tried str:title method but that is actually not what I want. I prefer using the question mark pattern to finish the query. -
multiple user model in django
there will be a model for the shop owners and another for the customers. both models will have different form fields. like shop form will have owner name ,shop name, location, etc. customer form will have customer name, location, phone number, etc. shops can view orders and customers can submit orders. How can I approach this problem? -
Specifying an alternate value for foreign key in POST payload with Django Rest Framework's GenericViewSets
I need to be able to specify something other than a foreign relationship object's pk/id in the payload of a POST request. My model: class Damage(PDAbstractBaseModel): vehicle = models.ForeignKey(Vehicle, related_name='damages', on_delete=models.CASCADE) driver = models.ForeignKey(Driver, related_name='damages', null=True, on_delete=models.CASCADE) description = models.TextField() My view: class VehicleDamageViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): permission_classes = (permissions.IsAuthenticated, IsDriverOrAbove) serializer_class = DamageSerializer queryset = Damage.objects.all() lookup_field = 'uid' lookup_url_kwarg = 'uid' lookup_value_regex = '[0-9a-f-]{36}' ordering_fields = ['modified', ] ordering = ['modified'] logger = get_logger('VehicleDamageViewSet') def get_serializer_context(self): return {'request': self.request} def get_vehicle(self, vehicle_uid): return Vehicle.objects.get(uid=vehicle_uid) def get_queryset(self): return self.queryset.filter(vehicle__uid=self.kwargs['vehicle_uid']) def perform_create(self, serializer): return serializer.save(vehicle=self.get_vehicle(self.kwargs['vehicle_uid'])) my urls.py ... omitted for brevity ... router = routers.SimpleRouter() router.register(r'damage/(?P<vehicle_uid>[a-fA-F0-9-]+)', VehicleDamageViewSet) ... omitted for brevity .... The serializer: class DamageSerializer(serializers.ModelSerializer): damage_photos = serializers.SerializerMethodField() def get_damage_photos(self, damage): qs = DamagePhoto.objects.filter(damage=damage) serializer = DamagePhotoSerializer(instance=qs, many=True) return serializer.data class Meta: model = Damage fields = ('id', 'uid', 'driver', 'description', 'damage_photos') read_only_fields = ('uid', 'id') The part of my unit test that fails: data = { # 'driver': self.user.id, 'driver': self.user.uid, 'description': 'horn does not work.', } url = reverse("vehicle:damage-list", kwargs={'vehicle_uid': vehicle_uid}) # print(f"damage POST {url}\npayload {data}") response = self.client.post(path=url, data=data, format="json") print(response.status_code) print(response.data['driver'][0]) self.assertEqual(response.status_code, status.HTTP_201_CREATED) The above code works if I specify 'driver': self.user.id,, but … -
I have over written the save() method but the new code is only being applied to new records
I need titles to be in lowercase. I overwrite the save() method and included self.title.lower(), this works great for any new records I create. But when I modify existing records, the titles are not changed to lowercase? Does anyone know why? Or could someone point me in the direction of the relevant documentation? I have a many to many field in the table, should I update my m2m_changed signal to include code that addresses the issue? def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slug_generator(self) self.title = self.title.lower() super(CategoryTree, self).save(*args, **kwargs) else: super(CategoryTree, self).save(*args, **kwargs) -
Grabbing data from website using Selenium and storing data in a model (Python/Django)
I'm trying to have the user store data in one of my models when a favorite button is clicked. The data is grabbed from websites using selenium, but I'm not sure how to go about getting it actually store in my models and display on the favorites page. I'm new to django and it's confusing so any help would be appreciated! data.html - trying to grab data and send it to favorites page {% for doordash in doordash %} <div> <p>Restaurant: {{ doordash.restaurant_name }}</p> <p>Delivery Cost: {{ doordash.delivery_cost }}</p> <p>Delivery Time: {{ doordash.delivery_time }}</p> <form action="/favorites" method="post"> {% csrf_token %} <input type="hidden" value={{ doordash.location }}> <input type="hidden" value={{ doordash.restaurant_name }}> <input type="hidden" value={{ doordash.delivery_cost }}> <input type="hidden" value={{ doordash.delivery_time }}> <input type="hidden" value={{ doordash.rating }}> <button type="submit">Add {{ doordash.restaurant_name }} to favorites</button> </form> favorites view - data to be displayed on favorites page def favorites_index(request): if request.method == "post": model = Restaurant fields = '__all__' def form_valid(self, form): self.object = form.save(commit=False) print('!!!!! SELF.OBJECT:', self.object) self.object.user = self.request.user self.object.save() return HttpResponseRedirect('/') doordash = Restaurant.objects.all() return render(request, 'favorites/favorites.html', {'doordash': doordash}) def favorites_show(request, restaurant_id): doordash = Restaurant.objects.get(id=restaurant_id) return render(request, 'favorites/show.html', {'doordash': doordash}) -CRUD Routes for Restaurant model - when the favorites button is … -
How do I print Django form data from views.py?
So I have a form running on Django and I'm trying to print the form.cleaned_data from views.py but it does not print anything in the shell. $ views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import NameForm def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = NameForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... print(form.cleaned_Data) # redirect to a new URL: return HttpResponseRedirect('/polls/thanks/') # if a GET (or any other method) we'll create a blank form else: form = NameForm() return render(request, 'name.html', {'form': form}) def thanks(request): return render(request, 'thanks.html') The fix is probably very easy I'm just a newbie at Django. Thanks -
Using Ant Media Server in a Django Project
I am planning to integrate Ant media server in a django project for the live video streaming functionality only. I want my users to be able to start a livestream and their followers to be able to view the stream. Is this possible ? If it is could someone point me to specific guides or references I can refer to ? -
Errors while integrating bootstrap template in Django
I was trying to integrate the bootstrap template in my Django project. I have integrated it but I am having an error in the URL. The following is the error I have: Codes in template: <div class="col-md-6 col-sm-12"> <div class="shop-cat-box"> <a href="{% url 'fertilizer-name' %}"><img class="img" src="{% static 'images/cyp/3.png' %}" alt="" /></a> </div> </div> In URL: urlpatterns=[ path('', findex, name='fertilizer-name'), path('fertilizer/',predict_chances,name='submit_prediction'), path('fertilizer/results/',view_results,name='results'), ] -
Custom font to be rendered in Django using Amazon s3
I tried to read the documentation and still could not figure out how to render custom fonts in Django through s3 buckets. styles.css @font-face { font-family: 'ProximaNova'; src: url('../static/fonts/ProximaNova-Regular.otf'); font-style: normal; font-weight: 400; } settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CRISPY_TEMPLATE_PACK = 'bootstrap4' #s3 buckets config AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') # AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'ap-south-1' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' The code works fine in local environment. Do I need AWS lambda for this or the absolute path defined in styles.css src: url('../static/fonts/ProximaNova-Regular.otf'); is incorrect? Any help will be much appreciated..Thanks! -
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()?