Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to value Selected When edit form in Django?
I am updating my form, and it's succesfully updating, but I am selecting multiple values when i am editing the form, and my values are storing in database in this format 1,2,3,4 , Please let me know how i can display these values as selected in my html form. Here is my code... <select name='days' multiple> <option value='1' {% if datas.days == 1 %}selected{% endif %}>Day 1</option> <option value='2' {% if datas.days == 2 %}selected{% endif %}>Day 2</option> <option value='3' {% if datas.days == 3 %}selected{% endif %}>Day 3</option> <option value='4' {% if datas.days == 4 %}selected{% endif %}>Day 4</option> <option value='5' {% if datas.days == 5 %}selected{% endif %}>Day 5</option> </select> -
Django Full image is not loading
I am doing the Tango with Django tutorial. I am using Django version 3.1.1. I was able to get my image to load on the local link 'http://127.0.0.1:8000/static/images/rango.jpg' I am not getting it to load on to the index.html the code is <!DOCTYPE html> {% load static %} <html> <head> <title> Rango</title> </head> <body> <h1>Rango says...</h1> <div> hey there partner! <br /> <strong>{{ boldmessage }} </strong><br /> </div> <div> <a href="/rango/about/">About</a><br /> <img src="{% static 'images/rango.jpg' %}" alt="Picture of Rango" /> </div> </body> </html> I did try removing the "alt=" in html but that didn't work. I do not think the problem is my settings.py, but I'll share some parts of the settings.py anyway. TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') # this is the file path for templates STATIC_DIR = os.path.join(BASE_DIR,'static') # this is the file path for static STATICFILES_DIRS = [STATIC_DIR,] ... #At the very bottom... STATIC_URL = '/static/' Any help is appreciated. -
How can I run Scrapy on AWS with django_crontab?
I am trying to run a scheduled cron job on AWS. I already try other Django scripts and it works well. I can start Scrapy with Django-Template and it works well. Cron.py from .models import Spiders import importlib from first_bot.start import startallSpiders def scheduled_spider(): all_class = [] spiders = Spiders.objects.all() for spider in spiders: spider_name = spider.spider_name name = 'first_bot.first_bot.spiders.'+spider_name i = importlib.import_module(name) class_ = getattr(i, spider.spider_class) all_class.append(class_) startallSpiders(all_class) Here I am getting all spider names and spider class' to start crawling same function works with Django-Template and view. start.py from scrapy.crawler import CrawlerProcess, CrawlerRunner, configure_logging, Crawler from scrapy.utils.project import get_project_settings from crochet import setup import importlib import time import logging import datetime setup() def startallSpiders(all_Class): now = datetime.datetime.today() now_time = now.strftime("%d-%m-%y") for class_ in all_Class: configure_logging(install_root_handler=False) logging.basicConfig( filename='scrapy-log-'+now_time+'.txt', format='%(levelname)s: %(message)s', level=logging.INFO ) runner = CrawlerRunner(get_project_settings()) runner.crawl(class_) Here I am crawling all class' that I sent from view.py or cron.py have startallSpiders function and it works well with Django view. settings.py CRONJOBS = [ ('35 11 * * *', 'Bot.cron.scheduled_spider') ] I already try another function in cron.py it works well again but I couldn't figure out why the scrapy not start. 01_cron.config files: "/etc/cron.d/cron_process": mode: "000644" owner: root group: … -
Trying to override a get_queryset in a view
class OwnerList(generics.ListAPIView): serializer_class = OwnerDetailSerializer # queryset = Person.objects.filter(customuser__userrole__role__name='OWNER').distinct() permission_classes = [IsAuthenticated] filter_backends = [DjangoFilterBackend] def get_queryset(self): return super(OwnerList, self).get_queryset() I have this simple view and i am trying to over ride the get_queryset. The issue is that when this view is used i get : return super(OwnerList, self).get_queryset() File "C:\Users\kdalipaj\PycharmProjects\LTC SYSTEM\venv\lib\site-packages\rest_framework\generics.py", line 63, in get_queryset assert self.queryset is not None, ( AssertionError: 'OwnerList' should either include a queryset attribute, or override the get_queryset() method. Why is this happening? -
creating a serializer for OneToOne
I'm new to django. I need to write a serializer for OneToOne related models Models.py class AbstractUser(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField( _('phone number'), max_length=14, unique=True, help_text='Enter your phone number', ) email = models.EmailField(_('email address'), blank=True) created = models.DateTimeField(_('date joined'), default=timezone.now) class Participant(models.Model): user = models.OneToOneField(AbstractUser, on_delete=models.CASCADE, primary_key=True) first_name = models.CharField( _('first name'), max_length=50 ) last_name = models.CharField( _('last name'), max_length=50, ) device_reg_token = models.TextField( _('text mobile token'), ) is_participant = models.BooleanField( _('participant status'), default=True ) I wrote a serializer but it only displays fields of the participant model Serializers.py class AbstractUserSerializer(serializers.ModelSerializer): class Meta: model = AbstractUser fields = ('phone_number', 'email', 'password') class ParticipantSerializer(serializers.ModelSerializer): abstractUser = AbstractUserSerializer(read_only=True) class Meta: model = Participant fields = ('first_name', 'last_name', 'device_reg_token', 'abstractUser') def create(self, validated_data): participant = Partner.objects.create_participant( phone_number=validated_data['phone_number'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], device_reg_token=validated_data['device_reg_token'], password=validated_data['password'], ) participant.save() return participant How can I display all fields of the Abstract and Participant models. ReadOnly throws an error when removed Views.py class CreateUserView(generics.CreateAPIView): queryset = Participant.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ParticipantSerializer