Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to restrict overlapping datetimes in django model at DB level using CheckConstraint
I have the following fields in my Model: class Event(models.Model): starts = models.DateTimeField() ends = models.DateTimeField() I want to restrict overlapping dates (starts, ends). I have managed to do this in model validation, but now I want this enforced at database level such that an IntegrityError exception is thrown if an insert happens outside the model's save method. My Validation was as follows: ... def clean(self): if self.starts and self.ends: if self.__class__.objects.filter( models.Q(ends__gte=self.starts, starts__lt=self.starts) | models.Q(ends__gte=self.ends, starts__lt=self.ends) | models.Q(starts__gt=self.starts, ends__lt=self.ends) ).exists(): raise ValidationError('Event times overlap with existing record!') This works. Say an event starting 2020 Oct 11 @ 19:00, and ending 2020 Oct 11 @ 20:00, the following values will prompt an overlap: same date, starting @ 18:00, ending @ 21:00 same date, starting @ 19:30, ending @ 19:50 same date, starting @ 19:30, ending @ 20:50 But there are situations where the model's .clean() method will not be invoked, which may result in invalid data to be inserted. My question is, how can I enforce a constraint on the model, which will apply on the database itself, like unique_together does. I have used postgres specific fields like DateRangeField but in this case, their functionality is limited as they can … -
Google authentication using django-rest-auth and allauth
I am trying to create an authentication API for a flutter app that will log users in with a google authentication signup/login form. I followed this tutorial to achieve this. So far so good, except that the tutorial is based on a GitHub sign in rather than Google. I managed to get it working up till step "connecting" step. I am able to get the code from the redirect but when I access http://127.0.0.1:8000/auth/google/ I see it's asking for a two fields (access_token, code). When I try to just post with the information I do have I get the following error: "non_field_errors": [ "View is not defined, pass it as a context variable" ] -
How to user AJAX call to django DeleteView or CreatView or UpdateView?
class RegisterUser(CreateView): template_name = 'new_register.html' form_class = SignUpForm success_url = '/' def form_valid(self,form): user = form.save() password = form.cleaned_data.get('password') user.set_password(password) user.save() return JsonResponse({'url':reverse_lazy('accounts:dashboard')}) This is my CreateView and I want to return the redirection URL when the form submitted. I want to handle this URL in AJAX -
Querying and Filtering related models in DRF
I have Contact model to list the followers of an User object, I try to filter the contacts of a User but I still could not manage get a correct queryset. My Contact model is simple with two ForeignKey: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='rel_from_set', on_delete=models.CASCADE,) user_to = models.ForeignKey(User,related_name='rel_to_set', on_delete=models.CASCADE,) def __str__(self): return '{} follow {}'.format(self.user_from, self.user_to) I have created serializers for User and Contact: ##Contact Serializer class ContactsSerializer(serializers.ModelSerializer): user_from = serializers.StringRelatedField(read_only=True) user_to = serializers.StringRelatedField(read_only=True) class Meta: model = Contact fields = ["user_from", "user_to"] ##UserSerializer class UserInformationSerializer(serializers.ModelSerializer): followers = ContactsSerializer(many=True, read_only=True) class Meta: model = User fields = ['first_name', 'last_name', 'followers'] And try to make a query through views: class FollowerListView(APIView): queryset = Contact.objects.all() serializer_class = ContactsSerializer lookup_field = "username" def get(self, request, format=None, slug=None): kwarg_username = self.kwargs.get("slug") user = User.objects.filter(is_active=1).filter(username=kwarg_username) print(user.username) contacts = Contact.objects.filter(user_to=user.id) serializer = ContactsSerializer(contacts) return Response(serializer.data) Now I get error message: AttributeError at /api/member/ytsejam/followers/ 'QuerySet' object has no attribute 'username' print(user.username) If i try print(user) I can see the user an Object. Can you guide me how to correct? Thanks -
Django wont save form data to postgres database
I have a from that won't save any data with form.save() method. It worked before I migrated my whole db to postgres. I think the problem might be in my models file. I'm really new to postgres. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.postgres.fields import ArrayField # Create your models here. class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) weight = ArrayField( models.FloatField(max_length=20, blank=True, null=True), null=True, ) height = models.FloatField(max_length=20, blank=True, null=True) date = ArrayField( models.DateField(auto_now_add=True), null=True, ) def __str__(self): return self.user.username @receiver(post_save, sender=User) def save_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) views.py from django.shortcuts import render from django.contrib import messages from django.contrib.auth.models import User from django.http import JsonResponse from django.shortcuts import get_object_or_404 from users import models from users.models import Profile from django.core import serializers from .forms import WeightForm import logging import json def home(request): form = WeightForm() if request.is_ajax(): profile = get_object_or_404(Profile, id = request.user.id) form = WeightForm(request.POST, instance=profile) if form.is_valid(): form.save() return JsonResponse({ 'msg': 'Success' }) return render(request, 'Landing/index.html',{'form':form}) -
Django - page doesn't reflect changed contents
So, I am talking about the basic stuff as well....when I make a change in some text it is not getting changed when I refresh, I have to stop the server and again do python manag.py runserver to see the changes -
How to use the created objects from get_or_create method?
Here if the object created I want to use this object in another model. How can I do it ? I suppose created returns the Boolean value so How can I get the created object ? value, created = MyModel.objects.get_or_create(field1=field1, field2=field2) if created: another_model_obj.manytomanyfield.add(created) -
Python, Graphql Mutation and Dango API
I am working on a project that takes signups from a Django form and transfers them to a website, the info is mainly the data ( Name, surname, email...) and some extra-information (tags). One of the scripts give me the following error in the cronjob_logs; Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django_cron/management/commands/runcrons.py", line 71, in run_cron_with_cache_check manager.run(force) File "/usr/local/lib/python2.7/dist-packages/django_cron/init.py", line 215, in run self.msg = self.cron_job.do() File "/home/django/django_project/ogx/cron.py", line 31, in do ep_id = get_ep_id(ep.email) File "/home/django/django_project/ogx/graph_helper.py", line 75, in get_ep_id ''', {"query": email}) File "/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line 11, in execute return self._send(query, variables) File "/usr/local/lib/python2.7/dist-packages/graphqlclient/client.py", line 34, in _send raise e HTTPError: HTTP Error 500: Internal Server Error The script was working normally some time ago, as for the graph_helper.py it is as follows; def get_ep_id(email): client = GraphQLClient( '*this part I took off for confidentiality*') result = client.execute(''' query Myquery($query: String!){ allPeople(q:$query) { data { id full_name } } } ''', {"query": email}) data = json.loads(result) if len(data['data']['allPeople']['data']) > 0: return data['data']['allPeople']['data'][0]['id'] else: return None The cron.py in question is the following; class FetchEPsIDs(CronJobBase): RUN_EVERY_MINS = 30 schedule = Schedule(run_every_mins=RUN_EVERY_MINS) code = 'ogx.FetchEPsIDs' # a unique code def do(self): eps_query = mc_ogx_app.objects.filter(ep_id__isnull=True) for ep in eps_query: ep_id = get_ep_id(ep.email) … -
Cross-app join queries for retrieving linked data
I am working on an app that will store customers and addresses in seperate apps. Some addresses will be customer linked, which I planned on doing by storing the pk for the customer against the address and for primary addresses I planned to link the opposite (address pk to customer field). I am unsure on how to pull the data from both apps into the table I'm populating to "view all". def customers(request): customer_list = customer.objects.all() context = { 'customer_list': customer_list, } return render(request, 'customers.html', context) The goal I am trying to achieve is to turn these 2 pk's into the addresses stored in my address app. I tried to implement foreignkeys with my current structure and was returned an error when creating a foreignkey in my customer model linking to addresses; primary_address = models.ForeignKey('addresses.addresses', on_delete=models.CASCADE) #django.db.utils.OperationalError: no such column: customers_customer.primary_address_id The goal I have set is to replace the primary keys in the below table with the addresses from the address model. I am newer to django and I could be approaching this the wrong way. File structure address.models from django.db import models # Create your models here. class addresses(models.Model): tenant_code = models.CharField(max_length = 6) customer_id = models.IntegerField(blank = … -
Submit python script through PHP/AJAX
I made a python script who can convert .MOV to .MP4 the thing is I want to execute the script from my website made on PHP. So the example is I'm browsing a video on the web page then I click on submit and I'm waiting for the python script executing. It's working already but now I need to adapt it to my actual website and the session cookie (PHP). But I don't know how to do that.. I saw on some forum that they use Flask or Django but my website is already built and I don't want to rebuilt it. Thank you -
django, typeerror: missing 1 required positional argument
models.py: class DoctorList(models.Model): doctorname = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HospitalList, related_name="h_code", on_delete=models.CASCADE) def doctor_code_create(DoctorList): last_doctor_code = DoctorList.objects.all().order_by('d_code').last() testhospital = DoctorList.objects.filter().values('h_code') if not last_doctor_code: return 'd' + '001' d_code = last_doctor_code.d_code doctor_int = int(d_code[3:7]) new_doctor_int = doctor_int + 1 new_d_code = 'd' + str(testhospital) + str(new_doctor_int).zfill(3) return new_d_code d_code = models.CharField(primary_key=True, max_length = 200, default = doctor_code_create, editable=False) error code: Got a `TypeError` when calling `DoctorList.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `DoctorList.objects.create()`. You may need to make the field read-only, or override the DoctorListSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\rest_framework\serializers.py", line 948, in create instance = ModelClass._default_manager.create(**validated_data) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\query.py", line 445, in create obj = self.model(**kwargs) File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\base.py", line 475, in __init__ val = field.get_default() File "C:\Users\user\Desktop\venv\tutorial\lib\site-packages\django\db\models\fields\__init__.py", line 831, in get_default return self._get_default() TypeError: doctor_code_create() missing 1 required positional argument: 'DoctorList' I want to use h_code that exists in class DoctorList (models.Model) by putting it in doctor_code_create. I think it's right to use it like this, but I don't know what went wrong. Do I … -
ValueError: Field 'length' expected a number but got ''
models from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now from django.contrib.auth.models import User # Create your models here. class Allmusic(models.Model): sno=models.AutoField(primary_key=True) name=models.CharField(max_length=100,default="") author=models.CharField(max_length=100,default="") description=models.TextField(default="") movie=models.CharField(max_length=100,default="") category=models.CharField(max_length=100,default="") subcategory=models.CharField(max_length=100,default="") image=models.ImageField(upload_to='images', default="") musicfile=models.FileField(upload_to='music_file', default="") def __str__(self): return self.name class Watchlater(models.Model): watch_id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) video_id=models.CharField(max_length=100000,default="") class BlogComment(models.Model): sno=models.AutoField(primary_key=True) comment=models.TextField() user=models.ForeignKey(User,on_delete=models.CASCADE) post=models.ForeignKey(Allmusic,on_delete=models.CASCADE) timestamp=models.DateTimeField(default=now) class History(models.Model): history_id=models.AutoField(primary_key=True) user=models.ForeignKey(User,on_delete=models.CASCADE) music_id=models.CharField(max_length=100000,default="") views.py from django.shortcuts import render,HttpResponse,redirect from .models import Allmusic,Watchlater,BlogComment,History from math import ceil from django.contrib.auth.models import User from django.contrib.auth import login,authenticate,logout from django.contrib import messages from django.db.models import Case,When # Create your views here. def home(request): return render(request,'home.html') def index(request): allProds = [] catprods = Allmusic.objects.values('category', 'sno') cats = {item['category'] for item in catprods} for cat in cats: prod = Allmusic.objects.filter(category=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds':allProds} return render(request,'index.html',params) def indexmovie(request): allProds = [] catprods = Allmusic.objects.values('movie', 'sno') cats = {item['movie'] for item in catprods} for cat in cats: prod = Allmusic.objects.filter(movie=cat) n = len(prod) nSlides = n // 4 + ceil((n / 4) - (n // 4)) allProds.append([prod, range(1, nSlides), nSlides]) params = {'allProds':allProds} return render(request,'indexmovie.html',params) def about(request): return render(request,'about.html') def contact(request): return render(request,'contact.html') #Authenciation APIs … -
ImportError: cannot import name 'InvalidTokenError' from 'jwt'
ImportError: cannot import name 'InvalidTokenError' from 'jwt' -
How to generate presigned S3 urls using django storages?
I have a Django form which saves a file to s3 through the django-storages library and works fine. How can I generate and return a pre-signed url so the user can access the file temporarily after it is uploaded ? I have spent hours going through the Django-storages documentation however it is not very clear how to do this .. form.py class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='max. 42 megabytes' ) name = models.CharField(max_length=20) uploaded_at = models.DateTimeField(auto_now_add=True) views.py def upload_file(request): if request.method == 'POST: form = DocumentForm(request.POST) if form.is_valid(): form.save() url = #generate pre-signed url of uploaded file here return render(request, 'upload_response.html, url) -
Wagtail modeltranslation language switcher doesn't work on /search page
I have added search url to i18n_patterns, but the language switcher doesn't work on that page. urls.py: urlpatterns += i18n_patterns( path("search/", search_views.search, name="search"), path("", include(wagtail_urls)), ) language switcher: {% get_available_languages_wmt as languages %} <div class="nav-item dropdown float-right"> <p class="nav-link dropdown-toggle m-auto" data-toggle="dropdown" role="button" aria-expanded="false"> {{ request.LANGUAGE_CODE|upper }}</p> <div class="dropdown-menu w-25"> {% for language in languages %} {% if language != request.LANGUAGE_CODE %} <a class="dropdown-item" href="{% change_lang language page %}">{{ language|upper }}</a> {% endif %} {% endfor %} </div> </div> Furthermore, when i add search url above root one the search page raises 404 page. How can i make the language switcher work on the search page? -
The view account.views.signup didn't return an HttpResponse object. It returned None instead
Trying to register user in Django. it keep giving me HttpResponse error signup.html templates location is : templates/registration/signup.html Here's what i tried: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class SignUpForm(UserCreationForm): username = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'email', 'password1', 'password2', ) views.py from django.contrib.auth import login, authenticate from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.decorators import login_required from .forms import SignUpForm @login_required def home(request): return render(request, 'registration/home.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email= email, password= raw_password) login(request, user) return redirect('registration/home') else: form = SignUpForm() return render(request, 'registration/signup.html', {'form': form}) I did tried replacing redirect with HttpResponseRedirect but it did't work Account urls.py from django.contrib.auth import views as auth_views from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ path("login/", auth_views.LoginView.as_view(template_name = "registration/login.html"), name='login'), path("logout/", auth_views.LogoutView.as_view(), name='logout'), path('home/', views.home, name='home'), url('signup/', views.signup, name='signup'), ] Error ValueError at /accounts/signup/ The view account.views.signup didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 3.0.3 Exception Type: ValueError Exception Value: The view account.views.signup didn't return an … -
How do I use the manyToMany relationship in a graphene scheme?
I'm trying to do a graphql query in django. I have a problem with the manuToManu relationship. Can I ask for help? I don't know where I go wrong. Part written in Python models.py class Topping(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class Pizza(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) schema.py class Query(graphene.ObjectType): pizza = graphene.List(PizzaType) topping = graphene.List(ToppingType) @staticmethod def resolve_pizza(parent, info): return Pizza.objects.all() @staticmethod def resolve_topping(parent, info): return Topping.objects.all() types.py class ToppingType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) name = graphene.NonNull(graphene.String) class PizzaType(graphene.ObjectType): id = graphene.NonNull(graphene.Int) name = graphene.NonNull(graphene.String) toppings = graphene.List(ToppingType) Part written in Graphql query graphql query { pizza{ name toppings { name } } } response graphql { "errors": [ { "message": "User Error: expected iterable, but did not find one for field PizzaType.toppings." } ], "data": { "pizza": [ { "name": "mafia", "toppings": null } ] } } -
How to manually test task retry in Celery?
I'm trying to implement task retry in my Django app using Celery and would like to test if the task will be properly restarted when an unexpected exception will be raised. To do this I manually rise an Exception in the task but it's doesn't work as expected. It throws a RecursionError saying that maximum recursion depth is exceeded while calling a Python object. So how can I know if my task will be retried in case an Exception is raised in production mode? This is how my task looks like: @celery.app.task() def download(client): return client.download('www.something.com/api') The same task with Celery retry options: @celery.app.task(bind=True, autoretry_for=(Exception,), exponential_backoff=2, retry_kwargs={'max_retries': 5}, retry_jitter=True) def download(self, client): print('test') try: raise Exception return client.download('www.something.com/api') except Exception as exc: print('exception !') download.(client).retry(exc=exc) And code execution output shows that retries are not controled by Celery: test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test exception! test … -
filter a query based on a value only if the value is not empty in django
I need to filter a query based on a variable but only if this var is not empty ... here is what I have tried : rows = Attendance.objects.filter(type= the_type if the_type != "" else '*') the problem is in the part else '*' I have tried to remove else, but it won't work as it is required to use an else after if in the ternary operator, also tried else pass but it gives me an error. -
django import with django-import-export
could anybody tell me what I did wrongly here as I am unable to see all the fields while importing data from db class UserResource(ModelResource): class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'id') import_id_fields = ('id',) class UserAdmin(ImportMixin, admin.ModelAdmin): resource_class = UserResource As show below ss I can see only username field shows up and my csv file is shown below username, email, first_name, Last_name, id abc, abc@gmail.com, abd, de -
The 'django_comments' is in INSTALLED_APPS settings but the 'comments' is not recognizable template tag
I want to use django-comments-xtd for threaded comments in my app. This is a framework which extends original django-contrib-comments. So like the tutorial says, I included both django_comments_xtd and django_comments to installed apps. But when I load the tag comments it says 'comments' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache comments_xtd crispy_forms_field crispy_forms_filters crispy_forms_tags crispy_forms_utils django_simple_bulma i18n l10n log md2 posts_extras rest_framework static tz I am so confused. The traceback itself shows I have included django_comments to INSTALLED_APPS setting INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'six', 'social_django', 'django_simple_bulma', 'django_comments_xtd', 'django_comments', 'rest_framework', 'django_markdown2', 'posts.apps.PostsConfig', 'users.apps.UsersConfig', 'core.apps.CoreConfig', ] No idea why is this happening. How comments_xtd is registered tag library, not comments? -
How to check if there is more than one environment variable set for running Python scripts in PATH
I am learning Django and in Comand Prompt I have already installed Django, then when I check django-admin --version it says 'django-admin' is not recognized as an internal or external command, operable program or batch file. Because of this I tried to install Django 3 times again but it still output the same. What is the cause of this problem? To test is my Django is working or not I have also tried to import django in my python interpreter. I have 2 python versions in my computer the first one is 3.8 and the second one is 3.8.6 ,which the CMD tells me to download. When I tried to import django in python3.8 it output No module named 'django', when I tried to import django in python3.8.6 it worked !! I hope my python 3.8 work because my Pycharm is using that. What is the cause of the problem ?? I have been suffering from this problem for 1 week😥😥, if you know the problem, solution or suggestions please write it below. 😄😄😄 -
PermissionError: [Errno 13] Permission denied when doing migrations in docker
Here is my dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk update RUN \ apk add --no-cache postgresql-libs && \ apk add --no-cache --virtual .build-deps gcc libc-dev make git libffi-dev openssl-dev python3-dev libxml2-dev libxslt-dev gcc musl-dev && \ apk add postgresql && \ apk add postgresql-dev && \ apk add jpeg-dev zlib-dev libjpeg &&\ python3 -m pip install -r requirements.txt && \ apk del .build-deps RUN mkdir /backend COPY ./backend /backend WORKDIR /backend COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/ RUN adduser -D user RUN chown -R user:user ./ RUN chown -R user:user /vol RUN chmod -R 666 /vol/web USER user CMD ["entry_point.sh"] and my docker compose: version: "3.7" services: backend: build: context: . ports: - "8000:8000" volumes: - ./backend/backend:/backend command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 depends_on: - db links: - db:db networks: - djangonetwork db: image: postgres restart: always expose: - "5432" environment: POSTGRES_USER: xxxx POSTGRES_PASSWORD: demodemo POSTGRES_DB: xxxx networks: - djangonetwork networks: djangonetwork: driver: bridge When i run the docker-compose run backend python manage.py makemigrations --noinput command i get the following error: Migrations for 'auth': /usr/local/lib/python3.8/site-packages/django/contrib/auth/migrations/0012_userloginactivity.py - Create model UserLoginActivity Traceback (most recent call … -
Django Admin, ManyToMany field getting Unknown field(s) (linked_sites) specified for Model error
I have two Django Models connected through ManyToMany relation. class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) account = models.ForeignKey(Account, related_name=RelatedNames.USERS, on_delete=models.CASCADE, null=True, blank=True) accessed_sites = models.ManyToManyField(Site, related_name=RelatedNames.USERS) class Site(models.Model): name = models.CharField(max_length=255) location = models.OneToOneField(GeoLocation, on_delete=models.PROTECT, related_name=RelatedNames.ADDRESS, blank=True, null=True) score = models.IntegerField(default=0) avg_spent_time = models.DurationField(default=timedelta(days=0)) _type = models.IntegerField(choices=SiteTypeChoices.CHOICES, max_length=20) primary_email = models.EmailField(null=True, blank=True) def __str__(self): return self.name def get_site_address(self): return str(self.location) I'm trying to display and modify the relation through the admin: class SitesAdmin(ModelAdmin): fields = [Fields.NAME, Fields.PRIMARY_EMAIL, Fields.TYPE, Fields.SCORE, Fields.LOCATION] list_display = fields class UsersAdmin(ModelAdmin): fields = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] list_display = [Fields.EMAIL, 'full_name', Fields.ACCOUNTS, 'linked_sites'] readonly_fields = ('full_name',) def full_name(self, obj): return obj.get_full_name() def linked_sites(self, obj): return "\n".join([site.name for site in obj.accessed_sites.all()]) the list display works but when opening a User object I'm getting the following error: Unknown field(s) (linked_sites) specified for CustomUser. Check fields/fieldsets/exclude attributes of class UsersAdmin. -
Filter product Django "LATEST", "BEST SALE", "TOP RATED","ON SALE"
I need your help. I have 4 categories "LATEST", "BEST SALE", "TOP RATED" and "ON SALE". In the "LATEST", I want to show the 20 most recently added products. In the "BEST SALE", need to show products that have the best-selling status. In the "TOP RATED", need to show 20 products with a high rating. In the "ON SALE", need to show 20 products that have the sale status. How do I make a filter for these categories? Thanks a lot. Some examples Django, please. class Product(models.Model): StatusProduct=( (_(''), _('')), (_('best sale'), _('BEST SALE')), (_('on sale'), _('ON SALE')), ) name = models.CharField(_('Name'), max_length=150, blank=True, null=True, default=None, help_text=_('The maximum number of characters - 150')) price = models.DecimalField(_('Price'), max_digits=10, decimal_places=1, default=0) discount = models.IntegerField(_('Discount'), default=0) status = models.CharField(_('Status'), max_length=20, choices=StatusProduct, default='') parentcategory = models.ForeignKey(ParentCategory, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) category = models.ForeignKey(MenuBarProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) subcategory = models.ForeignKey(CategoryProduct, verbose_name=_('Category'), on_delete=models.CASCADE, blank=True, null=True, default=None) short_description = CKEditor5Field(_('Short description'), config_name='extends', blank=True, null=True, default=None) description = CKEditor5Field(_('Description'),config_name='extends', blank=True, null=True, default=None) is_active = models.BooleanField(_('Active'), default=True, help_text=_('Activated, allow to publish')) created = models.DateTimeField(_('Created'), auto_now_add=True, auto_now=False) updated = models.DateTimeField(_('Updated'), auto_now_add=False, auto_now=True) created_by = models.ForeignKey(User, verbose_name=_('Created by'), on_delete=models.CASCADE, editable=False, null=True, blank=True) def __str__(self): return "%s" % (self.name) …