Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
nginx as a proxy to react and django backend
Hello guys Im very new to nginx, recently I have been attempting to connect nginx to my django backend and react frontend but have been facing some issues. What im trying to achieve is that a user will be able to access my nginx proxy at port 8080 or the default port, and be served with my built react application. There after any api calls will then be routed to my django backend that is listening at port 8000. Here is my nginx config file : upstream api { server backend:8000; } server { listen 8080; location /test/ { proxy_pass http://api$request_uri; } location /api/ { proxy_pass http://api$request_uri; include /etc/nginx/uwsgi_params; } location /static/rest_framework/ { proxy_pass http://api$request_uri; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri /index.html; } } and here is my docker-compose file for production: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user backend: build: ./backend volumes: - static_data:/vol/web env_file: - ./.env.dev depends_on: - postgres frontend: tty: true build: ./frontend command: ["yarn","build"] volumes: - ./frontend:/usr/src/frontend redis: restart: always image: redis:latest ports: - "6379:6379" … -
How to filter on a Sum() containing F()s?
Suppose I have those two models: class Category(models.Model): name = models.CharField(max_length=32) class Item(models.Model): category = models.ForeignKey('Category', related_name='items', on_delete=models.CASCADE) quantity = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) Then I'd like to query all categories to find out how each is performing with its items: (Category.objects.all() .annotate( sales_yesterday=Sum('items__quantity', filter=Q(items__created_at__date=yesterday)), revenue_yesterday=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()), sales_today=Sum('items__quantity', filter=Q(items__created_at__date=today)), revenue_today=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()) ) ) But revenue_yesterdayand revenue_today don't filter for yesterday and today respectively, unlike sales_yesterday and sales_today which do. Meaning the revenue_* annotations do their aggregations over the entire table and that's not what I want. The challenge I'm facing is how to apply those needed filters on my revenue_* annotations and one of the approaches I've tried is something similar to what I've done with my sales_* annotations: ( revenue_today=Sum(F('items__price') * F('items__quantity'), filter=Q(items__created_at__date=today), output_field=DecimalField()) ) Which only throws up an error: FieldError: Expression contains mixed types. You must set output_field. And I'm not sure what I should do since I already set output_field, and it's not clear to me if I'm putting that filter in the right place or in the right way inside Sum(). How do I solve this? -
Django one-to-one relationships and initial values
I´m learning to code and I´m trying to make a small app using Django. I have two models, Groups and Lists. The idea is that a user creates a Group, and then a List of students (which uses a formset). class Groups(models.Model): name = models.CharField(max_length=50) students_number = models.IntegerField() def __str__(self): return self.name class List(models.Model): name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) second_last_name = models.CharField(max_length=50) group = models.OnetoOneField(Groups, max_length=50, on_delete=models.CASCADE, default="Grupo") def __str__(self): return self.name All the students on that list should be assigned to the group you just created. I already set the one-to-one relationship, but in this way, the user has to choose the group for every student (it is supposed that ALL of these students belong to this group, so I think doing this repeatedly is unnecessary). This is the view: def addList(request): AddListFormSet = modelformset_factory(List, fields=("name", "last_name", "second_last_name", "group"), extra=2,) if request.method == "POST": form = AddListFormSet(request.POST) form.save() return redirect("/grupos") form = AddListFormSet(queryset=List.objects.none()) return render(request, "new_list.html", {"form": form}) How can I pre-assign the group that I just created for all the students that I capture in the next step? -
aggregate method in Django
I am new to Django and when i use Aggregate method , it returns something like {'max__age' : 35} but I need to display just the number (35 in this example). How can I solve it? Thanks all. -
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error
Access to fetch at 'http://localhost:8000/api/product/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. -
Large file upload to Django Rest Framework
I try to upload a big file (4GB) with a PUT on a DRF viewset. During the upload my memory is stable. At 100%, the python runserver process takes more and more RAM and is killed by the kernel. I have a logging line in the put method of this APIView but the process is killed before this method call. I use this setting to force file usage FILE_UPLOAD_HANDLERS = ["django.core.files.uploadhandler.TemporaryFileUploadHandler"] Where does this memory peak comes from? I guess it try to load the file content in memory but why (and where)? More information: I tried DEBUG true and false The runserver is in a docker behind a traefik but there is no limitation in traefik AFAIK and the upload reaches 100% I do not know yet if I would get the same behavior with daphne instead of runserver -
Moving the login panel to center of screen
While practicing Django, I want to mess around with CSS. In this case, I am creating a login page. The login form is currently appearing at the top-left corner of the page. How to I modify to make it right in the center? I am not good with CSS and could use some pointers. Here are my django files. I try to manipulate the panel-default but it does not work. base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">My Page</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> login.html (which extends the base.html) {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <div class="panel panel-default"> <h1>Log-in</h1> <form method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Log in"></p> </form> </div> {% endblock %} base.css @import url(http://fonts.googleapis.com/css?family=Muli); body { margin:0; padding:0; font-family:helvetica, sans-serif; } .panel-default{ position: absolute; top: 50%; left: 50%; } #header { padding:10px 100px; font-size:14px; background:#12c064; color:#fff; border-bottom:4px solid #1cdf78; overflow:auto; } -
how can make a custom filter with django-filter
Help!... I need to make a search engine that filters and obtain the results depending on the parameters that are sent from the front end, for example if they send the 3 parameters (Repository, family and array of Products) it would have to iterate through the array products and get the stock of that product by repository and family (group) I already did it with queries like these: for product in products["entries"]: product_id = product["id"] try: query = Stock.objects.filter(product__family=family,product__id=product_id) except Stock.DoesNotExist: query = None if query: try: query_to_return = StockSerializer(query,many=True).data But then I had a lot of problems and I couldn't find a way to paginate the data because there are many records, so I would like to do it with Django-Filter. class Stock(CustomModel): product = models.ForeignKey(Product, on_delete=models.PROTECT, related_name='stocks', verbose_name=("Producto")) repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stocks', verbose_name=("Almacén")) date = models.DateTimeField(auto_now=True) class Product(CustomModel): name = models.CharField(max_length=100, unique=True, verbose_name=("Nombre")) codebar = models.CharField(max_length=20, null=True, blank=True, verbose_name=("Código de Barras")) brand = models.ForeignKey(Brand, null=True, blank=True, on_delete=models.PROTECT, related_name='products', verbose_name=("Marca")) model = models.CharField(max_length=50, verbose_name=("Modelo")) data_serie = models.CharField(max_length=50, verbose_name=_("Serie de Datos")) ....another fields.. class Repository(CustomModel): name = models.CharField(max_length=100, unique=True,verbose_name=("Nombre")) code = models.CharField(("Clave"), max_length=20, null=True, blank=True) repositories_group = models.ForeignKey(RepositoriesGroup, verbose_name=("Grupo"), on_delete=models.PROTECT, related_name='repositories', null=True, blank=True) description = models.TextField(("Descripción"), null=True, blank=True) .......Another … -
How do I create this complex user filter in Django 2.0?
I have several overlapping categories. I wanted to search and filter each person according to their type, specialty and place of residence class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) gender = models.CharField(choices = GENDER_CHOICES) country = models.CharField(choices = COUNTRY_CHOICES) city = models.CharField(choices = CITY_CHOICES) class License(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) types = models.CharField( choices = TYPES) specialization = models.CharField( choices = SPECIALIZATION_CHOICES) and this is my filter viws def search(request): profiles = Profile.objects.all() if request.method == 'POST': types = request.POST['types'] specialization = request.POST['specialization'] country = request.POST['country'] city = request.POST['city'] gender = request.POST['gender'] if types or specialization or username or country or city or gender: license_match = License.objects.filter( Q(types__exact = types)| Q(specialization__exact = specialization) ) profile_mutch = Profile.objects.filter( Q(country__exact = country)| Q(city__exact = city)| Q(gender__exact = gender) ) if license_match or profile_mutch: license_match = License.objects.filter( Q(types__exact = types)| Q(specialization__exact = specialization) ) profile_mutch = Profile.objects.filter( Q(country__exact = country)| Q(city__exact = city)| Q(gender__exact = gender) ) mutch = profile_mutch and license_match paginator = Paginator(mutch, 60) page = request.GET.get(mutch, 1) page_number = request.GET.get(page) page_obj = paginator.get_page(page_number) return render(request, 'search_result.html', {'page_obj': page_obj, 'result': mutch, 'profiles': profiles}) else: messages.error(request, 'No result found.') else: return HttpResponseRedirect('result') else: profile_mutch = Profile.objects.all() license_match = License.objects.all() … -
How to generate a "fake" slug in Django
I saw in a video I didn't save that you could do something like this: www.mysite.com/post/12345/this-is-a-title Where the 12345 is the id and what actually is used to do the query and the this-is-a-tilte part is automatically assigned when loading the page and you can actually write whatever you want there and will still load the page. How do I set this up in my path and do I still need a SlugField? -
Django: Cache function
I created the following serializer where I call the function _calculate_image_dimensions twice. I now tried @cachedproperty but doesn't work because I have to pass the values width, height. However, they will not change for get_width and get_height. Is there a way to make sure the calculation only computes once? class IntegrationImageSerializer(serializers.ModelSerializer): width = serializers.SerializerMethodField() height = serializers.SerializerMethodField() class Meta: model = IntegrationImage fields = ("image", "width", "height") def _calculate_image_dimensions(self, width, height) -> int: MAX_IMAGE_SIZE = 350 aspect_ratio = width / height if width > height: width = MAX_IMAGE_SIZE height = width / aspect_ratio else: height = MAX_IMAGE_SIZE width = height * aspect_ratio return round(width), round(height) def get_width(self, obj: IntegrationImage) -> int: width, height = self._calculate_image_dimensions( obj.image.width, obj.image.height ) return width def get_height(self, obj: IntegrationImage) -> int: width, height = self._calculate_image_dimensions( obj.image.width, obj.image.height ) return height -
Python and Django TimeZone Format Postgres
I have a line of code here that works on my dev server for Django and Python using SQL Lite, however when I upload my code it gives me an error about my time zone . Here is my Code. Postgres doesn't like the %z at the end , however SQL Lite its fine. What do I do to fix this on my Heroku Postgres Production Environment? Thanks new_event.start = datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z') Error Message: time data '2020-10-08 12:17:51-04:00' does not match format '%Y-%m-%d %H:%M:%S%z' -
Django Form Dropdown HTML code not working
I am trying to achieve a dropdown list of fields using my MODELS.py. When app is run HTML page displays OK and some of the inputs fields works fine. But the dropdown fields doesn't appear correctly and appear as TEXT only on the page. I have tried all sorts of HTML formating but still no success. Also I have searched thru NET but there isint much help available as well. Kindly check and help pls. MODELS.PY from django.db import models from django.contrib.auth.models import User # Create your models here. class Vehicle(models.Model): VEHICLE_STATUS_CHOICES = ( ('B', 'Booked'), ('NB', 'Not Booked'), ) INSURANCE_STATUS_CHOICES = ( ('U','Updated'), ('NU','Not Updated'), ) VEHICLE_TYPE_CHOICES = ( ('P','Passenger'), ('T','Truck'), ('C','Construction'), ) FUEL_TYPE_CHOICES = ( ('P','Petrol'), ('D','Diesel'), ) owner = models.ForeignKey(User,default=None,on_delete=models.CASCADE) cost_per_km = models.DecimalField(max_digits=20,default=0,decimal_places=2) price = models.DecimalField(max_digits=20,default="0",decimal_places=3) registration_plate = models.CharField(max_length=200,default='') vehicle_status = models.CharField(max_length=2, choices=VEHICLE_STATUS_CHOICES, default='NB') insurance_status = models.CharField(max_length=2,choices=INSURANCE_STATUS_CHOICES, default='NU') no_of_km_travelled = models.DecimalField(max_digits=20,default=0,decimal_places=0) fuel_type = models.CharField(max_length=1,default='P',choices=FUEL_TYPE_CHOICES) mileage = models.DecimalField(max_digits=20,default=0,decimal_places=0) vehicle_type = models.CharField(max_length=1,choices=VEHICLE_TYPE_CHOICES, default='P') image=models.ImageField(upload_to="vehicle_image",default="default.png",blank=True) def __str__(self): # return self.registration_plate return self.vehicle_type **Forms.py** from django import forms from .models import Vehicle class VehicleForm(forms.ModelForm): class Meta: model=Vehicle # fields = '__all__' fields = ('cost_per_km', 'price', 'registration_plate', 'no_of_km_travelled', 'mileage', 'vehicle_type', 'fuel_type', 'insurance_status', 'image') ----------------------------------------------------------------------------------------------- **Views.py** from django.shortcuts import render,redirect,get_object_or_404 from django.http import … -
Django static files always returning 404 179
I have been trying every video or post I can possibly find on the internet none of that seems to work unless a run on the insecure mode. I'm using Django 3.0.10 At the moment I'm working locally to after deploy on Cpanel. But even after I tried to deploy the problem is the same. They always return 404 179 for every static file even that I can go through the files and see they are all there. The only anomaly that I have when working locally is that my username contains spaces. I follow each step on the docs and still didn't work. I change the collectstatic folder and where to find the files I want know if there is something I'm doing wrong. I even add to the urlpatterns += staticfiles_urlpatterns and also add the project name to the INSTALLED_APPS. STATIC_ROOT = os.path.join(BASE_DIR, 'app\static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Thank you in advance! -
How to add a button using bootstrap
I'm new to Django and bootstrap and currently working on a project. Basically my question is purely on html and css. I want to insert a button on the right side of the box. I use the following code: <div class="col-md-12 text-right"> <a href="{% url 'listing' listing.id %}" class="btn btn-info">More Info</a> </div> However i get: As you can see there is a gap because of the button, how can i put this button without this gap. Thank you -
Django: How do I delete one Address instance out of many based on current user using APIView
I have an Address model which can have multiple instances per user. I am using APIView to delete one out of many instances but I can't figure out how do i chose the one instance for the logged in user. My view: class AddressView(APIView): permission_classes = (IsAuthenticated,) def post(self, request): ... def put(self, request): ... def get(self, request, format=None): ... def delete(self, request, format = None): id = request.GET.get('id', '') address = get_object_or_404(Address, id = id) address.delete() return Response({"message": "Address has been deleted."}) I have defined a plain URL that handles GET, POST and PUT along with this DELETE: path('address/', AddressView.as_view(), name='user_address'), I understand it has many flaws but every time I run this, I get this error: ValueError: Field 'id' expected a number but got ''. How should be the right view to delete an Address instance for the logged in user? -
Django form - user url attr to fill automatically the form - RelatedObjectDoesNotExist
I'm still stuck with my issue. So I've found a new way to do it. Better I think Your help will be really appreciate. path('new/<seller>/', CreateChannelSellerView.as_view(),name="channel_to"), Assume I got .../new/fredo/ -> fredo is the username of the seller. I want to catch it. But I got an issue: Exception Type: RelatedObjectDoesNotExist Exception Value: Channel has no seller. Trace: form.instance.seller.add(existed_seller) "%s has no %s." % (self.field.model.name, self.field.name) views.py class CreateChannelSellerView(CreateView): model = Channel form_class = CreateSellerChannelForm template_name = 'channel_seller_new.html' def form_valid(self, form): form.instance.consumer = self.request.user seller_field = self.kwargs['seller'] current_seller = User.objects.filter(username=seller_field) if current_seller.count()<1: raise forms.ValidationError('Username does not exist') else: existed_seller = User.objects.get(username=seller_field) form.instance.seller.add(existed_seller) form.save() return super(CreateChannelSellerView, self).form_valid(form) def get_success_url(self): return reverse_lazy('channel:channel_home') models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super().save(*args, **kwargs) def __str__(self): return self.name forms.py class CreateSellerChannelForm(forms.ModelForm): class Meta: model = Channel widgets = { 'name':forms.TextInput(attrs={'class':'','style':'','placeholder':'First group'}), } fields = [ 'name', ] -
Django FileField: cómo devolver solo el nombre de archivo (en la plantilla)
Tengo un campo filefield para subir archivos en una ruta establecida desde mi modelo files = models.FileField(upload_to="files/%Y/%m/%d") Pero cuando desde mi html lo muestro, en lugar de aparecer solo el nombre del archivo me aparece la ruta completa {% for item in Anexo %} <a href="{{ item.files.url }}"><br/> {{ item.files }}<br/></a> {% endfor %} Encontre informacion aqui pero es de 2008 y no me funciona la solucion. -
Django loaddata fails: models.DoesNotExist
I try to works with fixtures which are normally simple but got an error I do not understand I've made a fixture using dumpdata command I flush my database and try to load (loaddata) my fixture but got an error: raise self.model.DoesNotExist( parameters.models.DoesNotExist: Thesaurus matching query does not exist. so I can "resolve" this error iby changing the line that raise error but I want to understand what is wrong Is it related with admin form? class RandomisationSecoursFormAdmin(forms.ModelForm): LIBELLE = Thesaurus.options_list(3,'fr') ***<- line that raise error*** bra_lib = forms.ChoiceField(label="Libellé du bras", widget=forms.Select, choices=LIBELLE) ... if I change line that raise error with the code below, it works if Thesaurus.objects.filter(the_ide = 3).exists(): LIBELLE = Thesaurus.options_list(3,'fr') else: LIBELLE = [] -
how to use any() and all() function in django templates without custom templates tag
i have some situation where i got python dict as data which i want to check if any( any(dict.values) ) value exist or not.. but not sure how to use any() or all() function in django templates. is there any built in filter ?? {% if search_result.result.show_more.values %} <tr class="header"> <th colspan="4">{% trans 'Charges Info' %}</th> </tr> {% endif %} if any value exist in showmore dict the i want to display header. -
How can I make Django user logout without a new url page?
For logout I am using ready django.contrib.auth.LogoutView and everyone in their tutorials are creating a new url for example '/logout' and my question is how can I use that view without a new url page and html template? Plese use some code for views.py in your answers ;) -
Can I edit the datetime field before saving in database in django?
I am uploading an excelsheet in which date is in format 08-10-2020(DD-MM-YYYY). When it's saved in the database, it becomes, Oct. 8,2020 8:50 p.m. But I want the date to be saved in YYYY-MM-DD format. Is this posssible? My models.py looks like this: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=100) email = models.EmailField() bday = models.DateTimeField(auto_now_add=True) year = models.IntegerField() def __str__(self): return self.name -
Where to put 'allow_empy_files` in a Django form?
I currently have this form and I want to allow the user to upload empty files but I'm not sure on where to add allow_empty_files. class FileUploadForm(forms.ModelForm): class Meta: model = Uploaded fields = ( 'name', 'description', 'file', 'usertags', ) -
Is there way to add Q objects in django?
I am passing multiple values in a list and I want to filter my queryset with this values. I know about Q object but I don't know how to add filters together. I thought of something like: categories = ['1','3','4'] for category in categories: Q+= Q(id = category) and after that I would filter my queryset queryset.filter(Q) -
Django Templates Configuration
hello everyone I am beginner in this industry I am not for long installed django 3 for python 3 on kali linux I put inside settings.py/TEMPLETES my file name but its not works I am looking for over 5 days from internet but I can not find answer pls help me