Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Wagtail 2.10 update breaks SVGs
I have an old codebase written using wagtail at work and I have to update the wagtail version from 2.9 to 2.10. I tried this thing and the icons from the cms literally break. They do not show up at all. Looks like the 2.10 update migrates the font icons to svg icons. The HTML looks good, but there is no svg path to reference to for some reason. <svg class="icon icon-folder-open-inverse icon--menuitem" aria-hidden="true"> :before <use href="#icon-folder-open-inverse"></use> </svg> From other examples, looks like I should have the svgs with paths defined at the top of the body tag, but there are none. Tried to rerun collectstatic, but with no success. Does anyone have any idea why or how to solve this? -
Django get authors in serie through book-object
For a hobby project I am building a django-app that displays the books in a private collection. I have 3 models relevant to this question: Serie, Book and Author: from django.db import models class Author(models.Model): pass class Book(models.Model): authors = models.ManyToManyField(Author) class Serie(models.Model): books = models.ManyToManyField(Book) If I have a Serie-object, what is a good way to get all authors in the serie? (Some series in the collection have books written by different authors) -
Please explain the essence of the task related to Django models
Good afternoon! I ask for help in explaining the task of using DRF. The task is to develop an authorization and news server. I basically understand what I need to do, but here are some steps from the explanation I don't understand. I need to have a Users model (which has a username field and an encrypted password field). I can't figure out if I need to use the built-in Django - User model or create this model myself. It is also written in the explanation that admin users may not overlap with users in the Users table I tried to create my own Users class, but I couldn't figure out which type of field to choose for the password. -
Django Model VIewSet overriding
Models class Inventory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=100) unit_price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.PositiveIntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.product.name} - {self.quantity}" class InventoryHistory(models.Model): inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE) quantity_change = models.DecimalField(max_digits=8, decimal_places=2) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.product.name} - {self.quantity_change} ({self.timestamp})" Serializers class InventoryHistorySerializer(serializers.ModelSerializer): class Meta: model = InventoryHistory fields = '__all__' class InventorySerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = Inventory fields = '__all__' ViewSets class InventoryViewSet(viewsets.ModelViewSet): queryset = Inventory.objects.all() serializer_class = InventorySerializer class InventoryHistoryViewSet(viewsets.ReadOnlyModelViewSet): queryset = InventoryHistory.objects.all() serializer_class = InventoryHistorySerializer I'm working with above code. The idea is, When Some changes are made in Inventory, the InventoryHistory gets automatically updated with a new record. My main confusion is, having two different serializers. How can i override viewsets and manage these two different serializers. -
Django - Show a simple gallery in the template
I have these models: class Car(models.Model): brand = models.CharField(max_length=255) model = models.CharField(max_length=255) class CarImage(models.Model): car = models.ForeignKey(to=Car, on_delete=models.CASCADE) image_upload = models.ImageField(upload_to="images", blank=True, null=True) From my DetailView to the template I am passing the Car instance's data and also the CarImage instances belonging to the specific Car. How do I create a simple, but responsive gallery of images from CarImage instances if I shall not use JavaScript frameworks like Vue, React or anything else? I am looking to get a gallery like these ones: https://photoswipe.com/ or https://www.lightgalleryjs.com/ I was not able to get them running either because of some weird JavaScript issues, or, because they require some license to be purchased. Thank you -
django user.is_authenticate dos not import
I am a beginner in Django and python and I Getting an error in Django login user in views. I want to import user.is_authenticated in function in views. Why user.is_authenticated dos not import and How can I resolve this Error? -
Error when Making Migration for Django Project
When I completed writing my models, one models, I used GenericForeignKey. Here is the code from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey # Create your models here. class Tag(models.Model): label = models.CharField(max_length=255) class TaggedItem(models.Model): # what tag applied to what object tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_type = GenericForeignKey() but I counter this error which I could not solve. SystemCheckError: System check identified some issues: ERRORS: like.LikedItem.content_type: (contenttypes.E003) 'LikedItem.content_type' is not a ForeignKey. HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field. tags.TaggedItem.content_type: (contenttypes.E003) 'TaggedItem.content_type' is not a ForeignKey. HINT: GenericForeignKeys must use a ForeignKey to 'contenttypes.ContentType' as the 'content_type' field. Your support is appreciated I tried multiple solution that I found through my research in the Internet, but none of those fixed the issue. One of the change I did is: content_type = GenericForeignKey('content_type', 'object_id') -
How to apply Count on prefetched queryset in django?
To demonstrate my use case, I've devised a similar but simpler setup as follows: class Student(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Routine(models.Model): owner = models.OneToOneField(Student, on_delete=models.CASCADE, related_name='routine') def __str__(self): return f"Routine | {self.owner}" class Activity(models.Model): title = models.CharField(max_length=100) is_active = models.BooleanField(default=True) routine = models.ForeignKey(Routine, on_delete=models.CASCADE, related_name='activities') def __str__(self): return f"{self.title} | {'Active' if self.is_active else 'Expired'} | {self.routine.owner}" routines = Routine.objects.all().prefetch_related( Prefetch('activities', queryset=Activity.objects.filter(is_active=True)) ) The queryset above will retrieve all routines and their related active activities. However, some routines might not have any associated active activities, and in such cases, their activities will be empty. routines = Routine.objects.all().prefetch_related( Prefetch('activities', queryset=Activity.objects.filter(is_active=True)) ).annotate(active_activity_count=Count("activities")).exclude(active_activity_count=0) I updated the queryset to filter out routines with empty activities after prefetching active activities but this doesn't work. It seems like Count counts actual activities instead of prefetched activities. Is there a way to make Count count prefetched activities? -
How to install chormadb on AWS EC2?
Pythoners. I need an urgent help with AWS and Django. I created AWS EC2 instance and installed django using pip install django. But when I try to install chromadb, it freezes on the stage of installing hnswlib. What is the reason? This is my second time to deploy on AWS EC2. But at the first time, my client created instance and I only used it. And there was no issue. But this time, I created instance and tried. I felt the speed is very slower than before. Are there any options of the speed of instance? Thanks -
Invalid date error with django DateField using generic UpdateView and bootstrap_datepicker_plus
Django noob but been wrangling with this for a while. When attempting to update or create a new ticket on my dev server I encounter an error beneath the field stating 'Enter a valid date.'. The relevant details models.py class Ticket(models.Model): date_of_complaint = models.DateField() ticket_new.html template <!--templates/ticket_edit--> {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>Edit</h1> <form action="" method="post">{% csrf_token %} {{ form.media }} {{ form|crispy }} <button class="btn btn-info ml-2" type="submit">Update</button> </form> {% endblock content %} views.py class TicketCreateView(LoginRequiredMixin, CreateView): model = Ticket template_name = "ticket_new.html" fields = ( "title", "date_of_complaint", "author", "customer", "description", "account_manager", ) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_form(self): form = super().get_form() form.fields["date_of_complaint"].widget = DateTimePickerInput() return form settings.py I believe the root of the issue is that the field was formerly a DateTimeField before I realized I did not want the time, only the date. I changed the model to DateTime and ran makemigrations and migrate, then changed the settings of bootstrap date picker plus to only include mm/dd/yyyy, but when I click on a date within the widget it still brings a timestamp. settings.py BOOTSTRAP_DATEPICKER_PLUS = { "options":{ "showTodayButton": True, }, "variant_options": { "date": { "format": "MM/DD/YYYY", … -
How to set a dictionary or list to a cookie and get it properly in Django?
I could set a dictionary or list to a session and get it properly as shown below: # "views.py" from django.http import HttpResponse def my_view(request): request.session['teacher'] = {'name': 'John', 'age': 36} print(request.session['teacher']) # {'name':'John','age':36} print(request.session['teacher']['name']) # John print(request.session['teacher']['age']) # 36 request.session['student'] = ['David', 21] print(request.session['student']) # ['David', 21] print(request.session['student'][0]) # David print(request.session['student'][1]) # 21 return HttpResponse("Test") But, I couldn't set a dictionary or list to a cookie and get it properly as shown below: # "views.py" from django.http import HttpResponse def my_view(request): response = HttpResponse('Test') response.set_cookie('teacher', {'name': 'John', 'age': 36}) response.cookies['student'] = ['David', 21] return response # "views.py" from django.http import HttpResponse def my_view(request): print(request.COOKIES['teacher']) # {'name': 'John', 'age': 36} print(request.COOKIES['teacher']['name']) # Error print(request.COOKIES['teacher']['age']) # Error print(request.COOKIES['student']) # ['David', 21] print(request.COOKIES['student'][0]) # [ print(request.COOKIES['student'][1]) # ' HttpResponse("Test") So, how can I set a dictionary or list to a cookie and get it properly in Django? -
How do we add functions in existing Django views?
This is my current views.py. In this case, how could I add reverse_sentence function as another view? class SentenceViewSet(viewsets.ModelViewSet): queryset = Sentence.objects.all() serializer_class = SentenceSerializer def reverse_sentence(request): if request.method == 'POST': sentence = Sentence.objects.all.values('content') reversed_words = ' '.join(reversed(sentence.split())) response_data = {'reversed_sentence': reversed_words} return JsonResponse(response_data) else: return JsonResponse({'error': 'Invalid request method. Must use POST.'}) and when I use router.register(r'reverse_sentence', views.reverse_sentence, basename='reverse_sentence') in urls.py, how come it shows AttributeError: 'function' object has no attribute 'get_extra_actions'? Thanks in advance! -
Django shuts up after pandas DataFrame.loc search by index and column combination
I am using pandas to read csv and create Dataframe with columns pilot and avarage_lap_time. So to do find average_lap_time for particular pilot I use: for pilot in race_statistic_df.loc[:, "pilot"]: needed_index = race_statistic_df.loc[race_statistic_df.loc[:, "pilot"] == pilot, "pilot"].index lap_time = race_statistic_df.loc[ needed_index, "average_lap_time" ] As soon, as my programme tries to do lap_time = django stopps working, without any arrors printed into console. Also wants to mention, for some reason just doing needed_index = is fine, but as soon as it goes into lap_time = - crash appears I am trying to get value from Dataframe by the combination of Int64Index and column name with function pd.Dataframe.loc -
How to configure dev environment with multiple containers from a git repository?
I have a full-stack application repository with the following structure: .git <- Note git repository /front-end /back-end <- python back-end /docker -front-end-dockerfile -back-end-dockerfile -front-end-setup.sh -back-end-setup.sh docker-compose.yaml After running docker compose build and docker compose up -d in the repository's root level, I get 2 containers: front-end-dev back-end-dev Both work fine, however, when building, both the front-end and the back-end get split up between both containers. I want to develop inside each container and still want git to track changes, despite each container containing either the back-end or front-end directory. Currently I see two options: develop outside the container, which mean I won't have a working interpreter for intellisense/pylance. develop in the container, which means I won't have git working. Is there a way to have both 1) git and 2) intellisense/pylance working? Any suggestions and recommendations on how to develop using this configuration would also be appreciated. -
Is the Basic File Upload example in the Django documentation correct?
I'm using python 3.10.5 with django 4.2.2. The djangoproject documentation for a Basic File Upload has the following example for uploading a file: Consider a form containing a FileField: forms.py from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm # Imaginary function to handle an uploaded file. from somewhere import handle_uploaded_file def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) This is my upload.html: <!DOCTYPE html> <html> <head> <title>File Upload</title> </head> <body> <h1>File Upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file" required> <button type="submit">Upload</button> </form> </body> </html> When I run that code, it fails the... if form.is_valid() ...test in views.py because "title" is empty, but it's defined as required in the forms.py. If I simply comment out the... title = forms.CharField(max_length=50) ...line from forms.py, then it works fine, so what is that "title = forms.CharField(max_length=50)" line for in forms.py? -
Django-filters field forms doesn't show in HTML
I try to use django-filters in my Django app. I am using it with pagination. Page renders properly (it just works), but without filter fields that I created. Only submit button shows. I will be really thankful for any help i don't know what I am doing wrong. I want to use ModelChoiceFilter to filter objects from Image model, by their foreign key Publisher filters.py # filters.py import django_filters from django import forms from .models import Image, Publisher, Author class ImageFilter(django_filters.FilterSet): class Meta: model = Image fields = ['title', 'created'] class ImageForeignFilter(django_filters.FilterSet): wydawca = django_filters.ModelChoiceFilter( queryset=Publisher.objects.all(), empty_label="Wszyscy wydawcy", label="Wydawca", widget=forms.Select(attrs={'class': 'form-control'}), ) class Meta: model = Image fields = ['created', 'wydawca'] models.py # models.py class Publisher(models.Model): name = models.CharField(max_length=200, default='',blank=True, verbose_name="Nazwa wydawcy", help_text="Nazwa wydawcy") urlglowna = models.URLField(max_length=2000, default='', blank=True, verbose_name="Strona główna", help_text="Adres strony") def __str__(self): return '{} {}'.format(self.name,self.urlglowna) class Image(models.Model): url = models.URLField(max_length=2000, verbose_name="Link do znaleziska", help_text="Podaj bezpośredni link") created = models.DateField(auto_now_add=True) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE, null = True, blank=True) views.py # views.py def image_list(request): images = ImageForeignFilter( request.GET, queryset=Image.objects.filter(status=Image.Status.PUBLISHED).order_by('created') ).qs paginator = Paginator(images, 15) page = request.GET.get('page') try: page_number = paginator.page(page) except PageNotAnInteger: page_number = paginator.page(1) except EmptyPage: page_number = paginator.page(paginator.num_pages) return render(request, 'images/image/list.html', {'section': 'images','images': images, 'page_number': page_number}) … -
new Media files in django gets 404 not found nginx
My old media files (photos) are loading correctly but when new medias are uploaded I'm getting 404 not found by nginx. I used docker and this is my volume part of docker compose: volumes: - '/root/docker-compose/data/media/MEDIA/:/app/MEDIA' all media files are loading correctly and saved correctly but when new files added I get 404 not found. although all files are uploaded correctly and I can see them not only in docker container but also outside of it. but still getting 404 not found! I tried changing media files and reseting all docker compose details and uwsgi configs. but still not fixed. and also try refactor settings and urls. -
"Column 'group_id' cannot be null". i cant register superuser?
as i said i cant register superuser. this is not my project so I don't know it fully. during the createsperuser, django requires a password and a phone number and that's it. models.py class User(AbstractBaseUser): is_required = models.BooleanField(verbose_name=_('Статус подтверждения'), default=False, blank=True) is_staff = models.BooleanField(verbose_name=_('Статус персонала'), default=False) group = models.ForeignKey('Groups', verbose_name=_('Группа'), on_delete=models.CASCADE, ) center = models.ForeignKey('Centers', verbose_name=_('Центр'), on_delete=models.PROTECT, null=True) disease = models.ForeignKey('Disease', verbose_name=_('Заболевание'), on_delete=models.SET_NULL, null=True) number = models.CharField(verbose_name=_('Номер'), max_length=30, unique=True, null=True) email = models.CharField(verbose_name=_('Электронный адрес'), max_length=100, blank=True, null=True) first_name = models.CharField(verbose_name=_('Имя'), max_length=20, null=True, blank=True) last_name = models.CharField(verbose_name=_('Фамилия'), max_length=30, null=True, blank=True) surname = models.CharField(verbose_name=_('Отчество'), max_length=40, null=True, blank=True) birthday = models.DateField(verbose_name=_('День рождения'), null=True, blank=True) image = models.ImageField(verbose_name=_('Фотография Пользователья'), upload_to='users_photos/', blank=True, default='media/site_photos/AccauntPreview.png') country = models.ForeignKey('Countries', on_delete=models.PROTECT, verbose_name=_('Страна'), null=True) city = models.CharField(verbose_name=_('Город'), max_length=50, null=True) address = models.CharField(verbose_name=_('Адрес'), max_length=100, unique=False, null=True) created_at = models.DateTimeField(verbose_name=_('Дата создания'), auto_now_add=True, blank=True, null=True, ) updated_at = models.DateTimeField(verbose_name=_('Дата изменения'), auto_now=True, blank=True, null=True, ) USERNAME_FIELD = 'number' objects = UserManager() def __str__(self): return self.number def delete(self, using=None, keep_parents=False): group = Groups.objects.get(id=self.group_id) group.number_of_people -= 1 group.save(update_fields=['number_of_people']) super(User, self).delete() def has_perm(self, perm, obj=None): return self.is_staff def has_module_perms(self, app_label): return self.is_staff class Meta: verbose_name_plural = 'Пользователи' verbose_name = 'Пользователья' ordering = ['-created_at'] class Groups(models.Model): name = models.CharField(verbose_name=_('Название Группы'), max_length=100, null=True) number_of_people = models.IntegerField(verbose_name=_('Количество людей'), default=0) def … -
How long does it take to install chromadb on Ubuntu?
I have developed a django project and am trying to deploy to AWS EC2 Instance. My project uses chromadb so I try to install with this command. pip install chromadb Then it installs all the related dependencies but when it starts to install hnswlib, it freezes. Building wheels for collected packages: hnswlib Building wheel for hnswlib (pyproject.toml) ... \ It doesn't give any error but no progress. How to handle this? Should I wait? This was the second time for me to deploy this kind of project but at the first time, I installed chromadb without any issue. But at that time, I used the Instance that my client has provided. Now I created the Instance with myself. Are there any kind of settings about Instance? Thanks -
Django BaseFormSet and formset_factory not working properly
I took reference from https://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html to create a formset that creates multiple users from a model named Office365User that has a foreign key field linked to another model named Domain, but the formset is not saving the form. It would be really helpful if the problem can be identified in this or an alternative solution can be suggested. ############models.py########## class CloudFlareAccount(models.Model): username = models.CharField(max_length=200, null=False) password = models.CharField(max_length=200, null=False) api_key = models.CharField(max_length=500, null=False) date_created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CMSUser, null=False, on_delete=models.CASCADE) def __str__(self): return self.username class Domain(models.Model): name = models.CharField(max_length=150, null=False) date_created = models.DateTimeField(auto_now_add=True) is_verified = models.CharField(max_length=10, default='Not Specified') cloud_flare_account = models.ForeignKey(CloudFlareAccount, null=False, on_delete=models.CASCADE) def __str__(self): return self.name class Office365User(models.Model): name = models.CharField(max_length=200, null=False) issuer = models.ForeignKey(Domain, null=False, default='Select Issuer', on_delete=models.CASCADE) mail = models.CharField(max_length=150, null=False, unique=True) password = models.CharField(max_length=100, null=False) date_created = models.DateTimeField(auto_now_add=True) is_licensed = models.CharField(max_length=10, default='True') is_active = models.CharField(max_length=10, default='Not Specified') def __str__(self): return self.name ############forms.py############ class CreateUser(ModelForm): def __init__(self,*args, listt=None, **kwargs): super(CreateUser, self).__init__(*args, **kwargs) if listt is not None: self.fields['issuer'].queryset = listt class Meta: model = Office365User fields = ['name', 'issuer', 'mail', 'password'] class CreateBulkUser(BaseFormSet): def clean(self): """ Adds validation to check that no two links have the same anchor or URL and that all links have both … -
Why isn't CSS loading on my django website?
I have managed to upload my django project to a server(www.sb10-89.co.uk but the css file isn’t working. Even the admin page doesn't look right, again i guess its missing a css page. The code below is from my settings file. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'staticfiles/bands_ratings' See below image for file structure. Connecting css in html <link rel="stylesheet" href="{% static 'Style.css' %}" > Project level urls file code """download_band_rater_v4 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path , include from django.views.generic import RedirectView from django.contrib.auth.views import LogoutView urlpatterns = [ path("admin/", admin.site.urls), path('bands_ratings/', include ('bands_ratings.urls')), path('',RedirectView.as_view(url='bands_ratings/signup/')), path('accounts/', include('django.contrib.auth.urls')) ] #urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
How can I get the user's data that is not logged in from a model
I have this model that represents a connection between two users: class Connection(models.Model): userone = models.OneToOneField(User, on_delete=models.CASCADE, related_name="downconnections") usertwo = models.OneToOneField(User, on_delete=models.CASCADE, related_name="upconnections") date_established = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "connection" verbose_name_plural = "connections" ordering = ["date_established"] db_table = "connections" def __str__(self): return f"{self.userone} is connected to {self.usertwo}" I would like to the serialized data of the user that is not logged in but no matter what I get a key error "request" Here is the serializer: class ConnectionSerializer(serializers.ModelSerializer): user = serializers.SerializerMethodField() class Meta: model = Connection fields = [ "id", "user", "date_established" ] def get_user(self, obj): request = self.context.get("request") logged_in_user = getattr(request, "user", None) if logged_in_user: if obj.userone == logged_in_user: return UserSerializer(obj.usertwo).data elif obj.usertwo == logged_in_user: return UserSerializer(obj.userone).data return None def to_representation(self, instance): return self.get_user(instance) Why is this not working? -
Integrating Veracode logging formatter library into Django project
there! I'm currently working on resolving a vulnerability issue reported by Veracode, specifically CWE 117 (Improper Output Neutralization for Logs). To address this issue, I need to implement the Veracode logging formatter library available at logging-formatter-anticrlf in my Django project. In Django, there is a configuration file called settings.py where the logging behavior for the application is defined using formatters, handlers, and loggers. Here's an example of the configuration: # Logging LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {filename}:{lineno} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'file': { 'level': 'DEBUG', 'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler', 'filename': os.path.join(BASE_DIR, '..', '..', 'log-debug.log'), 'maxBytes': 1024 * 1024 * 1024, 'backupCount': 365 * 7, 'formatter': 'verbose', }, }, 'root': { 'handlers': ['console', 'file', 'errorfile'], 'level': 'DEBUG', }, 'loggers': { 'root': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': True, 'level': 'DEBUG', }, 'django.request': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, 'django.server': { 'handlers': ['console', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, 'webportal': { 'handlers': ['console', 'file', 'errorfile'], 'propagate': False, 'level': 'DEBUG', }, } } In each module of the Django application, the LOGGER is instantiated … -
Reduce database hit when using django-taggit and mymodel.tags.all in a template
I'm using django-taggit in Django 3.2 and can't figure out how to prevent it from hitting the database for every object in a list view template. Here's how I'm using it: class Quest(TagsModelMixin, models.Manager): # etc. In a ListView html template, I am displaying all Quest objects and their tags like this: {% for obj in quest_queryset %} {{obj.name}}: {{ obj.tags.all }} {% endfor %} At first, this was hitting the DB twice per object. I found that if I prefetch_related I could remove half of them: quest_queryset = quest_queryset.prefetch_related('tags') But I'm still getting one hit per object. How can I eliminate this repetition? Here's the offending query as shown by django-debug-toolbar, when there are 5 Quest objects. -
Django: How to format nested data, including a list of dictionaries, as multipart/form-data for posting?
How can I format nested data, including a list of dictionaries, as multipart/form-data for posting in Django? DATA = { "title": "Test Entry", "subcategory_id": subcategory.pk, "description": "Description for test entry.\n" * 2, "price": 150_000.00, "publisher": publisher.pk, "location": { "town": "Ant Town", "landmark": "Pink Poolside", }, "cover": _simple_image(), "images": [_simple_image(), _simple_image()], "specs": [ {"name": spec_field1.name, "value": "1000", "field_id": spec_field1.id}, {"name": spec_field2.name, "value": "SSD", "field_id": spec_field2.id}, ], "tags_ids": [tag.id for tag in TagFactory.create_batch(2)], } def test_something_doesnt_go_wrong(self): self.client.force_authenticate(user=UserFactory()) url = reverse("entries:entry-list") response = self.client.post(url, data, format="multipart") self.assertEqual(response.status_code, 201) self.assertEqual(len(response.data["images"]), 2) self.assertEqual(len(response.data["tags"]), 2) This is the error I get when I run my test suite. AssertionError: Test data contained a dictionary value for key 'location', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. Is this even legal? Is the API badly designed (I'm wondering). What can I do here? I can't seem to wrap my head around how to achieve this using QueryDict.