Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination not working with django-tables2
I don't get any pagination at all, it is supposed to be automatic. I am using django_mail_admin for the models Table code class IncomingTable(tables.Table): class Meta: model = IncomingEmail template_name = "django_tables2/bootstrap.html" fields = ("id", "subject",) View code, there seems to be some duplication of models class IncomingMail(SingleTableView): table_class = IncomingTable queryset = IncomingEmail.objects.all().order_by("-id") template_name = "incoming.html" Any help would be great, thanks. -
List of all values in Django model attribute
I am creating an e-commerce website and I want to allow the user to filter the search results by various products specs. I want to return in my API a meta dictionary containing all the values each product attribute has. For example, if the user searches for 'iPhone', the response should look like this: { 'data': { ... }, 'meta':{ 'options':{ 'model': ['iPhone 12', 'iPhone 13', 'iPhone 14'], 'manufacturer': ['Apple'], ... } } } Here is my model for reference: class Product(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=False, blank=False) description = models.TextField(max_length=2048, null=False, blank=True) price = models.FloatField(null=False, blank=False, default=0) model = models.CharField(max_length=255, null=False) manufacturer = models.CharField(max_length=255, null=False) seller = models.CharField(max_length=255, null=False) So far i have tried using this, where products is my QuerySet of Product entities after applying the 'iPhone' search: products.values_list('model') The problem with this is that it returns a QuerySet, but I want a list. I was hoping there is a one-liner that I don't know about. -
In Django Admin, how do I reference reverse foreign key relations for `list_display`?
In my app, we may have new languages or dialects of languages appear at any time, and text written in one language or dialect may need to be translated into another. That's why we handle text by relating text in different languages into "families" (i.e. the translation set into different languages). class StringFamily(models.Model): id = models.AutoField(primary_key=True) # plus some other fields class String(models.Model): id = models.AutoField(primary_key=True) # the reference to StringFamily family = models.ForeignKey(StringFamily, null=False, on_delete=models.CASCADE) # other important stuff language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) dialect = models.ForeignKey(Dialect, null=True, on_delete=models.SET_NULL) text = models.TextField(null=False) Unfortunately this complicates using the Django ORM. When we hit a problem with the app, we're generally saved by using raw SQL to deal with this setup. But I also want to use the Django admin, and I don't see any SQL workaround there. In particular, there are all sorts of models that have some text that may appear in multiple languages, like so: class Element(models.Model): id = models.AutoField(primary_key=True) element_role = models.ForeignKey(ElementRole, null=False, on_delete=models.RESTRICT) string_family = models.ForeignKey(StringFamily, null=True, on_delete=models.SET_NULL) # plus more fields What I want is to be able to something like this (everything here works except "display_english_string"): class ElementAdmin(admin.ModelAdmin): list_display = ("element_role", "display_element_type", "display_english_string") This works … -
Goal: How to dynamically create field named status to be display end user side using django?
I am working on a personal web page that ideally would tell me the status of my groceries for example: expired and unexpired based on some input such as date bought and expiration date printed on the products. I am new to the django framework but I been learning a lot online and using chatgpt, youtube and reading articles to explain some of the concepts and how to use it. I am currently stuck on why the code that dynamically generates the status field in the function get_context_data(), at the moment it works but I am confused why it works since it was a suggestion by chatgpt. I am unsure why do I have to write context['allproducts'] = productStatus instead of simply create a context['status'] = productStatus then call status in the variable for all elements in the Products model. The datatype for the productStatus is Queryset but it appears to be behaving as a dictionary when I use the assignment operation for product.status. I you could explain why it is actually working would be amazing since it is not obvious to me how the productStatus is receving this product.status column. Is this the best practice on how to dynamically … -
Django - HTTP ERROR 405 - Method Not Allowed (GET): /account/logout
When try to click logout button, shows this text In urls.py from django.urls import path from users_app import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register', views.register, name='register'), path('login', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout') ] In logout.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} <title>Logged Out - Taskmate</title> {% endblock title %} {% block content %} <div class="container"> </br> <h4>Logged Out Of TaskMate, Thank You For Using Us!</h4> </div> {% endblock content %} type here When clicked on to Logout button, expected to appear the text as "Logged Out Of TaskMate, Thank You For Using Us!"your text -
How to make a Custom Response class in Django REST framework
I am using django rest framework api as the backend for my project. I treid making a custom Response class for the project and put together the code shown below: class CustomResponse(Response): def __init__(self, error=None, message=None, data=None, status_code=None, *args, **kwargs): self.error = '' if error is None else error self.message = {} if message is None else message self.data = {} if data is None else data self.status_code = status.HTTP_200_OK if status_code is 1 else status.HTTP_400_BAD_REQUEST return super().__init__(data = {'error': self.error, 'message': self.message, 'data': self.data, 'status_code': self.status_code}, status=self.status_code, *args, **kwargs) Is there a better way to do this? Like should I expand some more on this CustomResponse class or should I create a completely new one in some other way? The CustomResponse is to be used for returning serialized data from Views that are made by inheriting the APIView. I was using Response directly for this and I wanted to make something that allows me to add extra details easily according to whether the Response was for something that succeeded or if it had some sort of errors. I searched a lot and everything that I found was similar to the code I made above. But I feel like something … -
How can I handle user authentication in my Remix app if I'm running a DRF backend?
I have Remix app which which relies on a django rest framework api as the backend for data(including users'). In the API, I use JWT to handle user authentication but now that i want to connect it to my remix app, I'm not sure of the best approach on implementing this jwt authentication from the frontend(remix app) or if I should be using a different authentication backend entirely in my API. I've created a sign up page that sends user credentials to the sign up endpoint which creates the user and to sign in, I also send user credentials to the login endpoint which returns the access and refresh tokens. For now, I save this tokens in localStorage(i know this is insecure) and include them in the headers of any requests to endpoints with auth or permissions. Also, in the root module of my remix app, i get the access token(if avaliable) from LS and make a request to the endpoint to get the current user context and pass this into the root component as context. This is stressfull, inefficient and insecure. What is a better, more secure approach to achieve this? -
Django FileResponse crashes with large files
...I have a Django application with a lot of data and a MariaDB database running on a Raspberry Pi (OS = Debian 12). The application uses Daphne as Webserver because there are also Django Channels components in there (Websocket). Now I want to implement a backup feature, that automatically dumps the database, zips together the dump with the other data files and has the browser automatically download the ZIP-file. So I made a view for the download: def downbackup(request): if request.user.is_superuser: filename = '../temp/backup/backup.zip' sourcefile = open(filename, 'rb') return FileResponse(sourcefile) else: return(HttpResponse('No Access.')) That view is called from the relevant template via url and verything is fine. Until we meet large files in real live. In this case (filesize around 6 GB) Daphne immediatly stops operation, and the Raspi crashes so deep that I have to switch power on and of. Also, in Monitorix I see huge memory consumption spikes after these crashes. But there is no error message in the Daphne logs, in the Django logs (incl. debug-setting) nor in the journalctl. Nginx (the reverse proxy) reports an uplink timeout (504). I think I learned from the Django documentation the FileResponse buffers the file to avoid memory consumption, but … -
Hosting static site and Django apps on Ubuntu with Nginx
I am hitting a wall on what to do here. I have tried so many variations of solutions on line and none seem to work. This is what I want to do: I have a domain example.com and a VPS running Ubuntu wth a nginx server. I have a static site that I would like accessible when going to example.com. I have a django project and applications that I would like accessible when going to example.com/apps/. I would like example.com/apps/ to be the root for all files that belong in the project. So far, my basic set up is: I can access my static site via example.com. The files are sitting in /var/www/example.com/html. I cannot access my django app correctly. When I try going to www.example.com/apps/, I can see the Django test page when you first install the software and have it running (with the rocket ship). However, when I go to example.com/apps/admin, the browser URL changes to example.com/admin and I get a 404. I have tried many things here that end up not working. I get some kind of error with the server or with Django. Nginx Using proxy_set_header SCRIPT_NAME /apps (this doesn't seem to do anything). Rewriting the … -
Problem with non-Latin letters in website links
I am programming a website using django. I have placed my website in namecheep hosting and in pythonanywhere (for testing only). I faced a problem when adding Arabic links in the project, in namecheep hosting, where when I choose the link that contains an Arabic word, it directs me directly to the page page not found. In pythonanywhere and in localhost, which accepts Arabic links normally Now I want to know whether namecheep does not accept Arabic links? Are there any settings in cpanel to solve the problem? Is there a solution to the problem? I have verified that the problem is not in the code, but rather a settings problem in the hosting -
'NoneType' object has no attribute 'user' in django
def getuser(request): if request is None: return CustomUser.objects.none() return CustomUser.objects.filter(username=request.user) class sales_summary_filter(django_filters.FilterSet): username = django_filters.filters.ModelChoiceFilter(queryset=getuser) class Meta: model = sales_invoice fields= ('username', 'voucher_no','client') 'NoneType' object has no attribute 'user' -
Django ManyToManyField Validators
What's the best solution to apply following requirement? In my model I have 2 manytomany fields (team1 and team2) which contains both a list of players. If a player is in team1 he cannot be also in team2. How can I implement this logic? First idea is to use validators, but they are not supported by manytomanyfield as in the django doc, so i'm humbling ask your support for a better solution please. As of now not a single view expose a POST to create matches and only admin via django admin should be able to create matches. here the Model class Match(models.Model): date=models.DateField(auto_now_add=False,auto_now=False) team1=models.ManyToManyField(Player,related_name='team_1') team2=models.ManyToManyField(Player,related_name='team_2') score_team1=models.IntegerField( validators=[MinValueValidator(0)] ) score_team2=models.IntegerField( validators=[MinValueValidator(0)] ) -
Efficient Django query for model with foreign key to itself
I'm building a simple blog post website using Django. Basically there are two models: Post and Comment, where the comment model looks like this: class Comment: post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') # A comment can have many replies, and an user can only reply to the "parent" comment (A comment which isn't a reply to any comment) reply = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) likes = models.ManyToManyField(User, 'like_comments', blank=True) # Some other fields def save(self, *args, **kwargs): if self.reply is not None: self.post = self.reply.post super(Comment, self).save(*args, **kwargs) I have a class-based view which inherits Django generic DetailView to retrieve a specific post. The problem is I also want to retrieve all comments of the post, along with the replies of those comments and number of likes in an efficient way. What would be the most performant way to do so? I came up with the following way: from django.db.models import Prefetch from django.views.generic.detail import DetailView # Some views here ... class PostDetailView(DetailView): model = Post template_name = 'core/post_detail.html' context_object_name = 'post' def get_queryset(self, **kwargs): return Post.objects.prefetch_related(Prefetch('comments', queryset=Comment.objects.annotate(num_likes=Count('likes')))) However, when I inspect the query using QuerySet.query, the raw SQL looks the same as if I used "Post.objects.all()". I'm not sure if … -
why css is not working on the options of selector in html?
this is my html code <div class="blackbar" id="blackbar"> <div class="title"> <span id="titleText">Screen</span> <input class="search" type="text" id="search" placeholder="Search Movie" > <select class="dropdown" id="fruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> <option value="grape">Grape</option> </select> </div> </div> this is my css code for this #fruit { margin-left: 150px; width: 225px; height: 42px; border-radius: 12px; font-size: 24px; border: none; font-weight: lighter; box-shadow: inset 1px 1px 5px rgba(0,0,0, 0.8); padding-left: 50px; /* Add padding for indentation */ overflow-y: auto; /* Enable vertical scrolling */ max-height: 150px; /* Set maximum height for the dropdown */ } /* Style the options */ #fruit option { font-size: 24px; color: #333; background-color: #fff; padding: 10px; border-radius: 12px; } /* Style the hover state */ #fruit option:hover { background-color: #cef106; color: #000; } help me please ! see why my css is not working the options, i want my the hover to be yellow but it still blue and border rounding is also not working its working for the select but not for its options help me please -
Django "KeyError at "
i'm learning python / django and doing this weather app with api with youtube tutorial. But when i enter city name i got an error. I even copied hole tutorial code from github, but i still got same error and this just drives me crazy. And i allways get error on those 2 lines: weather_data1, daily_forecasts1 = fetch_weather_and_forecast(city1, api_key, current_weather_url, forecast_url) and for daily_data in forecast_response['daily'][:5]: enter image description here from django.shortcuts import render import requests import datetime def index(request): api_key = 'my api' current_weather_url = 'https://api.openweathermap.org/data/2.5/weather?q={}&appid={}' forecast_url = 'https://api.openweathermap.org/data/2.5/onecall?lat={}&lon={}&exclude=current,minutely,hourly,alerts&appid={}' if request.method == 'POST': city1 = request.POST['city1'] city2 = request.POST.get('city2', None) weather_data1, daily_forecasts1 = fetch_weather_and_forecast(city1, api_key, current_weather_url, forecast_url) if city2: weather_data2, daily_forecasts2 = fetch_weather_and_forecast(city2, api_key, current_weather_url, forecast_url) else: weather_data2, daily_forecasts2 = None, None context = { 'weather_data1': weather_data1, 'daily_forecasts1': daily_forecasts1, 'weather_data2': weather_data2, 'daily_forecasts2': daily_forecasts2, } return render(request, 'weatherApp/index.html', context) else: return render(request, 'weatherApp/index.html') def fetch_weather_and_forecast(city, api_key, current_weather_url, forecast_url): response = requests.get(current_weather_url.format(city, api_key)).json() lat, lon = response['coord']['lat'], response['coord']['lon'] forecast_response = requests.get(forecast_url.format(lat, lon, api_key)).json() weather_data = { 'city': city, 'temperature': round(response['main']['temp'] - 273.15, 2), 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], } daily_forecasts = [] for daily_data in forecast_response['daily'][:5]: daily_forecasts.append({ 'day': datetime.datetime.fromtimestamp(daily_data['dt']).strftime('%A'), 'min_temp': round(daily_data['temp']['min'] - 273.15, 2), 'max_temp': round(daily_data['temp']['max'] - 273.15, 2), 'description': daily_data['weather'][0]['description'], 'icon': … -
Is it safe to manually delete django_sessions data rows in ProsgreSQL table?
First, let me state that I know about the Django Python session cleanup scripts, but I currently don't have easy access to the shell where the Django framework is hosted. However, I have access to the backend PostgreSQL database. I'm trying to reduce the size of the over-data tables, and I noticed that the django_session table now has over 2.8 million rows. I don't think there's ever been a cron job setup for cleanup sessions since this website started running in 2016. From what I read, the django_session table stores user sessions when they log in, and if they don't log out, it stores them. Therefore, could I remove any rows older than a specified date? DELETE FROM public.django_session WHERE expire_date < '2023-01-01' I plan to test this out on a test server, but I would like to know whether it's the right approach. Otherwise, I'll have to figure out how to get access to run the shell script to do the cleanup. -
why the get method not able to use django restframework's request?
I have below code snippet class ListAccTokenView(ListAPIView): serializer_class = TokenSerializers def get_queryset(self): org_id = self.kwargs.get('id') entity_id = self.kwargs.get('comp') queryset = ErpLinkToken.objects.filter(id=id, comp=comp) return queryset class MeCompInfo(APIView): @staticmethod def get_company_info(request): get_token = ListAccTokenView.as_view() queryset = get_token(Request(Request(request=request)).data token = queryset[0]['token'] if queryset else None account_token_client = create_merge_client(token) I am getting below error AssertionError at /api/comp The `request` argument must be an instance of `django.http.HttpRequest`, not `rest_framework.request.Request`. I tried importing from django.http import HttpRequest and converting it to rest_framework instance as seen below, but not helping class MeCompInfo(APIView): @staticmethod def get_comp_info(request): django_request = HttpRequest() django_request.method = request.method django_request.GET = request.query_params get_token = ListAccTokenView.as_view() queryset = get_token(Request(request=django_request)).data ac_token = queryset[0]['token'] if queryset else None account_token_client = create_merge_client(ac_tok) def get(self, request, *args, **kwargs): api_log(msg="Processing GET request...") organization_data = self.get_comp_info(request) how can I fix this? -
how to connect django models?
I have two models, applications and additional information. class Submissions(models.Model): def create_new_ref_number(): return str(random.randint(1000000000, 9999999999)) submissions_number_id = models.CharField(max_length=10,blank=True, unique=True, default=create_new_ref_number,editable=False) client = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, related_name='submissions') contents = models.TextField() status = models.CharField( max_length=30, choices=STATUS, default='1') submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='submissions_supervisor') contractors = models.ManyToManyField(User, related_name='contractors') submissions_cause=models.CharField(max_length=30, choices=CAUSE, default='3') execution_date = models.DateField(null=True, blank=True) details_planned_service=models.TextField(null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class AdditionalInfo(models.Model): submission = models.ForeignKey(Submissions, on_delete=models.CASCADE, related_name='additional_info', default='') contents = models.TextField() submissions_supervisor = models.ForeignKey(User,on_delete=models.SET_NULL, null=True, related_name='additional_info_supervisor') created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) The website displays all submissions according to the date they were scheduled, and it is also possible to click the mini preview which opens the MODAL WINDOW, and here is the problem because the data from the submission model is all displayed, but I don't know how to add additional information to it. -
Deleting 'disabled' when saving changes in formset
I'm creating a table with a formset from a queryset of existing objects. Few fields in the table should change, and other fields should be displayed, but not changed. For displaying non-editable fields, I use the widget with 'disabled' in the form. GET request does everything right. But the POST request does not save changes to the resolved fields, because unresolved fields are required and have disabled and blocks the sending of existing values. I tried to use jQuery from the example, but it doesn't work. Moreover, I do not understand how I can refer to different ids in the formset. Models: class Order(models.Model): car = models.ForeignKey( Car, blank=True, null=True, on_delete=models.PROTECT, related_name='car_orders', ) department = models.ForeignKey( Department, blank=False, null=False, on_delete=models.PROTECT, related_name='dep_orders', ) ... View def orders_list(request, year, month, day): orders = Order.objects.filter( order_date__year=year, order_date__month=month, order_date__day=day ) if request.method == 'POST': formset = OrderCloseFormSet( request.POST or None, queryset=orders, prefix='order' ) if formset.is_valid(): formset.save(commit=False) for form in formset: form.save() formset = OrderCloseFormSet(queryset=orders, prefix='order') context = {'orders': orders, 'formset': formset} return render(request, 'orders/orders_list.html', context) Form class OrderCloseForm(forms.ModelForm): class Meta: model = Order fields = ( 'type_car', 'department', ... ) widgets = { 'car': forms.Select(attrs={'style': 'width: 100%'}), 'department': forms.Select(attrs={'disabled': 'True', 'style': 'width: 100%'}), ... … -
Solution for Django model composite foreign keys
I’m working with two models in Django: Order and OrderItems. I want to establish a one-to-one relationship between them using two columns instead of the usual single column. I’m aware of solutions like SQL Alchemy’s ForeignKeyConstraint and the django-composite-foreignkey package, but I’d prefer not to use ForeignKeyConstraint and the latter isn’t compatible with Django 4.0. Is there an alternative solution available for creating a composite foreign key that references two columns in Django 4.0? class Orders(models.Model): objects = models.Manager() id = models.AutoField(primary_key=True) order_id = models.CharField(max_length=255) --------> here it should reference with two columns ( id and department_id ) orderItem = models.ForeignKey('OrderCustomers', on_delete=models.PROTECT, db_column='order_item_id', to_field='id') order_item_id = models..CharField(max_length=255) department_id = models.CharField(max_length=255) created_at = DateTimeWithoutTZField(auto_now_add=True) updated_at = DateTimeWithoutTZField(auto_now=True) def __str__(self): return self.order_id -
problem occured during running a django program
from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\LENOVO\OneDrive\Desktop\internet and intranet\django-ecommerce\venv\lib\site-packages\django\utils\encoding.py) i am trying to run django program -
Error in setting SIGNING_KEY in djangorestframework-simplejwt
It's a bit odd! I have separated the base settings from the local settings. For instance, I moved SECRET_KEY into an other file called local.py as my local settings: SECRET_KEY = env( "DJANGO_SECRET_KEY", default="MY_DEFAULT_SEC_KEY" ) and the following is my simple-jwt settings in base.py which does not contain any variable called SECRET_KEY(since I moved it into local.py): REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("Bearer", ), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "SIGNING_KEY": env("SIGNING_KEY"), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", } I want to set a different SIGNING_KEY but I get the following error: File "/usr/local/lib/python3.11/site-packages/rest_framework_simplejwt/settings.py", line 19, in celery_worker-1 | "SIGNING_KEY": settings.SECRET_KEY, celery_worker-1 | ^^^^^^^^^^^^^^^^^^^ celery_worker-1 | File "/usr/local/lib/python3.11/site-packages/django/conf/init.py", line 111, in getattr celery_worker-1 | raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") celery_worker-1 | django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I don't need to set SECRET_KEY according to the documentation when I set a different SIGNING_KEY. However, it says I need to give it a value. What is the problem? -
Django Ajax Request - JSONDecodeError: Expecting value
I am working on a Django project where I have a course enrollment system. I have a button on my HTML page that, when clicked, triggers an Ajax request to submit enrollment data. The button redirects me to a page with a form where a student can fill in data such as name, surname, phone number, email, and language level. However, I am facing an issue where the values from the HTML attributes (data-language-id, data-course-name, data-price) are not getting passed into the Django view. The Django view returns a JSONDecodeError: Expecting value when trying to parse the request body. I intend to save this data into two tables in my database: Student and Enrolment. Any insights or suggestions on how to resolve this issue and successfully save the data into these tables would be greatly appreciated. Thank you! HTML Code: <!-- This is the button triggering the Ajax request --> <div class="block1_1"> <!-- ... other HTML content ... --> <div class="block__button" onclick="submitData(this)" data-language-id="1" data-course-name="Стандарт" data-price="6000"> <a href="{% url 'index3' %}">Записатися</a> </div> </div> JavaScript Code: function submitData(clickedBlock) { var languageId = clickedBlock.getAttribute('data-language-id'); var courseName = clickedBlock.getAttribute('data-course-name'); var price = clickedBlock.getAttribute('data-price'); $.ajax({ url: "/index3/", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: … -
Django TypeError: save() got an unexpected keyword argument 'force_insert'
I get an error when creating a new user via a form on the site, or via python manage.py createsuperuser: TypeError: save() got an unexpected keyword argument 'force_insert' signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I tried passing args, **kwargs to get def save(self, *args, **kwargs) and super(Profile, self).save(*args, **kwargs). I also tried passing these arguments to signals.py. The error remains, I don't know what to do. If you need more code from any script, I will provide it all Read other threads on this topic, but the solution didn't work for me 😥 -
Incorrect output of parents for a search result in a tree structure
I’m trying to enter parents for the search result so that the user understands in which node the value is located. The output is not correct. How to remove the extra ones???? models.py class Composition(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', db_index=True, verbose_name='Родительская категория') mapping = models.BooleanField(default=False, verbose_name='Отображение в дереве состава') id_drawing = models.ImageField(upload_to='media/image/', blank=True, null=True, default='null', verbose_name='Рисунок') position = models.PositiveIntegerField(verbose_name='Номер позции в родительской категории') designstion = models.CharField(max_length=255, primary_key=True, verbose_name='Обозначение') name = models.CharField(max_length=255, default='null', verbose_name='Наименование') description = models.TextField(blank=True, null=True, default='null', verbose_name='Описание') quantities = models.PositiveIntegerField(blank=True, null=True, default='null', verbose_name='Количество в родительской категории') slug = models.SlugField(verbose_name="Альт. заголовок") objects = TreeManager() @property def drawing_url(self): if self.id_drawing and hasattr(self.id_drawing, 'url'): return self.id_drawing.url class MPTTMeta: order_insertion_by = ['designstion'] class Meta: # unique_together = [['parent', 'slug']] verbose_name = 'Спецификация' verbose_name_plural = 'Спецификация' def get_absolute_url(self): return reverse('manual:catalog_page', args=[str(self.pk), str(self.slug)]) def __str__(self): return "%s (%s)" % (self.name, self.designstion) view.py def get_ancestors(unit): unit.designstion = unit.get_ancestors() return unit def catalog(request): catalog_list = models.Composition.objects.filter(mapping=True) if request.GET.get('q') != None: question = request.GET.get('q') ** seach_catalog =map(get_ancestors, Composition.objects.filter(Q(name__icontains=question)|Q(designstion__icontains=question)))** return render(request, 'catalog.html', { 'catalog_list': catalog_list, 'seach_catalog': seach_catalog, }) else: return render(request, 'catalog.html', { 'catalog_list': catalog_list, }) html {% for unite in seach_catalog %} {{ unite.name}} <div> {{ unite.designstion }}</div> </li> {% endfor %} Output results: …