Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which should i learn now, Flask or Django [closed]
I just learnt core python for software development and now i am trying to pick up a framework, which of the framework would you advise me to pick up?? Flask or Django -
Nginx 403 fobidden for static files in django
I deployed my webiste on a linux server but the problem is that css is not loading. NGINX server { listen 80; server_name ip; location = /favicon.ico { access_log off; log_not_found off; } # Serve static files location /static/ { root /home/paul/myproject; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Inside of myproject I have below directories and file myproject(dir-here are settings.py, etc) env(dir) manage.py main(dir) requirements.txt static(dir) static admin(dir) css(dir) media(dir) settings.py STATIC_URL = '/static/' import os STATIC_ROOT = os.path.join(BASE_DIR, 'static/') I do not know what I am doing wrong, on my local computer everything looks ok -
How could we change the app name in Wagtail after creation?
Because of some mistakes in naming the apps during their creation with Wagtail and working on their content for some days, It's important to know how we could change their name after creation with Wagtail. I'm trying to do it with Django's methods for creating and changing the app name. But they didn't work perfectly. -
Django: how can i show user data based on model object
I have a model called Category, and I want to show some icons based on what is created from a Category model, if user created an object from a Category model called Food, I want to show the food icon in the template, for example: {% if category is food %} <a href=""> show Food Icon </a> {% else %} show others category icons using this method below: a user can click an object and get everything that is created from a Product model with a category of food or any object of Category model, but I do not know how to write a query to get an object of Category model and show icon based on that object. how can I do this? def home(request): category = request.GET.get('category') if category == None: products = Product.objects.all() else: products = Product.objects.filter(category__name=category) categories = Category.objects.all() context = { 'products': products, 'categories': categories } return render(request, 'home.html', context) template: <div class="container"> <div class="row justify-content-center"> {% for category in categories %} <div class="col-md-4"> <a href="{% url 'home' %}?category={{category.name}}">{{category.name}}</a> </div> {% endfor %} </div> </div> models: class Category(models.Model): name = models.CharField(max_length=50) def __str__(self): return str(self.name) -
Django. Field for selecting values (ManyToMany) as in the admin panel
How to achieve the display of the field for the form (when it is filled) as in the admin panel (screenshot)? I tried using forms.CheckboxSelectMultiple widget but it doesn't quite fit. It provides the entire list from the request as a whole, this is not very convenient, since my list will be very large. We need a slider and search fields, as it is actually implemented in the admin panel. -
django restfrawwork not working on cpanel [closed]
when i try to save to db on cpanel not working but get method is working the code is def CreateUser(request): serializer = UserSerializer(data=request.data) try: if serializer.is_valid(): serializer.save() return Response(serializer.data) except User.DoesNotExist: return JsonResponse({'status':'404','message':'invalid user data'}) -
How to scrape headlines by a keyword using django
Hi i've written a web scraper with beautiful soup and django. I'm trying to display the headlines that contain the keyword, which has been sent by the user or in other words the user searches for something and we scrape the headlines related to that search and then show them to the user. I've tried it without search and it worked. But when i search for something no headline is scraped. This is what i've written so far. What should i do? Thanks in advance. my views.py from django.shortcuts import render import requests from bs4 import BeautifulSoup news_list = [] def search(request): bbc_r = requests.get("https://www.bbc.com/news") bbc_soup = BeautifulSoup(bbc_r.content, 'lxml') if request.method == 'post': q = request.POST.get('q') query = bbc_soup.find_all('a', {"class": "gs-c-promo-heading gs-o-faux-block-link__overlay-link gel-pica-bold nw-o-link-split__anchor"}) for th in query: if q in th: news_list.append(th.text) return render(request, 'search.html', {'news_list':news_list}) this is my html <!DOCTYPE html> <html> <head> <title>News</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <style> </style> </head> <body> <div class="jumbotron"> <center><h1>BBC News Headlines</h1> </center> </div> <div class="container d-flex align-items-center justify-content-center"> <div class="row"> <div class="col-6"> <h3 class="text-center mb-5"> Lastest News</h3> {% for n in news_list %} <h5 class="text-center"> - <a href="https://www.bbc.com/news"> {{n}} </a></h5> <hr> {% endfor %} <br> </div> </div> </div> this is the … -
How to pass context to the django static template tag
I have an image with the name image1.png. Image name is stored in the context_image like context_image = 'image1.png'. How to pass my context_image to this code {% static "images/image1.png" %}? I try this {% static "images/{{ context_image }}" %} but this code ain't working. -
Django does not download file from query
I have a Django app where I need to allow a user to download a log file generated from a query. I have created a view for the download, and I generate the file - but once the client presses the button (called with ajax), nothing gets downloaded. My View is as follows: def download_rollback(request): serial = request.POST.get('serial') response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="{}.csv"'.format(serial) writer = csv.writer(response) writer.writerow(['timestamp','serial','log']) queryset = ConfigLog.objects.filter(ser_no=serial).filter(log__contains='ROLLBACK') for obj in queryset: writer.writerow([obj.timestamp, obj.ser_no, obj.log]) return response and I have the following urls.py: urlpatterns = [ ... path('beaconing/download_rollback/', views.download_rollback,name='download_rollback'), ... ] I have followed various tutorials to try this - they all pointed to something like the above, but none works. -
Data in form is not showing in database. Only new line is appearing
I am doing project in django. It is voting system. I already designed webpage. But the problem is when I connected voting page to database it is not working properly. When i am voting and submitting the form. It is not displaying in database. Only entry is happening. Means there will be new line add in table but the data we entered in voting page is not showing. How can I solve this? I want to display voter name and the candidate name voter voted for in database. -
No data is sent when submitting the django form
I'm trying to create an Order object via ModelForm, but nothing comes out. Forms.py class OrderCreateForm(forms.ModelForm): user = forms.ModelChoiceField(queryset=get_user_model().objects.all(), widget=forms.HiddenInput()) is_payed = forms.BooleanField(required=False, widget=forms.HiddenInput()) status = forms.IntegerField(widget=forms.HiddenInput()) payed_at = forms.DateTimeField(widget=forms.HiddenInput(), required=False) price = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = m.OrderStorage fields = '__all__' Views class StartOrder(generic.CreateView): template_name = 'clientpart/order_create.html' success_url = reverse_lazy('order_list_tire') form_class = f.OrderCreateForm queryset = m.OrderStorage.objects.all() def get_form(self, form_class=None): if form_class is None: form_class = self.get_form_class() form = form_class(**self.get_form_kwargs()) if form.is_valid(): size = int(str(form.cleaned_data['size'])) period = int(str(form.cleaned_data['period'])) price = size*period form.fields['price'].queryset = int(price) return form def get_form_kwargs(self,): ret = super().get_form_kwargs() print(ret) ret['initial'] = { 'user': self.request.user.pk, 'status': OrderStatus.CREATE, } return ret According to my idea, the value is taken from the field and the price is created, then it is written to the dictionary, but for some reason it is not written to the dictionary. enter image description here How do I record an object price -
Efficient way to gathering data by datetime range for multiple rows stored in another table in Django
I've got two models: class CombinedData(models.Model): datetimestamp = models.DateTimeField(null=True, blank=True) N1_leq = models.FloatField(null=True, blank=True) N2_leq = models.FloatField(null=True, blank=True) class DateTimeFolderTable(models.Model): path = models.CharField(max_length=255,primary_key=True) datetimestamp = models.DateTimeField(null=True, blank=True) device = models.IntegerField(default=0) CombinedData example: datetimestamp N1_leq N2_leq 2023-04-14 12:20:00 52.3 54.2 2023-04-14 12:30:00 51.2 52.7 2023-04-14 12:40:00 45.7 47.3 2023-04-14 12:50:00 43.9 45.3 ... ... ... 2023-04-14 13:20:00 53.1 52.1 DateTimeFolderTable example: Path datetimestamp device file1 2023-04-14 12:00:00 1 file2 2023-04-14 12:05:00 1 file3 2023-04-14 12:52:00 1 file4 2023-04-14 13:20:00 1 file5 2023-04-14 14:10:00 1 file6 2023-04-14 11:45:00 2 file7 2023-04-14 12:13:00 2 file8 2023-04-14 12:45:00 2 file9 2023-04-14 13:28:00 2 file10 2023-04-14 13:41:00 2 CombinedData contains information in evenly-spaced time intervals. DateTimeFolderTable contains path to some files, but its in not-evenly spaced and random intervals. I want to render a table, where for each object of Combined Data ther is a list of all files in DateTime FolderTable that have datetimestamp in some range (ie. from a full hour to next full hour). This is expected table i want to render: datetimestamp N1_leq N2_leq paths_device_1 paths_device_2 2023-04-14 12:20:00 52.3 54.2 file1, file2, file3 file7, file8 2023-04-14 12:30:00 51.2 52.7 file1, file2, file3 file7, file8 2023-04-14 12:40:00 45.7 47.3 file1, file2, file3 … -
How to create a MySQL database pool in Django app and how to use these connections?
I want to setup a connection pool in my Django app which uses a MySQL database. I want to create a connection pool and make sure that instead of creating new connection for every request, I can connect it to the connection pool and after performing some queries, I would like to revoke the connection. How can I do that ? How can I setup a mysql connection pool in Django app ? I want to create a connection pool just to avoid 'Too many connection error' in Django -
How can I optimize this Django query to get faster result?
items = Items.objects.filter(active=True) price_list = [] for item in items: price = Price.objects.filter(item_id = item.id).last() price_list.append(price) Price model can have multiple entry for single item, I have to pick last element. How can we optimize above query to avoid use of query in loop. -
Djagno: How to define __init__ function to django modelformset_factory?
I am trying to create a model formset and also for the field where users have to select a product, i don't want to show all the products in the database, i want to filter the products based on the logged in users. by doing something like this on the ModelForm class CartOrderItemsInvoiceForm(forms.ModelForm): class Meta: ... def __init__(self, *args, **kwargs): super(CartOrderItemsInvoiceForm, self).__init__(*args, **kwargs) self.fields['product_obj'].queryset = Product.objects.filter(user=self.request.user) but is it possible to do this on a modelformset_factory AuthorFormset = modelformset_factory( Author, fields=('name', 'age', 'gender', 'product'), extra=1, widgets={ 'name': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author Name here' }), 'age': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author age' }), 'gender': forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Author Gender' }) } ) How do i def the __init__ on the AuthorFormset = modelformset_factory() this is how my models looks class Products(models.Model): title = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) class Book(models.Model): name = models.CharField(max_length=255) isbn_number = models.CharField(max_length=13) user = models.ForeignKey(User, on_delete=models.CASCADE) class Author(models.Model): name = models.CharField(max_length=255) age = models.CharField(max_length=255) gender = models.CharField(max_length=255) product = models.ForeignKey(Products, on_delete=models.CASCADE) book = models.ForeignKey(Book, related_name='authors', on_delete=models.SET_NULL, null=True) -
How to write complex filter queries on M2M models in Django?
I have an app matching candidates (Candidate) with jobs (Job). For both of these models I have an m2m relationship with a Language. A language can be required for a specific job. class JobLanguage(models.Model): language = models.ForeignKey(Language, on_delete=models.CASCADE) job = models.ForeignKey(Job, related_name='languages', on_delete=models.CASCADE) is_mandatory = models.BooleanField(default=False) And a candidate speaks a language with a certain level of "mastery". class CandidateLanguage(models.Model): language = models.ForeignKey(CandidateComponentLanguage, on_delete=models.CASCADE) candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE, related_name='languages') mastery = models.PositiveSmallIntegerField(blank=True, choices=MasteryLevel.choices, null=True) Now in my matching algorithm I need at some point to filter candidates based on the languages required for a specific job. Let's say I have list of mandatory languages for a job : job_mandatory_languages_ids = [1, 2]. How would you write in the most efficient way a method that only returns candidates who master (meaning mastery=1) at least all the languages in this list ? I would like to avoid having to iterate on each candidate to remove them from the list and just use something like filter(Q()) This obviously does not work but it is an idea of what I want to achieve. def filter_on_languages(candidates, job_mandatory_languages_ids): return candidates.filter(languages__language__contains=job_mandatory_languages_ids, languages__language__mastery=1) Thank you :) -
PostgreSQL table partitioning using Djano
Using PostgreSQL database and django-postgres-extra for creating a table partitioning in Django 4.2 application. The database settings are { "default": { "ENGINE": "psqlextra.backend", "NAME": "example1", "USER": "example1", "PASSWORD": "example1", "HOST": "database", "PORT": "5432", "ATOMIC_REQUESTS": False, "AUTOCOMMIT": True, "CONN_MAX_AGE": 0, "CONN_HEALTH_CHECKS": False, "TIME_ZONE": None, } } PSQLEXTRA_PARTITIONING_MANAGER = 'app.partitioning.manager' and the model to be partitioned class TrackingData(PostgresPartitionedModel): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) dynamic_url_object_id = models.IntegerField(blank=True, null=True) ip_address = models.GenericIPAddressField(blank=False) user_agent = models.TextField(null=True, blank=True) scan_time = models.DateTimeField(blank=True, default=datetime.now) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'Tracking Data' class PartitioningMeta: method = PostgresPartitioningMethod.RANGE key = ['scan_time'] then generated migration using the command python manage.py pgmakemigrations but when running python manage.py migrate, it is giving error django.db.utils.NotSupportedError: unique constraint on the partitioned table must include all partitioning columns DETAIL: UNIQUE constraint on table "tracking_trackingdata" lacks column "scan_time" which is part of the partition key. Also tried the following update in the Meta class class Meta: verbose_name_plural = 'Tracking Data' constraints = [ models.UniqueConstraint( fields=['id', 'scan_time'], name='unique_scan_time_per_partition' ) ] -
django_plotly_dash, plotly dash url navigation not working
I am building dashboard using plotly dash. For the web framework I have used Django framework for authentication and embedding other applications. Integrated the plotly dash with the Django using the django_plotly_dash library. I tried integrating the dash app into django using the django_plotly_dash package. plotly dash navigation: from django_plotly_dash import DjangoDash app = DjangoDash('SimpleExample', external_stylesheets=[dbc.themes.SOLAR, dbc.themes.SPACELAB, dbc.themes.BOOTSTRAP]) profile_menu = dmc.Menu( [ dmc.MenuTarget(dmc.Avatar("BR", color="blue",radius="xl",id="user_profile_dropdown")), dmc.MenuDropdown( [ dmc.MenuItem( "Profile", href="/my-profile", # target="_blank", icon=DashIconify(icon="streamline:interface-user-profile-focus-close-geometric-human-person-profile-focus-user"), ), dmc.MenuItem( "Logout", icon=DashIconify(icon="majesticons:logout-half-circle"), href='/logout', id='logout-button' ), ] ), ], trigger="hover", # position='top-end', style=right_align_style, ) app.layout = html.Div([ profile_menu ]) welcome.html <!DOCTYPE html> <html lang="en"> <head> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> </head> {% comment %} <h1>Dash Home page</h1> {% endcomment %} <body> {% load plotly_dash %} <div class="{% plotly_class name='SimpleExample' %} card" style="height: 100%; width: 100%"> {% plotly_app name='SimpleExample' ratio=0.65 %} </div> </body> </html> SimpleExample is my DjangoDash app name. Django urls: urlpatterns = \[ path('',views.home, name='home-page'), path('login',views.login_user.as_view(), name='login-url'), path('plotly_home',views.dash, name='plotly-home'), path('logout',views.logout_user, name='logout-url'), path('django_plotly_dash', include('django_plotly_dash.urls')) \] plotly_home endpoint will render the welcome.html page which shows the dash app. Output: Problem: By default it renders my dash app inside the html Iframe. Thus, any changes or URL changes won't be reflected outside that Iframe. So the plotly dash navigation links are not … -
How to implement two factor authentication over simplejwt in django?
I have implemented authentication using simple jwt and Now I want to implement 2 factor authentication. I am using react for frontend. 2-fa will be introduced only when there is change in browser/device/ip address. I store this information I have thee field in my user model last_login_location, last_login_device, last_login_browser. To get the token: class CookieTokenObtainPairView(TokenObtainPairView): def finalize_response(self, request, response, *args, **kwargs): if response.data.get('refresh'): cookie_max_age = 3600*24*24 # 14 days response.set_cookie('refresh_token',response.data['refresh'],max_age=cookie_max_age,httponly=True) del response.data['refresh'] return super().finalize_response(request,response,*args,**kwargs) serializer_class = CookieTokenObtainPairSerializer Serializer class: class CookieTokenObtainPairSerializer(TokenObtainPairSerializer): @classmethod def get_token(cls, user): token = super().get_token(user) return token def validate(self, attrs): data = super().validate(attrs) refresh = self.get_token(self.user) data['refresh'] = str(refresh) data['access'] = str(refresh.access_token) data['mail'] = self.user.mail return data I want to check for change in location/device/browser during login and apply 2-fa by sending OTP over mail. I could not find anything online. Is there any way I can implement over this ? -
Find closed Trangular lat long around a give lat long point
I have data set which contains thousands of latitude and longitude points How can I write a program in which I input a random lat long and from the date base it finds and creates a closed triangle with its closed 3 lats long and the input lat long should be inside that created tringle 1 Got input A(lat, long) 2 find the nearest point of A named B(lat, long) 3 find the second nearest point named C(lat, long) 4 Liksewise get the 3rd point named as D(lat, long) 5 create a triangle with B, C, and D points and make sure point A should be inside the triangle area, if point A is outside the area then there is no sense of that triangle as an output show me that three lat long points from the DATABASE -
How do I run a Django project database with phpMyAdmin and MAMP?
I'm new to both Django and MySQL (I am more used to Node and Mongo). I want to write my project's backend with Django, but I need to work with phpMyAdmin. I managed to start a sql server from my backend django test app, but it seems to be non-related to my MAMP-phpMyAdmin settings. I tried to run MAMP and phpMyAdmin and create my db on phpMyAdmin then use my Django app settings to relate to my phpMyAdmin test db but it didn't work so my guess is I didn't understand how to use Django settings correctly. Also I got an error saying that my mySql version should be at least 8. It is on my computer, but phpMyAdmin's version is stuck to 5.7 and I couldn't find a way to update it. Then I created and launched a mysql db from my VSCode shell and migrated Django default apps on it and it works... but it's not on phpMyAdmin >< Do you have a tutorial or could you guide me step by step to do this ? I am using the latest version of Django. -
self.assertEqual(response.status_code, 200) AssertionError: 302 != 200 in django
Here i am creating a Login api and if login is success then redirect to csv_import view I am not write in my unit test as i am new to django here is my urls.py urlpatterns = [ path('', LoginAPIView.as_view(), name='login_api'), path('register/',views.register, name="register"), path('books/details/',login_required(views.csv_import),name="csv_import"), path('logout/',views.logout,name="logout"), ] Here is my views.py class LoginAPIView(View): def get(self, request): return render(request, 'login.html') def post(self, request): email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email=email, password=password) print("USERRR",user) if user is not None: print("USERR") login(request, user) print("CREATED") return redirect('csv_import') else: messages.info(request,'Invalid credentials..') return redirect('login_api') def csv_import(request): print("CSV IMPORT") csv_file = os.path.join('static','books.csv') with open(csv_file,'r') as f: reader = csv.DictReader(f) for row in reader: title = row['title'] author = row['author'] authors = row['authors'] isbn13 = int(row['isbn13']) isbn10 = row['isbn10'] try: price = float(row['price'].replace('$','')) except: price = None publisher = row['publisher'] pubyear = row['pubyear'] subjects = row['subjects'] try: pages = int(row['pages']) except ValueError: pages = None dimensions = row['dimensions'], x, books = BooksDetails.objects.get_or_create(title=title,author=author,authors=authors,isbn13=isbn13, isbn10=isbn10,price=price,pages=pages, publisher=publisher,pubyear=pubyear,subjects=subjects, dimensions=dimensions) books_list = BooksDetails.objects.get_queryset().order_by('-id') flag = request.POST.get('flag_value') if flag == '1': try: rows = int(request.POST.get('row','')) print("ROWS",rows) if rows is not None: books_list = books_list[:rows] else: books_list = books_list except ValueError: books_list = books_list else: books_list = books_list print("HERE") paginator = Paginator(books_list, 30) print("NEAR") … -
MultipleObjectsReturned at /rants/first-rant/ get() returned more than one Rant -- it returned 2
I'm getting the error because I have two first-rant slug's on the database. I expected this to come. I have a solution in mind to add random numbers at the end of the url. Can anyone help me implement this using the RandomCharField of https://django-extensions.readthedocs.io/en/latest/field_extensions.html. Here are my models: class Category(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Category, self).save(*args, **kwargs) return self.slug def get_context_data(self, **kwargs): context = super(self).get_context_data(**kwargs) context['rants'] = Rant.objects.filter('category') return class Rant(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150) categories = models.ManyToManyField( Category, related_name='rants_categories') user = models.ForeignKey(User, default='', null=True, related_name='users_rant', on_delete=models.PROTECT) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateField(auto_now=True) class Meta: verbose_name = "rant" verbose_name_plural = 'rants' def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Rant, self).save(*args, **kwargs) return self.slug def get_absolute_url(self): from django.urls import reverse return reverse('main:detail', kwargs={'slug': self.slug}) Here are my views: class RantListView(ListView): model = Rant template_name = 'rants/list.html' context_object_name = 'rants' class RantDetailView(DetailView): model = Rant template_name = 'rants/detail.html' def rant_category(request, slug): rants = Rant.objects.filter( categories__slug__contains=slug ) context = { "slug": slug, "rants": rants } return render(request, "rants/category_list.html", context) And finally my urls path('', RantListView.as_view(), name='list'), path('<slug:slug>/', RantDetailView.as_view(), name='detail'), path('category/<slug:slug>/', rant_category, name='categories'), My … -
'NoneType' object has no attribute 'id'
Added a form to the DetailView, I'm trying to create an entry through the form, I get an error My views I don’t even know why this problem got out, it seems that I did everything according to the dock class CardDetailView(SuccessMessageMixin, ModelFormMixin, DetailView): model = Card template_name = 'cards/detail.html' success_message = 'Ваше сообщение об ошибке получено. Мы обязательно займемся этим.' form_class = WrongCardsForm def get_success_url(self): return reverse_lazy('detail', kwargs={'pk': self.object.id}) def get_context_data(self, **kwargs): context = super(CardDetailView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): form = form.save(commit=False) form.author = self.request.user form.card = self.get_object() form.save() super(CardDetailView, self).form_valid(form) else: return super(CardDetailView, self).form_valid(form) My forms class WrongCardsForm(ModelForm): class Meta: model = WrongCards fields = ['mistake_in', 'error_text',] # fields = '__all__' My urls urlpatterns = [ path('', views.CardsListView.as_view(), name='index'), path('<int:pk>/', views.CardDetailView.as_view(), name='detail'), ] My models class WrongCards(models.Model): """Карточки с ошибками""" CHOICE = ((None, 'Выберите в чем ошибка'), ('a', 'терминe'), ('b', 'определение'), ('c', 'произношение')) mistake_in = models.CharField('Ошибка в', choices=CHOICE, max_length=3) card = models.ForeignKey('Card', on_delete=models.CASCADE, verbose_name='Ошибка', related_name='wrong_cards') error_text = models.TextField('Подробнее об ошибки') author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='Автор') def __str__(self): return self.mistake_in class Card(models.Model): """Карточки слов""" term = models.CharField('Термин', max_length=100) transcription = models.CharField('Транскрипция', max_length=100) definition = … -
Djanog Filter by field values of the reverse reference model of 1:N relationship
The Branch and Subsidy models have a 1:N relationship, In the Subsidy model, the 'related_name' of the branch field is set to 'subsidy'. I'm trying to filter the Branch query set with the 'price' field value of Subsidy, but I get the following error. Branch.objects.filter(subsidy__price__gt=0) Cannot resolve keyword 'subsidy' into field. Choices are: brand_idx, idx, is_active, name, order, province_idx, sido, sido_id As shown below, individual instances seem to have good access to the related_name called 'subsidy', but I don't know why I couldn't find the field "subsidy" when filtering the query set. Branch.objects.get(idx=1).subsidy.all() my models.py class Branch(models.Model): idx = models.AutoField(primary_key=True) name = models.CharField(max_length=128, null=True, blank=True) province_idx = models.IntegerField(default=0, null=True, blank=True) sido = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name='sigungu') brand_idx = models.IntegerField(default=0, null=True, blank=True) order = models.IntegerField(default=0, null=True, blank=True) is_active = models.IntegerField(default=1, null=True, blank=True) def save(self, *args, **kwargs): if self.province_idx: self.sido_id = self.province_idx else: self.sido_id = 0 super().save(*args, **kwargs) class Meta: managed = False db_table = 'branch' class Subsidy(models.Model): idx = models.AutoField(primary_key=True) car = models.ForeignKey(Car, on_delete=models.CASCADE, blank=True, null=True, db_column='car_idx', related_name='car_subs') lineup = models.ForeignKey(Lineup, on_delete=models.CASCADE, blank=True, null=True, db_column='lineup_idx', related_name='lineup_subs') trim = models.ForeignKey(Trim, on_delete=models.CASCADE, blank=True, null=True, db_column='trim_idx', related_name='trim_subs') branch = models.ForeignKey(Branch, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name='subsidy') price = models.IntegerField(default=0, blank=True, null=True) is_state = models.IntegerField(default=0, …