Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve "TypeError: Field.__init__() got an unexpected keyword argument 'choices'"?
I recently decided to update my forms.py file of my Django project to make one of the fields into a drop down menu rather than an empty text box. In my forms.py file, I changed the class for customers from; class CustomerSignUpForm(UserCreationForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user to the following class CustomerSignUpForm(UserCreationForm): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) email_address = forms.EmailField(required=True) membership_tier = forms.CharField(choices = member_tiers, default = 'Basic', required=True) class Meta(UserCreationForm.Meta): model = User @transaction.atomic def data_save(self): user = super().save(commit=False) user.first_name = self.cleaned_data.get('first_name') user.last_name = self.cleaned_data.get('last_name') user.is_customer = True user.save() customer = Customer.objects.create(user=user) customer.email_address = self.cleaned_data.get('email_address') customer.membership_tier = self.cleaned_data.get('membership_tier') customer.save() return user And here is my customer class in my models.py as well if that will help, class Customer(models.Model): member_tiers = ( 'Basic', 'Intermediate', 'Beast' ) username = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) email_address = models.EmailField(max_length=30) membership_tier = models.CharField(max_length = 30, choices = member_tiers, default = 'Basic') What my question boils down to is: … -
How to POST requests in Django with JS?
I'm trying to add products in my basket without refreshing the page and i have urls: app_name = 'basket' urlpatterns = [ path('', views.BasketView.as_view(), name='summary'), path('/add', views.BasketView.post, name='basket_add'), ] views: class BasketView(generic.list.ListView): template_name = 'basket/basket.html' model = Category def post(self, request, *args, **kwargs): data = request.POST print(data) return 'something' html (+JS): ... <button onclick="basket_add(this)" id="{{ item.id }}"></button> ... <script> function send_productId(id){ var request = new XMLHttpRequest(); request.open('POST', '{% url 'basket:basket_add' %}', true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); const data = { id: id, csrfmiddlewaretoken:'{{ csrf_token }}', action: "POST", }; request.send(data); }; function basket_add(obj){ send_productId(obj.id); }; </script> after pressing the button i get this error Forbidden (CSRF token missing.): /basket/add So how can i at least print data correctly or do i need to do it the other way? -
Does `django-import-export` delete old saved model objects when updating them?
This is just a quick question to better understand how django-import-export works. Say I have a few objects of some model already saved in my database. If I try to import from a file containing the data for an object that is already in the database (so, an object with the pk in the import file already exists in the database), the change list shows that this object is being updated. My question is this: does the update process involve deleting the old instance of that object (the one that is saved in the database) and then adding the one that we are importing as if it was a new instance? or is it actually updated using, for example, the instance.update(attr=new_val) method? -
Login not redirecting to the LOGIN_REDIRECT_URL
I created a simple login form with username and password. My login is not redirecting to the LOGIN_REDIRECT_URL link which should redirect to the home page. I tried several credentials from the admin side(which I got from signing up) Urls.py: from django.contrib import admin from django.urls import path from jobs import views as jobs_views #from the job application it is gonna import views from users import views as users_views from django.contrib.auth import views as auth_views urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name = 'login.html'), name= 'login'),] Login.html(only added relevant code): <section class="site-section"> <div class="container"> <div class="row"> {% csrf_token %} {{ form.non_field_errors }} <!-- DEBUG --> {% for field in form %} {% if field.errors %}{{ field.html_name }}: {{ field.errors }}{% endif %} {% endfor %} <div class="col-lg-6"> <h2 class="mb-4">Log In To JobBoard</h2> <form class="p-4 border rounded", submit= 'POST'> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="fname">Username</label> {{ form.username }} </div> </div> <div class="row form-group mb-4"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="fname">Password</label> {{ form.password }} </div> </div> <div class="row form-group"> <div class="col-md-12"> <input type="submit" value="Log In" class="btn px-4 btn-primary text-white"> </div> </div> </form> </div> </div> </div> </section> settins.py(only added relevant code): LOGIN_REDIRECT_URL = 'home_page' LOGIN_URL = 'login' I tried putting … -
Django raw queries and Postgres declare variable
I have a file with many raw sql queries, that uses text substitution i.e select * from table1 where date_col between '%%from_date%%' and '%%to_date%%' these %%date_from%% and %%date_to%% are then replaced by values using python string replace function. this works fine and the queries work. however it is not idle as it can be open to sql injection. (and no I can't use models or anything beside the raw sql) to make matters worse I can't use %s and parametrise the queries because the variables change order and %s works by order (as far as I can tell) I thought about using declare in order to have my variables at the start of the select block i.e sql - declare from_date date:= %s declare to_date date:= %s select * from table1 where date_col between to_date and from_date python - with with connection.cursor() as cursor: cursor.execute(query, [from_date, to_date']) but this gives out django.db.utils.ProgrammingError: syntax error at or near "date" LINE 1: DECLARE from_date date := '2022-01-01'::date DECLARE to_date... ^ I don't know what I'm doing wrong and I'll be glad for some help. as far as I can see I got the syntax right, maybe django raw queries only support select? … -
How to create a search field in django MultipleChoiceField?
I have a list of skills and I added them to django MultipleChoiceField. But there are a lot of skills and it's hard to find what you want. So I decided to add a search field to this MultipleChoiceField. Is that possible and how can I do it? -
json.dumps returns the objects as a string instead of a JSON object
In the views.py: data1 = Inventory.objects.values_list('product_number','amount') data = json.dumps(list(data1), cls=DjangoJSONEncoder). I pass data as context to the html file. In the HTML file, Using JS I access the JSON object with this code: {{ data|json_script:"hello-data" }} <script type="text/javascript"> var data = JSON.parse(document.getElementById('hello-data').textContent); document.getElementById('id_line_one').onchange = function(event){ console.log(typeof data) alert(data); document.getElementById('id_line_one_unit_price').value = data[this.value]; }; </script> I expect the var data to be a dictionary but it seems to be a String. Object.fromEntries is not working and I get the error Uncaught TypeError: Iterator value [ is not an entry object at Function.fromEntries (<anonymous>). JSON.parse is removing the double quotation and I get [[1, 56000], [2, 55000]] but I am not able to access it as a dictionary. Whenever I use the index to access it, It returns the single characters as output instead of thinking of it as a dict object. How can I convert it into a dictionary? Thanks -
Having issue in loading files from static folder
I am new on django and having issue while following a tutorial on YouTube I stuck in it and try several things but didn't get rid of it plz help me so my static page which i changed into dynamic will load with changes that i made.Everything is working fine except when i try to run it by using {%static%} and i also told the system about static stuff through {%load static%} but it not showing pictures which i try to show through static folder. List item Not showing pictures on web page. Having issue to upload it from static folder. -
Django Rest API filter keeper query (foreignkey)
Django Rest API has user input in foreignkey format. The User input returns all users. But I only want to fetch users that are in the unit of the requesting user. current keeper select input: queryset = User.objects.all() my wish keeper input: queryset = User.objects.filter(unit=request.user.unit) serializers.py: class InventorySerializer(serializers.ModelSerializer): class Meta: fields = ('keeper','status','name') views.py: class InventoryGet(generics..RetrieveUpdateAPIView): serializer_class = InventorySerializer permission_classes = [permissions.IsAuthenticated] lookup_field = 'id' queryset = Inventory.objects.all() models.py keeper = models.ForeignKey(User,models.SET_NULL,null=true,blank=true) status = models.CharField(max_length=500) name = models.CharField(max_length=500) -
How to destructure message in django formatters?
I am trying to customize the logger in django, and here is my code: import logging.config LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "fmt1": { "format": "{asctime}\t{message}", "datefmt": "%Y-%m-%d", "style": "{", }, }, "handlers": { "console1": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "fmt1", }, }, "root": { "handlers": ["console1"], "level": "DEBUG", "propagate": True, }, "loggers": { "": { "handlers": ["console1"], "level": "DEBUG", "propagate": True, }, }, } logging.config.dictConfig(LOGGING) In so doing, I got the following message in my terminal: 2022-07-10 "GET /api/list/ HTTP/1.1" 200 13 However, when I try to use the string function .format() to format the message in formatters, I end up with the following error: ... File "/Users/retr0327/Desktop/Py/django-restAPI/env/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 187, in log_message Message: '"%s" %s %s' Arguments: ('GET /api/list/ HTTP/1.1', '200', '13') Ideally, I want my terminal to have this: 2022-07-10 GET /api/list/ 200 13 How can I achieve this or is there a better way to customize the logger? Thanks for any help!! -
what is the best way to store photos?
I'm using Django as backend and Flutter as front end. I'm developing my first app/website witch is an album app, just like instagram. As you can understand, there is a lot of photos to store, for each user. today I store photos in an sub folder in the backend, witch is not the best thing to do. what is then best place to store photos ? I learn in internet that I can use Base64 or CDN but I really dont know what to choose and why ? Thank you -
CSRF Protection for django session-based auth for Hasura + auth webhook
I have a react app for the frontend, a hasura instance for the graphql engine connected to my database and a django app for their easy session-based authentication, ORM and migrations. Before I introduced the Hasura instance my authentication worked like a charm. I would get the CSRF Token and HTTP-Only cookie from django, in my frontend and when sending POST requests would send the token in the headers along with the cookie that is sent automatically. For Hasura I have to use a webhook to authenticate the graphql requests and I wanted to do this with my already in-place django sessions. Using the apollo client i setup a middleware to get csrf token and cookie from my django app and send it along with every request, where Hasura would then (hopefully) forward them to the django webhook. But now my problem is: Django only does CSRF checks for POST requests, and if I configure Hasura to send a POST request to my webhook it puts all the headers from my client request in the body as JSON, and django CSRF middleware doesn't pass the checks. Is there a way to force django to do CSRF checks for a specific … -
I removed the video download button but it only works for the first post
I have no idea where the problem comes from, a similar problem happens with the like button. I've left my code below, if you want I can post it in more detail {% for post_item in post_items %} doesn't seem to work as it should, but whyyyy? my.html {% for post_item in post_items %} <ul style="padding-inline-start: 10px;" id="dataList_post"> <li class="content hidden"> <div> <div class="post" style="min-height: 174px; border: 1px solid #f0f0f0; border-width: 2px; border-radius: 20px; max-width: 600px; height: auto; margin-right: 100px;"> <div class="posticon"> {% if post_item.user.profile.avatar %} <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"><img src="{{ post_item.user.profile.avatar.url }}" style="border-radius: 100%; width: 48px; height: 48px;" alt=""></a> {% else %} <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"><img src="{% static 'img/default.png' %}" style="border-radius: 100%; width: 48px; height: 48px;" alt=""></a> {% endif %} </div> <div class="postname"> <a style="text-decoration: none; color: black;" href="{% url 'users' post_item.user %}"> <h5 class="postname_location" style="font-family: cursive;"><b>{{ post_item.user.username }}</b></h5> </a> </div> <div class="postcomment"> <a style="text-decoration: none; color:black;" href="{{ post_item.get_absolute_url }}"> <span>{{ post_item.caption }}</span> <br> </a> {% for tag in post_item.tags.all %}<a href="{{ tag.get_absolute_url }}"><b>#{{ tag }}</b></a>{% endfor %} <small class="font-italic text-muted" style="float: right;">{{ post_item.posted | naturaltime }}</small> </div> {% if post_item.content.first.file.name|slice:"-3:" == 'jpg' or post_item.content.first.file.name|slice:"-3:" == 'png' … -
How can I reuse a Django view with a post method for my API
I am currently trying to create an API with DRF on my backend for a mobile application. I would like to know if it is possible to reuse some POST methods already implemented by passing them a request as parameter. Thank you, Here is the view in question: The method I am interested in is the POST method. class ShopModuleCategoryCreateView(ShopModuleMixin, BorgiaView): """ """ permission_required_self = 'modules.change_config_selfsalemodule' permission_required_operator = 'modules.change_config_operatorsalemodule' menu_type = 'shops' template_name = 'modules/shop_module_category_create.html' def __init__(self): #logger.error(' __init__') super().__init__() self.shop = None self.module_class = None self.form_class = None def has_permission(self): has_perms = super().has_permission() if not has_perms: return False else: self.form_class = formset_factory(wraps(ModuleCategoryCreateForm)( partial(ModuleCategoryCreateForm, shop=self.shop)), extra=1) return True def get(self, request, *args, **kwargs): """ permet d'afficher la page de vente """ context = self.get_context_data(**kwargs) context['cat_form'] = self.form_class() context['cat_name_form'] = ModuleCategoryCreateNameForm( initial={'order': self.module.categories.all().count()}) return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): """ Permet de publier la creation d'une nouvelle categorie cat_name_form => renvoie une objet Form avec le nom et l'ordre entré self.module => Module de vente en libre service du magasin Pi """ cat_name_form = ModuleCategoryCreateNameForm(request.POST) f = open("myfile.txt", "a") f.write(str(request)) if cat_name_form.is_valid(): category = Category.objects.create( name=cat_name_form.cleaned_data['name'], order=cat_name_form.cleaned_data['order'], module=self.module, shop_id=self.shop.pk, category_image=cat_name_form.cleaned_data['category_image'], ) logger.error(self.shop.id) cat_form = self.form_class(request.POST) for product_form in … -
run telegram bot inside a docker container with django app
I have a Django application and using "python manage.py name_bot_job" i start the bot, but when i add this task to the docker-compose file and make build, my bot just refuses to start, how can i do it with best practices? entrypoint: ["/bin/sh","-c"] command: - | python manage.py collectstatic --no-input --clear python manage.py migrate --noinput python manage.py createsuperuserwithpassword --username $${DJANGO_SUPERUSER_USERNAME} --password $${DJANGO_SUPERUSER_PASSWORD} --email $${DJANGO_SUPERUSER_EMAIL} --preserve gunicorn job_filter_app.wsgi:application --bind 0.0.0.0:8000 python manage.py poolbot -
How to automatically update model field if there are changes to the previous field?
I am trying to find a way to update the latest field in a model if there are changes in the earlier field. for example: say I have a Cash Balance model If I change the sale inv 134 debits to 50. how do I make this change reflect on the other cashbalance coming after it automatically -
how to pass data from a model to the url in django?
I have a customized user model like this: class Utilisateur(models.Model): username = models.CharField(max_length=50) email = models.CharField(max_length=50) password = models.CharField(max_length=50) phone = models.CharField(max_length=80) And i have my view declared this way: def profile(request): return render(request, 'profile.html') So i want my url to appear with username in it, something like this http://127.0.0.1:8000/profile/username1/ How can i pass the username to the url? -
Django-ckeditor: editor-element-conflict
Django-ckeditor in for loop shows correctly only for the first iteration. For the remaining iterations, the default template form appears as shown below. I see element conflict error in the documentation but it doesn't say anything how to solve. ckeditor.js:21 [CKEDITOR] Error code: editor-element-conflict. Thank you in advance! Here is my template code <div class="d-none" id="comment-{{answer.id}}" > {% for comment in answer.comment_set.all %} <div class="card mb-2" > <div class="card-body"> <p>{{comment.comment|safe}}</p> <p> <a href="#">{{comment.user.username}}</a> </p> </div> </div> {% endfor %} </div> <div class="d-none" id="commentForm-{{answer.id}}"> {% if user.is_authenticated %} <div class="commentform"> <form method="post"> <div class="form-group"> {% csrf_token %} {{ commentForm.media }} {{commentForm|crispy}} <input type="hidden" name="answerid" value="{{ answer.id }}"> <input type="submit" name="submit" value="Submit" > </div> </form> </div> {% endif %} -
Celery: Task registered but not fired from django
init.py from .celery import app as celery_app __all__ = ['celery_app'] celery.py from __future__ import absolute_import import os from celery import Celery from celery.schedules import crontab from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tax.settings') app = Celery('tax') app.config_from_object('django.conf:settings') app.autodiscover_tasks() settings.py BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json', 'json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kathmandu' CELERY_IMPORTS = ('tax.tasks',) CELERY_ENABLE_UTC = False Version Python 3.8.10 flower==0.9.7 celery==4.3.0 Pip freeze aioredis==1.3.1 amqp==2.6.1 apns2==0.7.2 arabic-reshaper==2.1.3 asgiref==3.3.1 asn1crypto==1.5.1 async-timeout==3.0.1 attrs==20.3.0 autobahn==21.3.1 Automat==20.2.0 Babel==2.2.0 backcall==0.2.0 backports.zoneinfo==0.2.1 billiard==3.6.4.0 celery==4.3.0 certifi==2020.12.5 cffi==1.14.5 channels==3.0.3 channels-redis==3.2.0 chardet==4.0.0 click==8.1.3 click-didyoumean==0.3.0 click-plugins==1.1.1 click-repl==0.2.0 constantly==15.1.0 coverage==6.2 cryptography==3.4.6 cssselect2==0.6.0 daphne==3.0.1 decorator==4.4.2 defusedxml==0.7.1 diff-match-patch==20200713 Django==3.1.7 django-allauth==0.44.0 django-anymail==8.6 django-cachalot==2.3.3 django-cors-headers==3.7.0 django-debug-toolbar==3.2 django-extensions==3.1.1 django-filter==2.4.0 django-grappelli==2.14.3 django-import-export==2.5.0 django-js-asset==1.2.2 django-mptt==0.12.0 django-nested-admin==3.3.3 django-phonenumber-field==5.0.0 django-push-notifications==2.0.0 django-rest-auth==0.9.5 django-rest-framework==0.1.0 django-seed==0.3.1 django-summernote==0.8.11.6 django-webpush==0.3.3 djangorestframework==3.12.2 drf-spectacular==0.22.1 et-xmlfile==1.0.1 factory-boy==3.2.1 Faker==9.9.0 flower==0.9.7 future==0.18.2 gunicorn==20.0.4 h2==2.6.2 hiredis==1.1.0 hpack==3.0.0 html5lib==1.1 http-ece==1.1.0 humanize==4.2.3 hyper==0.7.0 hyperframe==3.2.0 hyperlink==21.0.0 idna==2.10 importlib-resources==5.7.1 incremental==21.3.0 inflection==0.5.1 iniconfig==1.1.1 ipdb==0.13.5 ipython==7.21.0 ipython-genutils==0.2.0 jedi==0.18.0 jsonschema==4.5.1 kombu==4.6.11 lxml==4.8.0 Markdown==3.3.4 MarkupPy==1.14 msgpack==1.0.2 numpy==1.21.4 oauthlib==3.1.0 odfpy==1.4.1 opencv-python==4.5.4.60 openpyxl==3.0.7 oscrypto==1.3.0 packaging==21.3 parso==0.8.1 pdfrw==0.4 pexpect==4.8.0 phonenumbers==8.12.19 pickleshare==0.7.5 Pillow==8.1.1 pluggy==1.0.0 prometheus-client==0.8.0 prompt-toolkit==3.0.16 ptyprocess==0.7.0 py==1.11.0 py-vapid==1.7.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.20 Pygments==2.8.0 pyHanko==0.13.1 pyhanko-certvalidator==0.19.5 PyJWT==1.7.1 pyOpenSSL==20.0.1 pyparsing==3.0.6 PyPDF2==1.27.12 PyPDF3==1.0.6 pyrsistent==0.18.1 pytest==6.2.5 pytest-cov==3.0.0 pytest-django==4.5.1 pytest-spec==3.2.0 pytest-testdox==2.0.1 … -
Django views.py not rendering and giving error
i have an app called play, inside it i have made a templates folder and hello.html is saved there, in views.py I render hello.html it says hello is not defined Environment: Request Method: GET Request URL: http://127.0.0.1:8000/play/hello/ Django Version: 3.1.1 Python Version: 3.8.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'play'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\harsh\anaconda3\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\My Data\Programing\django\store\play\views.py", line 6, in say_hello return render(request, hello.html) Exception Type: NameError at /play/hello/ Exception Value: name 'hello' is not defined -
Django template tag accessing a queryset
i have a progression models : class Progression(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True ) started_module = models.ForeignKey(Module,on_delete=models.CASCADE,null=True,blank=True,) completedchapters = models.ManyToManyField(Chapter) class Meta: constraints = [ models.UniqueConstraint( fields=["started_module", "user"], name="unique_module_by_user" ) ] in my module view i have : def Module_Detail(request,module_slug): module = get_object_or_404(Module,slug=module_slug) context = { 'module' :module } return render(request,'courses/module-detail.html',context) in the module-detail template I want to do something like: {% if module in request.user.progression_set.all.started_module %} {{ you have already started this module }} {% endif %} but it does not seem to work -
Django filtering with select_related using Custom QuerySet, works in shell, fails in views
I am using Django 3.2 Below is a reduced portion of my code models.py class ItemQuerySet(models.QuerySet): def qualified(self): return self.filter(status=1) def training(self): return self.filter(status=2) def failed(self): return self.filter(status=3) def showable(self): Q1 = Q(status=1) Q2 = (Q(last_fields__isnull=False) & ~Q(last_fields__exact='')) return self.filter(Q1 | Q2) class Foobar(models.Model): # some fields objects_qualifiers = ItemQuerySet().as_manager() class Category(models.Model): pass class Foo(Foobar): title = models.CharField(max_length=16) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) category = models.ForeignKey(Category, on_delete=models.CASCADE) content = models.TextField() is_done = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py class FooListView(ListView): model = Foo template_name = 'foobar/index.html' context_object_name = 'foos' paginate_by = 5 ordering=['-created_at'] def get_queryset(self): return self.model.objects_qualifiers.showable().filter(is_done=True).all().select_related('author','category') When the view is accessed, it raises the following error: self.RelatedObjectDoesNotExist( foo.models.Foo.author.RelatedObjectDoesNotExist: Foo has no author. This (seems to) makes sense, because I am calling select_related on a QuerySet object - however, the error is a bit misleading, because it does identify and report the correct class (Foo) but then says that it has no author field. It would make sense if the error message said something like ItemQuerySet has no 'author' field. In order to test that my reasoning was correct, I decided to test my hypothesis in the shell: console output from foo.models import Foo foo = Foo.objects.get(id=1) foo.author … -
how to view models with foreign keys with serializers
Hi I am making a crud with serializers and I am having trouble viewing them.An error which I am unable to solve "ErrorDetail(string='Incorrect type. Expected pk value, received str.', code='incorrect_type')" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) functions def insert(request): if request.method == "POST": print('POST',id) insert_clothes = {} insert_clothes['categories']=request.POST.get('categories') insert_clothes['sub_categories']=request.POST.get('sub_categories') insert_clothes['color']=request.POST.get('color') insert_clothes['size']=request.POST.get('size ') # insert_clothes['image']=request.POST.get('image') insert_clothes['title']=request.POST.get('title') insert_clothes['price']=request.POST.get('price') insert_clothes['sku_number']=request.POST.get('sku_number') insert_clothes['product_details']=request.POST.get('product_details') insert_clothes['quantity']=request.POST.get('quantity') print("insert clothes:",insert_clothes) serializer = POLLSerializer(data = insert_clothes) print('form:',serializer.initial_data) if serializer.is_valid(): serializer.save() messages.success(request,'Record Updated successfully :)!!!!') return redirect('polls:show') else: print("invalid") print("error of serializer:",serializer.errors) return redirect('polls:insert') else: print('GET',id) return render(request,'polls/product_insert.html') def show(request): showall = Products.objects.filter(isactive=True) print("show all data:",showall) serializer = POLLSerializer(showall,many=True) return render(request,'polls/product_list.html',{"data":serializer.data}) can someone please point out to where I am going wrong?Thanks -
Prevent all data from being displayed with Django-filter
I am currently developing a search system using Django-filter. For example, if you search under the following conditions, all the displays will be returned. Data [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] views.py class CitySearchView(APIView): def get(self, request): if not request.GET: raise Http404() queryset = City.objects.all() filterset = FilterCity(request.query_params, queryset=queryset) serializer = CitySerializer(instance=filterset.qs, many=True) return Response(serializer.data) filter.py class FilterCity(filters.FilterSet): city = filters.CharFilter(lookup_expr='icontains') class Meta: model = City fields = [] Request URL there is no value. http://127.0.0.1:8000/api/search/?city= Response [ { "id": 1, "city": "aaa", }, { "id": 2, "city": "bbb", }, { "id": 3, "city": "ccc", } ] My hope is to return the string "Not Found" or empty array[]. In that case, how should I implement it? Thank you. -
Why pagination provided by django rest framework is not consistent?
I am currently using Django-Rest framework to implement the API endpoints. I am following the documentation to implement the pagination, my pagination class is, class Pagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page' I am using this class as follows:- class QuestionList(generics.ListAPIView): queryset = Question.objects.all().prefetch_related('tags').order_by('id') serializer_class = QuestionSerializer pagination_class = Pagination For the first page, i am getting objects from id 1 to 10 which is expected. But from second page onwards, i am only getting 2 objects per page(id 3 and 4 for second page) and i cannot find any reason behind this strange behaviour. What should i do to make the pagination consistent.