Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework simple jwt: decode() got an unexpected keyword argument 'verify'
now I have this error from django rest framework, and I don't know why. All was fonctionnal before. File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch self.initial(request, *args, **kwargs) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial self.perform_authentication(request) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication request.user File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user self._authenticate() File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework/request.py", line 380, in _authenticate user_auth_tuple = authenticator.authenticate(self) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/authentication.py", line 40, in authenticate validated_token = self.get_validated_token(raw_token) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/authentication.py", line 94, in get_validated_token return AuthToken(raw_token) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/tokens.py", line 43, in __init__ self.payload = token_backend.decode(token, verify=verify) File "/home/mathieu/.local/share/virtualenvs/back-aSs_Rzmq/lib/python3.8/site-packages/rest_framework_simplejwt/backends.py", line 90, in decode return jwt.decode( TypeError: decode() got an unexpected keyword argument 'verify' I follow the simple dango rest simple jwt example. My settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], } And my views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from .models import … -
How to access a serializer attribute from a method with no 'attrs' argument
Im trying to access the participants attribute in my conversation serializer from inside my 'get_other_user' method. My participants attribute returns a list of user dictionaries. However, when I run the code I get model has no attribute 'participants'. Im assuming I have to pass in a, 'attrs' argument in to the 'get_other_user' method, (one similar to the 'def validate(self, attrs) method), then use attrs.get('participants). However, I do not know how to fill in the attrs parameter when calling this method in my get_other_username method. Any advice would be appreciates. Thanks! class ConversationSerializer(serializers.ModelSerializer): other_username = serializers.SerializerMethodField(method_name='get_other_username', read_only=True) other_user_email = serializers.SerializerMethodField(method_name='get_other_user_email', read_only=True) # latest_message = serializers.SerializerMethodField(method_name='get_latest_message', read_only=True) participants = UsersSerializer(many=True, read_only=True) class Meta: model = Conversation fields = ['conversation_id' ,'participants','other_username', 'other_user_email'] def get_current_user_id(self): user_id = self.context['current_user'].id return user_id def get_other_user(self): current_user_id = self.get_current_user_id() for participant in self.participants: if participant['id'] != current_user_id: return participant def get_other_username(self, obj): other_user = self.get_other_user() return other_user['username'] def get_other_user_email(self, obj): other_user = self.get_other_user() return other_user.email -
'Poll' object has no attribute 'get_absolute_url'
When I followed django cms 3.9.0 documentation of part 8. Content creation wizards. I got this error. Is there anyone know that how to fix it? I will really appreciate your advices. AttributeError at /zh/cms_wizard/create/ 'Poll' object has no attribute 'get_absolute_url' Request Method: POST Request URL: http://127.0.0.1:8000/en/cms_wizard/create/ Django Version: 3.1.13 Exception Type: AttributeError Exception Value: -
Can't handle Crispy Forms with helper with ModelForm and Base View (UpdateView)
i know how to render and use with success a form with Crispy whatever the view type but only with templates.html (not forms.py). But seing that all my forms were vertical, i searched a way to customize them. For example being able to display 3 checkboxes or other fields on the same row. I spent several days trying to do it with Django native forms classes but couldn't obtain what i wanted with CSS. I also tried a long time to do it with Crispy and Helper witch seem to me the easiest way but it still doesn't work. Without success. I'm blocked at the very start of my test especially because i have to manage with a / URL parameter Whatever i try to do, a never-ending error raises : init() got an unexpected keyword argument 'pk' forms.py, line 9, in init --> super(SupplierDetailForm, self).init(*args, **kwargs) If i remove this constructor, same error raises deeply in Django -> site-packages/django/core/handlers/base.py, line 181, in _get_response First question : during all my searches, i saw that Model used or Fields were declared either in VIEW or in FORM class in its META. What method should i use ? 2nd question : i … -
Why doesnt PyJwt recognize the positional argument "algorithm" when using "ES256" signing method?
I'm using PyJwt to generate and encode a JWT for apple application notification service token authentication which requires the ES256 signing algorithm as noted here . self.server = settings.APNS_SERVER self.algorithm = 'ES256' PRIVATE_KEY = settings.APNS_PRIVATE_KEY encoded_jwt = jwt.encode( {'iss': settings.TEAM_ID, 'iat': time.time()}, PRIVATE_KEY, algorithm=self.algorithm, headers={'alg': self.algorithm, 'kid': settings.APNS_KEY_ID}, ) When passed this way, I get the following error: encoded_jwt = jwt.encode( File "/usr/local/lib/python3.9/site-packages/jwt/api_jwt.py", line 63, in encode return api_jws.encode(json_payload, key, algorithm, headers, json_encoder) File "/usr/local/lib/python3.9/site-packages/jwt/api_jws.py", line 114, in encode signature = alg_obj.sign(signing_input, key) File "/usr/local/lib/python3.9/site-packages/jwt/algorithms.py", line 423, in sign der_sig = key.sign(msg, ec.ECDSA(self.hash_alg())) TypeError: sign() missing 1 required positional argument: 'algorithm' This doesn't happen when I use the RS256 or HS256 signing algorithm. Why is this happening? -
Getting all products from Many2Many field Django
My User model looks like this: class User(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True) #other user informations, f.e. color, size, name followed = models.ManyToManyField( Product, related_name="followed_products", blank=True) objects = CustomAccountManager() object = models.Manager() def __str__(self): return self.email I am storing an user followed products inside followed = models.ManyToManyField(Product, related_name="followed_products", blank=True). I am adding products by this FollowView: def FollowView(request, pk): if request.COOKIES.get('refresh_token'): refresh = jwt.decode(request.COOKIES.get( 'refresh_token'), SECRET_KEY, algorithms=["HS256"]) user = User.objects.filter(id=refresh['user_id']).first() product = Product.object.filter(id=pk).first() user.followed.add(product) return Response({}, status=status.HTTP_200_OK) My Product model looks like this: class Product(models.Model): class ProductObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') id = models.UUIDField(primary_key=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #other Product informations object = models.Manager() productobjects = ProductObjects() def __str__(self): return self.name Now my question is, how can I GET all the products with details (f.e. name, color, size) and send them to frontend? I tried to GET them like this: user.followed.get(owner=refresh['user_id']) but it returns me an error: get() returned more than one Product -- it returned 2! (the 2 here is strange, because when I do user.followed.count() it shows me 3) -
How to detect user from token?
I have Django for my backend and vue for my frontend. I am using dj-rest-auth for authentication, and a token key is generated on each login. I could save this to vuex, but I am not really sure how to identify the user? I am building a blog, and editing of certain blog posts must be allowed only for the author? How should I get to generate the username from the token so that only the author can edit it? -
how to show tick mark on the values that are saved in databse for update form in Django
Let us consider soil_type selected while creating a item, while creating a item we can choose multiple choices of soil_type for example let us consider a tree_name = Hibiscus when can be grown in multiple soil_type like clay soil, red soil, acidic soil,.. (where these are choices of soil_type and is a multiple choice field in create form ) if suppose the user selected soil_type for Hibiscus as both clay soil and acidic soil while update form it should show ticked let us consider my forms.py as SOIL_TYPE_CHOICES = ( ('Acidic','Acidic'), ('Alkaline','Alkaline'), ('Chalk','Chalk'), ('Clay','Clay'), ('Damp','Damp'), ) class HorticlutureUpdateForm(BetterModelForm): soil_type = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=SOIL_TYPE_CHOICES, ) .... ..... class Meta: model = TreeDetails exclude = ('created_by', 'client', 'is_deleted') fieldsets = [ ["main", { "fields": ['tree_name', 'common_name','description', 'part_number', 'unit_price'], "legend": "Main details", }], ["extra", { "fields": [ 'quantity', 'height' 'soil_type', ], "legend": "Additional details", }], ] here is my index.html <form class="form-horizontal" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form.hidden_fields %}{{ field }}{% endfor %} <fieldset class="add"> <legend class="main">{{ form.fieldsets.main.legend }}</legend> <fieldset id="edit-contact-fields" class="edit-contact"> {% for field in form.fieldsets.main %} <div class="control-group" id="{{ field.name }}_wrapper"> <label class="control-label pull-left" for="{{ field.auto_id }}">{{ field.label }} {% if field.field.required %}<span class="text-error">*</span>{% endif %}</label> … -
save values of foreign key django
I want savevalues of foreign key model in view fuctions, this my models, forms, and views. models.py: enter image description here Forms.py: enter image description here View.py enter image description here -
AWS EB container commands - collectstatic failed
Currently, I'm trying to push all static files to S3 in django project, but deployment is failed because of the ERROR below : 2021/10/07 14:55:55.675229 [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: Container commands build failed. Please refer to /var/log/cfn-init.log for more details. 2021/10/07 14:55:55.675250 [INFO] Executing cleanup logic 2021/10/07 14:55:55.675339 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment successfully generated a 'Procfile'.","timestamp":1633618548,"severity":"INFO"},{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1633618555,"severity":"ERROR"}]}]} FYI, when I do 'python manage.py collectstatic' on my computer, the command perfectly works and all static files uploaded to S3. However, on ElasticBeanstalk, the container command does not work. So the deployment is failed as well. EB environment : Python 3.8 running on 64bit Amazon Linux 2/3.3.6 Just in case, as I use pipenv, which is known compatibility issue with AWS EB CLI, I used 'pipenv_to_requirement -f' to create requirements.txt Among the packages checked by the pipenv graph command, those not in requirements.txt were manually added. settying.py DEFAULT_FILE_STORAGE = "config.custom_storages.UploadStorage" STATICFILES_STORAGE = "config.custom_storages.StaticStorage" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "mybucket_202110" AWS_DEFAULT_ACL = "public-read" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.ap-northeast-2.amazonaws.com" STATIC_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/static/" django.config container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 … -
Django LogEntry model out of the admin
I am having some struggles how does exactly django.admin.LogEntry objects are created. The question is: django docs are not very descriptive on how does LogEntry works and I can not find the best way. Where I can put logic to save records? Signal/Form save override/Model Save override which will be simple and elegent way? Does anybody got any experience with such scenarios and can share thoughts about it? -
Django filter a model with it's related models fields
i have a Product model with multiple related models: Currency Category Material in the view i'm filtering according to a search query how can i get the result with every related model data. views.py : def product_autocomplete(request): query = request.POST.get("query") if len(query) > 2: products = Product.objects.filter( Q(name__contains=query) | Q(material__name__contains=query) | Q(identifier__contains=query) | Q(barcode__contains=query) ) products = serializers.serialize("json", products) result = {"result": products} return JsonResponse(result) models.py: class Product(models.Model): name = models.CharField(max_length=30, unique=True) stock_price = models.FloatField() price = models.FloatField() special = models.FloatField() expire = models.DateField(null=True, blank=False) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) seller = models.ForeignKey(Seller, on_delete=models.SET_NULL, null=True) material = models.ManyToManyField(Material) quantity_type = models.ForeignKey(QuantityType, on_delete=models.SET_NULL, null=True) quantity = models.FloatField() extra_quantity = models.FloatField(null=True, default=0) barcode = models.CharField(null=True, max_length=30, blank=False) identifier = models.CharField(null=True, max_length=30, blank=False) location = models.CharField(null=True, max_length=30, blank=False) alert_if_lower_than = models.IntegerField(null=True) image = models.CharField(max_length=100, blank=False, null=True) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=30, unique=True) desc = models.CharField(max_length=300, null=True, blank=False) def __str__(self): return self.name class Currency(models.Model): name = models.CharField(max_length=30, unique=True) value = models.FloatField() rate = models.FloatField() def __str__(self): return self.name class Material(models.Model): name = models.CharField(max_length=30, unique=True) desc = models.CharField(max_length=300, null=True, blank=False) def __str__(self): return self.name for now the result only returns the primary key of the related model. how to return the … -
How to add multiple records for foreign key in a single request in DRF?
There is a model named as UserSkill. It contains User and Skills ForeignKeys I want to create multiple skills for one user in single post request and i want to store data like this [{'user': 1, 'skills': 1,2,3,4}]. The problem is how can i write create method for that? I do not want to use ManyToMany field for that class UserSkill(models.Model): user = ForeignKey(User, on_delete=models.CASCADE) skills = ForeignKey(Skills, on_delete=models.CASCADE) class UserSkillSerializer(ModelSerializer): class Meta: model = UserSkill fields = "__all__" class UserSkillList(ListCreateAPIView): serializer_class = UserSkillSerializer queryset = UserSkill.objects.all() def create(self, validated_data): ... -
Using Django to process data without using persistent models
I am new to Django, and my question must be straightforward to answer: How can I use Django to process data without persistent models? I want to make a POST request that receives an incoming object, processes it, and returns an object with a dictionary attribute - no persistence of any kind. I am using the REST framework package for ViewSets, Models and Serializers, but I cannot figure out how to use these classes without persistence. -
How can I do drag and drop and save the state after drop on django
I newbie here, I try to do some projects on Django (sqlite). In this project, I try to do drag and drop on a webpage. The drag and drop card was made. Then I do with jquery and jquery ui but it doesn't work. I want to drag the card to the zone that I made from . In the have an of building blueprint. the card will drop in the room direction and they stay in the position after drop even though refresh. How should I do? I have been looking for its solutions but didn't find any help. Thank you -
Item does not decrease Django
Hello I want to make a feature, that if I click quantity decrease by 1 but it does not decrease and only returns HttpResponse. class CartView(TemplateView): template_name = "shop/cart.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cart'] = Cart.objects.annotate( price=Sum(F('orderitem__item__price') * F('orderitem__quantity')) ).get(order_user= self.request.user) cart = context['cart'] cart.total = cart.price cart.save() context['order_items'] = OrderItem.objects.filter(cart=cart) return context def post(self, request): if 'minus' in request.POST: cart = Cart.objects.get(order_user=self.request.user) primary = request.POST.get('orderitem__id') item = OrderItem.objects.filter(id=primary, cart=cart) item.quantity = F('quantity') - 1 item.update() return HttpResponse("cart uptaded") -
Django form is not showing up
Here is my forms.py from django import forms class EmailForm(forms.Form): from_ = forms.EmailField(max_length=50) Here is my views.py from django.shortcuts import render from .forms import EmailForm def index(request): return render(request, "base.html") def emailSender(request): form = EmailForm(); return render(request, "base.html", {"form" : form}); And finally here is my html template <form id="form" method="post"> {% csrf_token %} {{ form }} <div class="form-outline mb-4"> <label class="form-label" for="from">From:</label> {{ form.from_ }} </div> Any of my {{ form }} does not work. When I check the inspect tab they both are not created so I think this isn't some css problems here. -
Why i get error when i try to create an article for a child user?
Here is the problem: When I try to create article for the user itself, it works. But when I try to create an article as the parent of the child user instead of the child user itself, I get a validation error. I am trying to make sure the parent is the authenticated user. How can I solve this issue? class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) class ArticleCreateSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('id','author','caption') def validate(self, attrs): attrs = super().validate(attrs) if attrs['author'].id != self.context['request'].user.pk: raise ValidationError('Unauthorized Request') elif attrs['author'].parent.id == self.context['request'].user.pk: return attrs elif (attrs.get('author').parent != None) and (attrs.get('parent').id != self.context['request'].user.pk): raise ValidationError('Unauthorized Request') return attrs -
Django pytest: can't test userpage detail
I have a detailed page of the author of the blog, which uses following urlpatterns urls.py from . import views from django.urls import path,include urlpatterns = [ path('all/', views.PostListView.as_view(), name='all'), path('<int:id>/',views.PostDetailView.as_view(), name='detail'), path('blogger/<username>/',views.userpage, name='userpage'), path('bloggers/', views.allblogers, name='allauthors'), ] main urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('app.urls')), path('account/', include('accounts.urls')) ] When using this test function, an error occurs: WARNING django.request:log.py:224 Not Found: /blog/1/ ========================== short test summary info ========================== FAILED app/tests.py::test_user_detail - assert 404 == 200 tests.py @pytest.mark.django_db def test_user_detail(client, django_user_model): user = django_user_model.objects.create( username='someone', password='password' ) url = reverse('detail', kwargs={'id': user.id}) response = client.get(url) assert response.status_code == 200 assert 'someone' in response.content -
Django - Table-like form for updating multiple relationships between multiple objects at the same time
Context Say I have two Orders (O1, O2) and three Tasks that can be done multiple times (T1, T2, T3). The table below shows how many repetitions of each task have been ordered: so e.g. order O1 consists of 2 reps of T1 and 8 reps of T2. I have all year to do these repetitions, but I want to control how many were done each month. Say these are the repetitions that I did: so in the month of September I only did 4 repetitions of task 2 and assigned 1 to order 1 and 3 to order 3 in October, I did 2 reps of T1 for O1, 2 reps of T2 for O1, and 1 rep of T3 for O2 and so on for November I am currently storing each of these numbers in the second table as a RepetitionLog object (with fields task, order, month, and reps) that looks like this: class RepetitionLog(models.Model): task = models.ForeignKey(Task, on_delete=models.CASCADE) order = models.ForeignKey(Order, on_delete=models.CASCADE) reps = models.DecimalField('Geleistete Wiederholungen', max_digits=9, decimal_places=2) month = models.DateField('Monat') Question My main question is what's the best way to generate an interactive table similar to the second table above and use it to create/update several … -
Forms not showing up when using a registration app
I'm using this app to register the user of my website https://github.com/egorsmkv/simple-django-login-and-register. The problem is that no metter what I do my form are not visible (they were when I did not use this registration app and the code worked just fine). This is my code: model class UserBio(models.Model): name = models.CharField(max_length=120) age = models.CharField(max_length=2) phone = models.CharField(max_length=10) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) form class UserBio(forms.ModelForm): class Meta: model = UserBio fields = (name', 'age', 'phone', 'height', 'weight') views def add_bio(request): submitted = False if request.method == "POST": info_form = UserBio(request.POST) if info_form.is_valid(): info_form.save() return HttpResponseRedirect('add_information?submitted=True') else: info_form = UserBio() if 'submitted' in request.GET: submitted = True return render(request, 'accounts/profile/add_information.html', {'form': info_form, 'submitted':submitted}) urls urlpatterns = [ path('add/information', views.add_information, name='add_information'), ] html {% extends 'layouts/default/base.html' %} {% block title %} Add info {% endblock %} {% load i18n %} {% block content %} <h4>{% trans 'Add Info' %}</h4> {% if submitted %} Sumitted correctly {% else %} <form method="post"> {% csrf_token %} {{ info_form.as_p }} </form> </div> <br/> </body> {% endif %} {% endblock %} Any help would be very apprecieted! -
How to sent POST request to Django from external app
I am trying to sent post request from python script which works on Windows machine. Here is my views.py Django def check(request): if 'login/password' in request.POST: checkdata(request.POST) else: message = '404' return HttpResponse(message) And here is my post.py param_tuples = [('login', 'value1'), ('pass', 'value2')] response = requests.post('http://127.0.0.1:8000/check', data=param_tuples) The problem is that Django reject my request because i dont have csrf token Forbidden (CSRF cookie not set.): /check How can i get csrf token in order to sent request to Django server externally ? -
How to serve non ascii file name with django and apache using xsendfile
I wanted to serve protected contents in django,so I tried to set xsendfile in both django and apache. It works for ascii file names, but when I tried with non-ascii file name the apache server reponds with 404. Do any one know whats going on here? Django: def media_xsendfile_pdf(request): file = Media.objects.last() response = HttpResponse() response['Content-Type'] = 'application/pdf' response['X-Sendfile']= smart_str(f"{settings.BASE_DIR}{file.file.url}") return response Apache: AllowEncodedSlashes On XSendFile On XsendFilePath /path-to-the-protected-resource Blockquote -
Get Many to many fileds in django model with together model fields
I have two models; class userPageAuths(models.Model): enName = models.CharField(max_length=30) trName = models.CharField(max_length=30) def __str__(self): return self.enName class userPages(models.Model): enName = models.CharField(max_length=30) trName = models.CharField(max_length=30) parent_id = models.IntegerField(blank=True, null=True) user_page_auths = models.ManyToManyField(userPageAuths, related_name="page_auth_list", blank=True) def __str__(self): return self.enName First model data is in my database; second model data is; and this data is for many to many field; I want to get all data like this; [ { "id": 1, "enName": "x", "trName": "x", "parent_id": null }, { "id": 2, "enName": "y", "trName": "y", "parent_id": null }, { "id": 3, "enName": "z", "trName": "z", "parent_id": 2 }, { "id": 1, "enName": "a", "trName": "a", "parent_id": 3 // this userpages_id which connected manytomany relation and ı want to get this as a parent_id }, { "id": 2, "enName": "b", "trName": "b", "parent_id": 3 }, { "id": 3, "enName": "c", "trName": "c", "parent_id": 3 }, ] I use this serailizers; class pagesSerializer(serializers.ModelSerializer): class Meta: model = userPages fields = ('id', 'enName', 'trName', 'parent_id') and this is my method; class pagesListView(ListAPIView): serializer_class = pagesSerializer def get_queryset(self): return list(itertools.chain(userPages.objects.all(), userPageAuths.objects.all())) ı got data like this; [ { "id": 1, "enName": "x", "trName": "x", "parent_id": null }, { "id": 2, "enName": "y", "trName": "y", "parent_id": null … -
Define component schema with drf-spectacular for django API
I am using drf-spectacular to generate an OpenAPI schema for django. As I am not using serializers, I am defining everything in the extend_schema decorator. Now my question is, if it is possible to manually define a component schema. Here is an example what my api view looks like: from rest_framework.decorators import api_view from drf_spectacular.utils import (extend_schema, OpenApiExample) from drf_spectacular.types import OpenApiTypes from rest_framework.response import Response @extend_schema( examples=[OpenApiExample( value=[ {'title': 'A title'}, {'title': 'Another title'}, ], )], responses={ 200: OpenApiTypes.OBJECT } ) @api_view(['GET']) def list_articles(request): return Response([{'title': 'Test1'}, {'title': 'Test2'}]) and the corresponding component is shown as empty (e.g. in swagger): Here is the definition in the documentation but I cannot figure out how to achieve it with drf-spectacular.