Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms - how to dynamically alter field labels
How do I dynamically alter field labels in forms in Django In the below code, the labels word in the def clean_passport function is 'greyed out', saying 'labels' not accessed class LegalDocumentUpdateForm(forms.ModelForm): # FORM META PARAMETERS class Meta: model = Legal_Document fields = ('document_type', 'name_on_document', 'number_on_document', 'issuing_country', 'issuance_date', 'expiry_date', 'document_location') labels = { 'document_type': _("Document Type*"), 'name_on_document': _("Name on Document*"), 'number_on_document': _("Document Number"), 'issuing_country': _("Issuing Country"), 'issuance_date': _("Issuance Date"), 'expiry_date': _("Expiry Date"), 'document_location': _("Document Location*") } # SANITIZATION & VALIDATION CHECKS def clean_passport(self): document_type = self.cleaned_data['document_type'] number_on_document = self.cleaned_data['number_on_document'] issuing_country = self.cleaned_data['issuing_country'] expiry_date = self.cleaned_data['expiry_date'] if document_type == 'Passport': labels = { 'name_on_document': _("Passport Full Name*"), 'number_on_document': _("Passport Number*"), 'issuing_country': _("Issuing Country*"), 'expiry_date': _("Passport Expiry Date*"), } if number_on_document == None: raise forms.ValidationError(_("Please enter the Passport Number.")) if issuing_country == None: raise forms.ValidationError(_("Please enter the Passport's Issuing Country.")) if expiry_date == None: raise forms.ValidationError(_("Please enter the Passport's Expiry Date.")) -
What is the syntax to pass a query in the ajax url using Django
I'm opening a modal with ajax, but I'm having a problem because I need to access a url on my site that needs a query <script> document.getElementById('myBtn2').onclick = function(){ $.ajax({ url:"{% url 'add_data' %}?filter=crew", type:'GET', success: function(data){ $('#modal-content2').html(data); } }); } </script> I can't access url with the query, just the url alone. for example: url:"{% url 'index' %}" But if I put a query in the url it still doesn't work. I think the syntax is wrong and I can't figure out what it looks like. url:"{% url 'add_dados' %}?filter=crew" --> doesn't work Any suggests? -
django ValidationError in admin save_model
Models.py class user(AbstractUser): salary_number = models.IntegerField(unique=True, null=True, blank=True) Admin.py def save_model(self, request, obj, form, change): if obj.salary_number == None: raise ValidationError("ERROR salary number!") .... obj.save() I'm trying to show error for user if they forget to fill salary number, but I got error ValidationError at /admin/information/user/add/. How can I fixed that? I have a reason to not set salary_number null & blank = False. -
Django Session auth and React token auth using one login page
I am working on converting an existing Django app (templates) to a microservices architecture - with a React frontend and a Django REST backend and am looking into how to handle authentication from a separately served (Nginx) React app where the user will be logging in using Django Session auth. Both frontend and backend will be served from the same domain using Nginx. Every service is packaged up in a separate Docker container. I am currently using the built in django.contrib.auth views for Session Auth: # authentication path('login/', auth_views.LoginView.as_view( template_name='users/login.html', authentication_form=AuthForm), name='login'), path('logout/', auth_views.LogoutView.as_view( template_name='users/logout.html'), name='logout'), The change will begin with writing new pages in React. Since these built-in Django auth views use Session Auth, and React usually relies on Token Auth, what are my options for using both Session and Token auth? My thought was to login using the built-in session auth and send a token with the response at the same time as the session response. Since the session will be authenticated, can the built-in session auth views be extended to send a JWT with the response then save it to local storage for access by React? Or should I focus on implementing session auth usage in React … -
Adding watchlist. Watchlist not displaying added items Django
I am trying to work on a project and one of the features is that users who are signed in should be able to visit a Watchlist page, which should display all of the listings that a user has added to their watchlist. So far, I am redirected and receive the pop-up message when 'add to watchlist' is clicked but it does not bring up the button of 'remove from watchlist' and also when it redirects me to the watchlist page (where i should view the users entire watchlist), it shows me 'No watchlist found.'. I have triple-checked and I am iterating properly (I think) but I don't know why it is not showing any of the watchlist) URLS.PY path("add_watchlist/<int:listing_id>/", views.add_watchlist, name="add_watchlist"), path("watchlist", views.watchlist, name="watchlist"), MODELS.PY class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) item = models.ManyToManyField(Auction) def __str__(self): return f"{self.user}'s watchlist" LAYOUT.HTML <li class="nav-item"> <a class="nav-link" href="{% url 'all_category' %}?category={{ category.name}}">Category</a> <li class="nav-item"> <a class="nav-link" href="{% url 'create_listing' %}">Sell</a> </li> <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'watchlist' %}">Watchlist</a> {% endif %} </li> </ul> VIEWS.PY @login_required def add_watchlist(request, listing_id): items = Auction.objects.get(pk=listing_id) watched = Watchlist.objects.filter(user=request.user, item=listing_id) if request.method == 'POST': if watched.exists(): watched.delete() messages.success(request, 'Listing removed from watchlist') … -
Can someone help me use react integrated paycard template in open layer payment gateway
I want to put my custom UI instead of open layer payment gateway UI but I am having issues understanding the code of the gateway. From what I have understand that it is ready made UI Payment Gateway and I am having issues replacing styling of this gateway. My website is using Django + React frameworks. Payment Gateway I am integrating in my website: https://github.com/bankopen/layer-sdk-python React Paycard template I want to use: https://github.com/jasminmif/react-interactive-paycard Warm Regards Keshav -
How to sort a model for a month's data in django?
This is for a project where we can enter income and expenditure and save it in the model. I need to sort records in a model according to month basis, like record for previous month. -
Django Password Recovery via Gmail [Errno 110] Connection timed out
I had a password recovery system via email in my web app, which was working perfectly before deployment. However, now that I have succesfully deployed, password recovery is the only feature that is not working, when solicited it stays loading for some time until the error TimeoutError at /password-reset/ [Errno 110] Connection timed out Here is my settings.py file email configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = config.get('EMAIL_USER') EMAIL_HOST_PASSWORD = config.get('EMAIL_PASS') The credentials are tucked away into config file. What could be causing this issue? -
NOT NULL constraint when creating a new user in django
I created a Django API to create a new user. However, when I try to create a user I get the error message: IntegrityError at /api/v1/users/register/ NOT NULL constraint failed: accounts_user.user_id This is what I have in 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 class User(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) password = models.CharField(max_length=32) email = models.EmailField(max_length=150) signup_confirmation = models.BooleanField(default=False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: User.objects.create(user=instance) instance.profile.save() In serializers.py from rest_framework import serializers from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('user_id', 'name', 'location', 'password', 'email', 'signup_confirmation') and my views.py from rest_framework import viewsets from .serializers import UserSerializer from .models import User from rest_framework.decorators import action from .forms import SignUpForm from .tokens import account_activation_token class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('name') serializer_class = UserSerializer @action (detail=True, methods=['post']) def register(self, request): print(request) Any ideas on what I can do to resolve this error -
Dango - show title from multiple models in autocomplete search bar
I want to display titles from 2 models in my autocomplete feature in the search bar, however, I am not sure how to write a loop in search_address_qa function that would display titles from multiple models. For now, I can only properly display address_objects (Article) or address_objects_qa(QA) but not both. The results from search_items are fine. When I try to put for address_object in address_objects_qa or address_objects then I get some random results. models.py class QA(models.Model): title=models.CharField(max_length=1000, help_text='max 1000 characters') body = RichTextField(verbose_name='Description', blank=True) class Article(models.Model): title=models.CharField(max_length=1000, help_text='max 1000 characters') body = RichTextField(verbose_name='Description', blank=True) views.py @login_required def search_address_qa(request): query = request.GET.get('title') payload = [] if query: lookups = Q(title__icontains=query) address_objects = Article.objects.filter(lookups, status=1) address_objects_qa = QA.objects.filter(lookups, status=1) for address_object in address_objects_qa: payload.append(address_object.title) return JsonResponse({'status':200, 'data': payload}) @login_required def search_items(request): query = request.GET.get('q') article = Article.objects.filter(title__icontains=query) qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) |Q(body__icontains=query) article = Article.objects.filter(lookups).distinct() qa_list = QA.objects.filter(lookups).distinct() context = { 'query_name': query, 'search_items': article, 'qa_list': qa_list, } return render(request, 'search/search_items.html', context) search_items.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=yes" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous"> <link rel="stylesheet" href="https://unpkg.com/@trevoreyre/autocomplete-js/dist/style.css" /> </head> <body> <main class="container-fluid"> <!--HEADER--> <header class="header" id="header"> <h3 class="col-6">Search results … -
Django : Upload multiple files in a directory labeled by the user
I am a newbee in Django and I try to do an application to upload multiple files by using forms. What's more, I would like that the files are save in a directory that contains the name of the user when it is authenticated. I use different tutorial that I could find but I do not understand why it does not work. Below you find my code. Thank you for your help. models.py from django.db import models def user_directory_path(user, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(user, filename) class Files(models.Model): files = models.FileField(upload_to=user_directory_path) uploaded_at = models.DateTimeField(auto_now_add=True) forms from django import forms class FilesForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) views.py def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', None) if error != None: context['errors'] = [] context['errors'].append(error) # Check for user in the session context['user'] = request.session.get('user', {'is_authenticated': False}) return context def upload(request): context = initialize_context(request) if request.method == 'POST': form = FilesForm(request.POST, request.FILES) files = request.FILES.getlist('file_field') if form.is_valid(): for f in files : newfile = Files(f) newfile.save() else: form = FilesForm() # Load files for the list page files = Files.objects.all() context['files'] = files return render(request, 'base/upload.html', context) settings.py STATIC_URL = … -
Paginate tables separately on same page?
I'm using tables2 for django. I have my tables (mostly) working, just some fine tuning of the rendering, but the data is all there. The trouble that I'm having is that I have several tables on one html page. Some of the tables might have four records, while others might have several hundred. When I paginate I get the "Next" box at the bottom of the tables that have more records. However, when I press the button, I can see that it's trying to go to page #2 of some of the tables that only have one page and giving me an error. Is there a way that I can ID each of my tables? Ideally, a user could be on page #1 for Table1, page #15 for Table2, page #73 for Table3, etc. -
Django Update User form photo saves but doesnt update in the site itself
So I am trying my hand out at my first django project on my own after tutorials, and I am trying to add an update user profile page. The username and email update perfectly fine, but when i try to update the profile picture, it doesnt update.Even though the file is saved in my media folder. forms.py: class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email') class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ('image',) views.py @login_required def profile(request, pk): user = User.objects.get(id=pk) profile = Profile(user=user) user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) if request.method == 'POST': user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() return redirect('home') return render(request, 'registration/profile.html', {'user': user, 'profile': profile, 'user_form': user_form, 'profile_form': profile_form}) If you need any more code i will update the question. What exactly is the problem here? -
Django Rest Framework GET request slow only on initial page load or reload
I'm using DRF as my backend API in conjunction with React. I am making a GET request using fetch and then populating a react table with the data provided by DRF. The issue is that when I first load the page or when I manually refresh it, theres a significant delay for the data to be fetched. I've tried limiting to 5 items but it still always takes 2 seconds. However, if I make the same request after the page has fully loaded the speed is normal. I've added a gif to illustrate in case I didn't explain it properly. Once the role is updated in the DB, the same GET request is done again to repopulate the table. My views, models and serializers: @api_view(['GET']) def getUserData(request): items = User.objects.all() # enabling pagination because api_view doesn't have it by default paginator = LimitOffsetPagination() result_page = paginator.paginate_queryset(items, request) # creating 1 serializer instance for paginated and 1 for full serializer_page = UserSerializer(result_page, many=True) serializer_full = UserSerializer(items, many=True) # if limit is not specified, return all object data if 'limit' not in request.query_params: return Response(serializer_full.data) else: return Response(serializer_page.data) class Role(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='roles') assigned_role = models.CharField(max_length=100) class RoleSerializer(serializers.ModelSerializer): class Meta: … -
Django validate FileField with clean()
I have a Form that includes a FileField and a CharField. Both work as expected. Neither field is required by itself, but one of them has to be given. So I want to add a validation that fails if both are empty. in forms.py: class MyForm(forms.Form): mytext = forms.CharField( label = "Enter text", required=False ) myfile = forms.FileField( label = "Or upload file", required=False ) def clean(self): cleaned_data = super().clean() mytext_value = cleaned_data.get("mytext") myfile_value = cleaned_data.get("myfile") # this remains empty, even after selecting a file! :-( if not mytext_value and not myfile_value: self.add_error("mytext", "Either text or file must be given!") This validation fails even if a file has been uploaded! (It does not fail if the text field has been used.) If I disable the validation, the form works fine within the app. In views.py, I can get the uploaded file from the request (myfile_value = request.FILES.get("myfile")) and work with it. But how do I get the content of the file during the clean() call, where I do not have a request, yet? self.files gives me an empty MultiValueDict, self.data doesn't contain the key myfile at all, and in cleaned_data, myfile is None. How can I check during form validation … -
How to send emails with get_connection method in django?
I'm trying to send emails. First i am creating connection instance with get instance. And getting all email host credentials from db. the connection instance is creating all flow is going good but i am not receiving email on my email address. On error is raising.. Step one:(passing email host object in connection function) def send_mass_html_mail_dynamic(email_object,request_data,template=None): email_host = EmailHost.objects.if_exists(request_data["email_host"]) connection = email_connection(email_host) #here is connection function that returns connection object. Step two:(creating connection with the credentials of email host) def email_connection(email_host=None): if email_host: password = decypt(email_host.password) print("password :",password) print("ssl :",email_host.use_ssl) connection = get_connection( host=email_host.host, username=email_host.email, password=password, port=email_host.port, use_tls =email_host.use_tls, use_ssl =email_host.use_ssl, fail_silently=False ) return connection step three(send messages with connection object) ..... messages = [message1,message2] print("reached to connect send instance") connection.send_messages(messages) print("sent to all") -->send to all is printing with no error...but im email is not receiving in my email address... I have triple checked email host credentials and also print them they are correct. -
What is the difference between `blocktrans` and `blocktranslate`? Between `trans` and `translate`?
What is the difference between these two lines of code in a Django template? {% blocktrans %}Example{% endblocktrans %} {% blocktranslate %}Example{% endblocktranslate %} Likewise, what is the difference between these two lines of code in a Django template? {% trans "Example" %} {% translate "Example" %} -
How can I remove null keys with values from JSON object in python?
I have a JSON object in which I want to remove the null key with the value that is my JSON. Please give me a solution how can I remove the null attribute with key and value from the object and can get without null keys data This is my JSON object { "null": "John", "Category": "General", "Product": "Shoes", "Size": "40" } -
Fixing Nginx Django uWSGI proxy timeout error
Nginx proxy is sending a timeout on 60sec even though timeout is set on higher values. How can I force a no-timeout or a >60sec timeout. My conf file for nginx is: server { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; proxy_connect_timeout 9000s; proxy_send_timeout 9000s; proxy_read_timeout 9000s; listen 8080; location /static { alias /vol/static; } location / { include /etc/nginx/uwsgi_params; uwsgi_pass toolsportal:8000; proxy_buffers 8 16k; # Buffer pool = 8 buffers of 16k ·fixes large cookie 502https://unix.stackexchange.com/questions/605467/how-to-handle-a-too-large-cookie-causing-nginx-to-return-a-502 proxy_buffer_size 16k; # 16k of buffers from pool used for headers proxy_connect_timeout 9000s; proxy_send_timeout 9000s; proxy_read_timeout 9000s; send_timeout 9000s; client_body_timeout 9000s; uwsgi_socket_keepalive on; uwsgi_send_timeout 3600s; uwsgi_read_timeout 3600s; } } Where "toolsportal" is the Django app service -
How to get email from google oauth token in django allauth social login?
I am using allauth for social login(google).If user is already registered with manual process and if the user tries google login with same email, response says "user already exists with this email". I want to know how to get the email address of that user from tha google access token so that i can take action furter. -
DjangoFilterBackend doesn't seem to call `filter()` on object manager
I'm building out a DRF/Django application and am trying to bootstrap the filtering on one of my models. The ModelViewSet in question uses DjangoFilterBackend for filtering, and the filtering works correctly, but the filtering doesn't seem to call the filter function on the Model's manager. ExModelViewset class ExModelViewSet(ModelViewSet): filter_backends = [ ExDjangoFilterBackend, ] def filter_queryset(self, *args, **kwargs): filtered_queryset = super().filter_queryset(*args, **kwargs) print(type(filtered_queryset.model.objects)) return filtered_queryset This prints <class 'assets.mixins.LinkedNodeManager'>, so we're using the right manager. EDjangoFilterBackend class ExDjangoFilterBackend(DjangoFilterBackend): def filter_queryset(self, request, queryset, view): queryset = super().filter_queryset(request, queryset, view) return queryset DeliverableViewSet class DeliverableViewSet(ExModelViewSet): """Allows REST access to the Deliverable model""" queryset = ( models.Deliverable.objects.all() .select_related("node", "asset", "language", "node__kind") .prefetch_related("node__links", "asset__publications", "asset__publications__platform") .order_by("node__path") ) serializer_class = serializers.ExDeliverableSerializer filter_fields = { "node": ["exact"], "node__code": ["exact", "in"], "node__code_path": ["exact", "istartswith"], "node__depth": ["lte", "exact"], "node__kind__code": ["exact", "in"], "node__links__code": ["exact", "in"], "node__links__code_path": ["exact", "in", "istartswith"], "kind__code": ["exact", "in"], "language__code": ["exact", "in"], } search_fields = [] You can see this uses the objects manager, which is using the correct mixin. LinkedNodeManager & LinkedNodeManagerMixin class LinkedNodeManager(ExManager): """Appends linked nodes to filtering""" def get(self, *args, **kwargs): print("I'm in the get!") node__code_path = kwargs.pop("node__code_path", None) if node__code_path is not None: kwargs["node__code_path"] = node__code_path return super().get(*args, **kwargs) def filter(self, *args, **kwargs): … -
Change Cell Color Conditional Formating Django HTML
I have a table in my HTML view that I want the cell background to change when a certain value is within the cell. Here is a screenshot of my table in HTML. The values are populated with a simple for loop within my Django views. Attached you will see the css and HTML. On the top of the table, you will see the legend. For example if the value in any td tag == 6 , make cell background rgb(1, 109, 167). That's what I'm trying to accomplish. Thanks <div class="table-responsive"> <table class="table" id="scores"> <thead> <tr> <td rowspan="3"></td> <th colspan="3" scope="colgroup">Reasoning</th> <th colspan="3" scope="colgroup">Executive Functions</th> <th colspan="2" scope="colgroup">Speed</th> <th colspan="2" scope="colgroup">Memory</th> </tr> <tr> <th scope="col">Verbal</th> <th scope="col">Spatial</th> <th scope="col">Abstract</th> <th scope="col">Flexible</th> <th scope="col">Working Memory</th> <th scope="col">Attention</th> <th scope="col">Processing</th> <th scope="col">Visual Motor</th> <th scope="col">Verbal</th> <th scope="col">Visual </th> </tr> </thead> {% for i in scores %} <tbody> <tr> <td>{{i.test_date}}</td> <td>{{i.reasoning_verbal }}</td> <td>{{i.reasoning_spatial}}</td> <td>{{i.reasoning_abstract}}</td> <td>{{i.executive_flexibility}}</td> <td>{{i.executive_working_memory}}</td> <td>{{i.executive_attention}}</td> <td>{{i.speed_processing}}</td> <td>{{i.speed_visual_motor}}</td> <td>{{i.memory_verbal}}</td> <td>{{i.memory_visual}}</td> </tr> </tbody> {% endfor %} </table> #d6 { background-color: rgb(1, 109, 167); color: black; } #d5 { background-color: rgb(1, 167, 164); color: black; } #d4 { background-color: rgb(154, 191, 80); color: black; } #d3 { background-color: rgb(228, 190, 36); color: black; … -
How to logged a user in just after Sign up with class based views?
I am working on a site which deals in selling images,i am tryting to find out a way so that user can login after signup using class based views, I have already done it with function based views, but i want to do it class based, because its requires less code. Below is with function based views: My models.py: from django.db import models from django.contrib.auth.models import User class JobType(models.Model): job_name = models.CharField(max_length=50) def __str__(self): return self.job_name class Country(models.Model): country_name = models.CharField(max_length=50) def __str__(self): return self.country_name class IndianState(models.Model): state_name = models.CharField(max_length=30) def __str__(self): return self.state_name class SignUpModel(User): company_name = models.CharField(max_length=80) job = models.ForeignKey(JobType, on_delete=models.CASCADE) mobile_no = models.PositiveIntegerField() country = models.ForeignKey( Country, on_delete=models.CASCADE, blank=True) state = models.ForeignKey(IndianState, on_delete=models.CASCADE) forms.py from django import forms from django.contrib.auth.forms import AuthenticationForm, UsernameField from django.utils.translation import gettext, gettext_lazy as _ from django.core import validators from .models import JobType, SignUpModel class MyAuthenticationForm(AuthenticationForm): username = UsernameField(widget=forms.TextInput(attrs={'autofocus': True})) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput(attrs={'autocomplete': 'current-password'}), ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password." ), 'inactive': _("This account is inactive."), } class LoginForm(MyAuthenticationForm): username = UsernameField(widget=forms.TextInput( attrs={"autofocus": True, "class": 'form-control', 'placeholder': 'Enter Username'}), error_messages={'required': 'Enter Username'}) password = forms.CharField( strip=False, widget=forms.PasswordInput( attrs={'placeholder': "Enter Password", 'class': 'form-control', … -
How to GET multipule ModelSrializer in one APIVIEW using Django Rest Framework
I have UserModel each user has multiple package and each package have price and program. model.py: class User(models.Model): name= models.CharField(max_length=100) class Package(models.Model): package_name = models.CharField(max_length=100) user= models.ForeignKey(User, on_delete=models.CASCADE,related_name='user_package') class Program(models.Model): title = models.CharField(max_length=100) user_package = models.ForeignKey(Package, on_delete=models.CASCADE) class Price(models.Model): price = models.FloatField() user_package = models.ForeignKey(Package, on_delete=models.CASCADE) serializer look like: class UserSerializer(NestedCreateMixin, NestedUpdateMixin,serializers.ModelSerializer): program = ProgramSerializer(source='user_program', many=True, read_only=True) package = PackageSerializer(source='user_package', many=True, read_only=True) price = PriceSerializer(source='price', many=True, read_only=True) class Meta: model = User fields= ("__all__") views.py: class user_apiView(APIView): def get(self, request): user= user.objects.all() serializer = UserSerializer(user, many = True) return Response(serializer.data) and that what I get: { "id": 1, "package": [ { "id": 1, "package_name": "wfe", "user": 1 }, { "id": 2, "package_name": "wfe", "user": 1 } ] } how can GET this RESULT? { "id": 1, "package": [ { "id": 1, "package_name": "wfe", "user": 1 }, { "id": 2, "package_name": "wfe", "user": 1 } ], "price": [ { "id": 1, "price": "wfe", "package": 1 }, { "id": 2, "price": "wfe", "package": 2 } ] "program": [ { "id": 1, "title": "wfe", "package": 1 }, { "id": 2, "title": "wfe", "package": 2 } ] } -
parse id in url Django
I want to be able to parse an id in my url and then get information from that url. If i don't parse a url, i would like to see all information my urls.py from django.urls import path from . import views from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ path('', views.home, name="home"), path('title', views.titles, name="titles"), path('json/<article_id>', views.articleList.as_view(), name="json"), ] my views.py class articleList(APIView): def get(self, request, article_id): if article_id == None: articles = Information.objects.all() serializer = InformationSerializers(articles, many=True) return Response(serializer.data) else: articles = Information.objects.filter(id = article_id) serializer = InformationSerializers(articles, many=True) return Response(serializer.data) def post(self): pass If i don't put anything behind .../json/ i get an error that i should fill in an id. How do i solve this issue?