Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to Update my Profile data in Django Forms
i extend the User Model to create profile dashboard,First I create a model named 'Profile to update some personal details. Now I want to extend User model to add educational details in profile dashboard. for this I extends User Model and then Try all ways to add and Update the data.My issue is all my code is working but when i click on update data is not going into my admin panel. Here is all my code` < Models.py from django.db import models from django.contrib.auth.models import User from PIL import Image from datetime import date GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) Martial_Status = ( ('M', 'Marriad'), ('U', 'Unmarriad'), ) Uni_CHOICES = ( ('IUB', 'The Islamia University Of Bahawalpur'), ) F_CHOICES = ( ('E', 'Faculity Of Engineeeing'), ) D_CHOICES = ( ('D', 'Department Of Information and Commmunication Engineering'), ) class Educationaldetails(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) University_Name =models.CharField( choices=Uni_CHOICES,max_length=50) Faculity = models.CharField( choices=F_CHOICES,max_length=50) Department_Name = models.CharField( choices=D_CHOICES,max_length=50) Degree_Title = models.CharField( max_length=50) Student_Id = models.CharField( max_length=50,unique=True) Registration_Number = models.CharField( max_length=50,unique=True) Transript_No = models.CharField( max_length=50,unique=True) C_GPA = models.CharField( max_length=50,default='0/4.00') Final_Year_Project = models.TextField() Supervisor_Name = models.CharField( max_length=50) Views.py def Educational_details(request): if request.method == 'POST': u_form = UserUpdateForm(instance=request.user, data=request.POST) E_form = EducationalUpdateForm(instance=request.user.profile, data=request.POST) if … -
How to create "related_name" relation with parent models of "through" model (about related_name inheritance)
I have 4 models including one M2M "through" model enabling to had an index: class TargetShape(models.Model): pass class Page(models.Model): target_shapes = models.ManyToManyField(TargetShape, through='PageElement', related_name='pages') class PageElement(models.Model): target_shape = models.ForeignKey(TargetShape, related_name='page_elements') page = models.ForeignKey(Page, related_name='page_elements') index = models.PositiveIntegerField(verbose_name='Order') class WorkingSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='working_sessions') I defined another model Resolution that enables me to link all of them together in order to create the following related_name relations: working_session.resolutions user.resolutions target_shape.resolutions page.resolutions page_element.resolutions To have it working, I had to declare: class Resolution(models.Model): # relations that would be needed from a DRY perspective: page_element = models.ForeignKey(PageElement, related_name='resolutions') working_session = models.ForeignKey(WorkingSession, related_name='resolutions') # relations I want to exist to use user.resolutions, target_shape.resolutions, page.resolutions: user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='resolutions') target_shape = models.ForeignKey(TargetShape, related_name='resolutions') page = models.ForeignKey(Page, related_name='resolutions') However, that's not very DRY. From a DRY perspective, I should be able to declare Resolution as linking to only PageElement and WorkingSession, and deduce / inherit the relation with the parent models: class Resolution(models.Model): page_element = models.ForeignKey(PageElement, related_name='resolutions') working_session = models.ForeignKey(WorkingSession, related_name='resolutions') But in that case, how can I create the following relations: user.resolutions target_shape.resolutions page.resolutions without going through: user.working_sessions.resolutions target_shape.page_elements.resolutions page.page_elements.resolutions -
ModelForm not saving data for user profile
I am having a bit of trouble with my Django forms. When I save my profile form, it's not updating the profile. When the user saves the form, I get the success message. I've tried a couple of solutions already offered here on stack overflow, but I couldn't get any of them to work. I'm sure it's something simple, but I can't figure it out. Any help is appreciated. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) subjectOfInterest = models.CharField(max_length=100) age = models.IntegerField() goal = models.TextField(max_length=500) forms.py class UpdateProfileForm(forms.ModelForm): class Meta: model = Profile labels = { "subjectOfInterest": "What subject interests you most?", "goal": "Whats the goal you want to achieve with Study Wise?", "age": "What is your age?", } fields = [ "subjectOfInterest", "goal", "age", ] views.py def profile(request): form_class = UpdateUserForm p_form_class = UpdateProfileForm if request.method == "POST": p_form = p_form_class(request.POST, instance=request.user) user_form = form_class(request.POST, instance=request.user) if user_form.is_valid() and p_form.is_valid(): user_form.save() p_form.save() messages.success(request, "Your profile has been updated") return redirect("profile") else: user_form = UpdateUserForm() p_form = UpdateProfileForm() profile_data = Profile.objects.all().filter(user=request.user) return render( request, "user/profile.html", {"user_form": user_form, "p_form": p_form, "profile_data": profile_data}, ) profile.html {%for profile in profile_data%} <h4>Interests: {{profile.subjectOfInterest}} </h4> <h4>Goal: {{profile.goal}}</h4> <h4>Age: {{profile.age}}</h4> {%empty%} empty {%endfor%} -
Custom button not performing action in Django admin
Am trying to add another custom button, and at the same time I want it to trigger certain processes in Django-admin with templates, below is how I have implemented the template : {% extends 'admin/custominlines/change_form.html' %} {% load i18n %} {% block submit_buttons_bottom %} {{ block.super }} {% if request.GET.edit %} <div class="submit-row"> <input type="submit" value="Custom button" name="_transition-states"> </div> {% endif %} {% endblock %} The button does appear however, when I click it , it doesn't show the print I have inserted in the response_change() function in the admin.py, what am I missing here : def response_change(self, request, obj): if '_transition-states' in request.POST: print("am working") return super().response_change(request, obj) When I click the button it just routes back to the previous page. -
SyntaxError : Invalid syntax jedi
There is a problem showing in my vs-code editor SyntaxError: Invalid syntax jedi I don't know why this problem showing it's bothering me so much and there are some weird symbols on my editor ←[0m ←[m you can see this image can anyone tell how to remove both of this from vs-code editor these will be really helpful. -
Load multiple comments for different events in Django view
In my recent project, I was trying to do a website to make people hold events, while others could comment the events. I want to show all the events hosted by the user in his/her profile page, I created EventsBoard model to store event details and Comment model to store all the comments. class Comment(models.Model): text = models.CharField(max_length=40) for_event = models.ForeignKey( EventsBoard, on_delete=models.CASCADE, related_name='comments' ) author = models.ForeignKey( "user_extend.UserExtend", on_delete = models.CASCADE, related_name='comment_author' ) rate = IntegerRangeField(min_value=1, max_value=10) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text and I have the view.py as follow. def profile_view(requests, id, *args, **kwargs): obj = UserExtend.objects.get(id=id) activities = EventsBoard.objects.filter(host=obj).filter(event_type='activity') projects = EventsBoard.objects.filter(host=obj).filter(event_type='project') personal_projs = EventsBoard.objects.filter(host=obj).filter(event_type='personal') context = { 'user': obj, 'activities': activities, 'projects': projects, 'personal_projs': personal_projs } return render(requests, 'profile.pug', context) But since one can host lots of events, I am wondering how could I load the comment model to the view.py to bind the event object with comment objects. -
Object of type LineString is not JSON serializable
How can I figure out this error when using folium.GeoJSON. gdf is a geodataframe. layer=folium.GeoJson( gdf, tooltip=folium.GeoJsonTooltip(fields=['oneway','lanes', 'length','speed','name'],localize=True), style_function=lambda x: { 'color': line_color }).add_to(m) m.fit_bounds(layer.get_bounds()) I also tried gdf.to_json() but it does not work -
In one project i seen serialize method outside model in models.py file
what is use of def serialize? Why outside of model method serialize present?. why on user once again serialize is used class Doctor(models.Model): """ This model stores the doctor profile. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_on = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=True) # Whether this doctor is accessible to users. qualification = models.TextField(null=True) specialization = models.ManyToManyField(DoctorSpecialization) def serialize(self): return { "id": self.id, "user": self.user.serialize(), "created_on": generate_readable_date_time(self.create_on), "active": self.active, "qualification": self.qualification, "specializations": [s.serialize() for s in self.specialization.all()] } -
how to save django foreignkey with get_or_create
i'm trying to add the vendor profile when user hit add_to_cart url everything works file without saving vendor profile, it was single vendor model, i wanted to make it multiple vendor model so the way can track the vendor data. thank you so much, appreciate your help model.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) vendor = models.ForeignKey(Vendor, related_name='items', on_delete=models.CASCADE) **save this vendor profile when user hit add_to_cart** # vendor_paid = models.BooleanField(default=False) quantity = models.IntegerField(default=1) # price = models.DecimalField(max_digits=8, decimal_places=2) wishlist = models.ManyToManyField(Wishlist, blank=True) views.py @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) vendor = Vendor.object. # this where the problem is order_item, created = OrderItem.objects.get_or_create( item=item, vendor=vendor, # how to save the vendor profile user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("product:product_detail_view", slug=item.slug) else: order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("product:product_detail_view", slug=item.slug) else: ordered_date = timezone.now() order = Order.objects.create(user=request.user, ordered_date=ordered_date) order.items.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("product:product_detail_view", slug=item.slug) -
Django models how to fix circular import error?
I read about solution for the error (write import instead of from ...) but it doesn't work I think because I have a complex folder structure. The folder structure quiz/models.py import apps.courses.models as courses_models class Quiz(models.Model): lesson = models.ForeignKey(courses_models.Lesson, on_delete=models.DO_NOTHING) # COURSE APP MODEL IMPORTED courses/models.py import apps.quiz.models as quiz_models class Lesson(models.Model): ... class UserCompletedMaterial(models.Model): ... lesson = models.ForeignKey(lesson) quiz = models.ForeignKey(quiz) # QUIZ APP MODEL IMPORTED How you can see I just can't keep it together or something else.. Because I think the UserCompletedMaterial model is a part of courses app -
How can I upload multiple files in to a Django model?
I'm trying to make an LMS system with Django and now I need to upload multiple pdf files to the curriculum of the class. I can upload one file with the OnetoOne field in the Django model but not more. When I try to add another material for the same class it says Upload materials with this Uploaded class already exists. This is my model code. class UploadMaterials(models.Model): name = models.CharField(max_length=255) uploaded_class = models.OneToOneField(Class, on_delete=models.CASCADE, related_name='upload_materials') upload_material = models.FileField(upload_to=rename, null=True) class Meta: verbose_name_plural = "Materials" I need to upload the materials and be able to view them in the template. like...... {% for material in class.materials %} <h1>{{ material.name }}</h1> {% endfor %} I tried the Django ForeignKey instead of OnetoOne and was able to create multiple materials for the same class but could not figure out how to access them from the template. What I want to know is how to upload multiple files to the same class and how to access them in the template. Thank you! -
Why am I getting "page not found" error in Django?
I am new in Django Framework having no previous experience with any other framework. After writing these code and hitting the url http://127.0.0.1:8000/MyApp/f2/400 I get the error "Page not found " This is the code of my Project's main urls.py file : from django.contrib import admin from django.urls import path from django.conf.urls import include,url urlpatterns = [ path('admin/', admin.site.urls), path('MyApp', include('MyApp.urls')), ] This is the code of my MyApp.urls file : from django.urls import path from django.conf.urls import include,url from MyApp import views urlpatterns = [ url('test', views.Index, name='Index'), url('f2/<int:guess>', views.F.as_view()), ] I have attached the image of erroneous page. -
Problem with timezone in Django ORM, datetime value differs from the value stored in the table
I have stored some data into PostgreSQL database. Here is the corresponding Django model: from django.contrib.gis.db import models class PrecipitationContourDjango10d(models.Model): value = models.FloatField(blank=True, null=True) geometry = models.PolygonField(blank=True, null=True) date = models.DateTimeField(blank=True, null=True) window_no = models.CharField(max_length=10, blank=True, null=True) color = models.CharField(max_length=20, blank=True, null=True) def __lt__(self, other): if self.date < other.date: return True return False class Meta: db_table = 'precipitation_contour_web_service10d' Here is some rows that are stored in the table: As you can see the datetime value for the row with id=5921 is 2021-05-07 21:00:00-07. However when I retrieve that row using the Django ORM, its datetime field will change: from data.models import PrecipitationContourDjango10d row = PrecipitationContourDjango10d.objects.get(id=5921) How can I solve this issue? Thanks. -
Forms are not getting displayed on django
models.py from django.db import models Create your models here. class dhiraj(models.Model): title=models.CharField(max_length=200, default="" ) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now=True) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from . models import dhiraj class dhirajForm(forms.ModelForm): class meta: model=dhiraj fiels='__all__' index.html <h1>this is</h1> <form> {{form}} </form> {% for taskk in dhiraj %} <div> <p>{{taskk}}</p> </div> {% endfor %} the coming error is Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Dhiraj Subedi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site- packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dhiraj Subedi\dhiraj\virenv\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return … -
Implementing notifications in django with MySQL
I am developing a web app using django.I need to check database continuously and if the database(mySQL) value is less than X, the user should get notification.what should I do? I have read about celery,dramatiq, django channels and many more but still confused how to implement them. Can anyone help me with this -
HTML code from one to another file is not extending in Django project
I am getting this issue from start of my project. I spent a day to solve but nothing happened. Code from base.html is showing on the page but the code from shop.html is not. base.html shop.html -
Passing a variable from javascript to Django view
I want to send a variable I got from a javascript function to my Django view. The function is as below: <script> function googleSignin() { firebase.auth().signInWithPopup(provider).then(function(result) { var token = result.credential.accessToken; var user = result.user; console.log(token) console.log(user) var uid = user.uid; return uid; }).catch(function(error) { var errorCode = error.code; var errorMessage = error.message; console.log(error.code) console.log(error.message) }); } </script> I used a onclick tag to call this function and the values properly show up in the console. I just need to send the value returned to my views somehow. I've tried using ajax to call on the view but I can't figure out how to make it work. The ajax code is below: $.ajax({ // points to the url where your data will be posted url: /gsignin/, // post for security reason type: "POST", // data that you will like to return data: {uid : uid}, // what to do when the call is success success:function(response){ console.log(sid); }, // what to do when the call is complete ( you can right your clean from code here) complete:function(){ window.location.href = "/gsignin/" }, // what to do when there is an error error:function (xhr, textStatus, thrownError){} }); I'm really new to this stuff … -
how to show all orders amount respective to every user in a table without duplicating a username twice
i have this order model: class Order(models.Model): productType = [ ('Document', 'Document'), ('Parcel', 'Parcel'), ('Box', 'Box') ] serviceType = [ ('Home', 'Home delivery'), ('Office', 'Office delivery'), ('Pick up from office', 'Pick up from office'), ] delivery_StatusType = [ ('Return', 'Return'), ('Delivering', 'Delivering'), ('Pending', 'Pending'), ('Complete', 'Complete') ] statustype = [ ('Paid', 'Paid'), ('Cash on delivery', 'Cash on delivery') ] status = [ ('Instant', 'Instant'), ('Same Day', 'Same Day'), ('Others', 'Others') ] payment_types = [ ('Cash', 'Cash'), ('Wallet', 'Wallet'), ('Online', 'Online') ] CHOICE_AREA = [ ('Inside Dhaka', 'Inside Dhaka'), ('Dhaka Suburb', 'Dhaka Suburb'), ('Outside Dhaka', 'Outside Dhaka') ] user = models.ForeignKey(User, on_delete=models.CASCADE) receiver = models.CharField(max_length=100, blank=False, unique=False) receiver_Contact = models.CharField( max_length=20, blank=False, unique=False) receiver_Email = models.CharField( max_length=100, blank=False, unique=False) payment = models.CharField( max_length=100, choices=payment_types, blank=False) area = models.CharField( max_length=100, choices=CHOICE_AREA, blank=True, null=True) weight = models.CharField(max_length=100, blank=True, null=True) service = models.CharField(choices=serviceType, max_length=100) product_Type = models.CharField(choices=productType, max_length=100) contents = models.CharField(max_length=100, blank=False, unique=False) quantity = models.CharField(max_length=100, blank=False, unique=False) package = models.ForeignKey( Package, on_delete=models.CASCADE, default=0) priority = models.CharField( choices=status, blank=True, null=True, max_length=20) amount = models.CharField(max_length=100, blank=True, unique=False) delivery_Status = models.CharField( choices=delivery_StatusType, blank=True, null=True, max_length=50) paid = models.BooleanField(default=False) reference_id = models.CharField(max_length=100, blank=True, unique=True) delivery_time = models.DateField(blank=True, null=True) created = models.DateField(auto_now_add=True) tran_id = models.CharField(max_length=20, blank=True, null=True) driver … -
How to achieve Waiting Room to match people 1-on-1 with Django Channels?
I could not find any starter basic solution for this problem. My thought process right now that when users join to the queue they will be added temporarily to a WaitingRoom model. Then there is a 10 seconds delay for waiting, the next step that they will be randomly match with each other. My problem with this that it won't prevent that multiple users would be matched up with each other. This is my current messy solution. It sends out to everyone in the queue and checks on the frontend if the current user is actually in the pair. class WaitingRoomConsumer(AsyncConsumer): @database_sync_to_async def get_waiting_room(self, user): room = WaitingRoom.objects.all().exclude(user=user) serializer = WaitingRoomSerializer(room, many=True) return serializer.data @database_sync_to_async def add_to_waiting_room(self, user): if (WaitingRoom.objects.filter(user=user).count() == 0): return WaitingRoom.objects.create(user=user) @database_sync_to_async def get_user_id(self, username): return User.objects.get(username=username).id @database_sync_to_async def remove_from_waiting_room(self, user): room = WaitingRoom.objects.get(user=user) return room.delete() async def websocket_connect(self, event): current_user = self.scope['user'] self.room_obj = await self.add_to_waiting_room(current_user) self.room_name = "WAITING_ROOM" #f'waiting_room{self.room_obj.id}' await self.channel_layer.group_add(self.room_name, self.channel_name) await self.send({ 'type': 'websocket.accept' }) msg = json.dumps({ 'type': 'joined', 'username': current_user.username, }) await self.channel_layer.group_send( self.room_name, { 'type': 'websocket.message', 'text': msg } ) print(f'[{self.channel_name}] - You are connected.') await self.recommend_candidate() async def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message. - {event["text"]}') msg = event.get('text') … -
Anyone knows how to properly create subscriptions (real time api )in django graphene?
I am using Django graphene and I successfully created queries and mutations, but when it comes to the subscription I find out the graphene doesn't sopported officially but it suggesting few libraries with very vague documentations and not working examples at all. However, I created a web socket chat app before but when it came to subscription it never works with me. any ideas any working exampes please? -
How to test a django rest url with query parameter?
My URL has 'nutritionist' query parameter, in this case, it will get profiles that has nutritionist with id=1 /profiles?nutritionist=1 When I tried to test this 'filtering' like this: def test_get_user_belonging_to_a_nutritionist(self): response = self.client.get("/profiles?nutritionist=1/",secure=True) users = CustomUser.objects.filter(nutritionist=1) serializer = CustomUserDetailsSerializer(users, many=True) self.assertEqual(response.data, serializer.data) The response contains HttpResponsePermanentRedirect object, instead of the normal response This is my Views.py if it helps class GetProfilesViewSet(generics.ListAPIView): serializer_class = CustomUserDetailsSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = CustomUser.objects.all() nutritionist_id = self.request.query_params.get('nutritionist') if nutritionist_id is not None: queryset = queryset.filter(nutritionist=nutritionist_id) return queryset How can I test this case? -
Adding your own link to the header of the django admin panel
I need to add a link to my page in the admin panel of the django framework How can this be done? Perhaps you can somehow add it here -
Change site address http://127.0.0.1:8000/ to something like http://www.rajSite.com in Django
I have tried python manage.py runserver www.rajSites.com but didnt work I searched in google for more than 1 hr. No info is available. I am using the development server that comes with Django. How to change https://127.0.0.1 to https://rajSites.com(Own Url).. Please Share your Ideas regarding this... Advance Thanks for helping... -
In Django there is some thing wrong with my code I cant retrieve the fields of value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} see the html
This is my edit.html code and during retrieving the values from database it shows only the text fields like value={{ i.full_name}} but when I am writing value={{ i.cv}}, value={{ i.status}}, value={{ i.gender}} it does not shows the value which needs to bed edited I have two choice fields and one file field. this is my edit.html <section class="site-section"> <div class="container"> <div class="row"> <div class="col-lg-12 mb-5"> <h2 class="mb-4 text-center">Update Candidate Details</h2> <form method="POST" action="/update/ {{i.id}}/" enctype="multipart/form-data" class="p-4 border rounded" onsubmit="myFunction()" > {% csrf_token %} {% comment %} <input type="hidden" name="csrfmiddlewaretoken" value="UabxqpD8HGPOu1ZSFnIHAPbMtRgWBAnVHEs8bLDx0HnxN6uhG3LyYvZShvcx1ekn"> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="full_name">Full Name :</label> <input type="text" class="form-control" value ={{ i.full_name}} name="full_name" id="id_full_name" placeholder="Enter First Name"> </div> </div> <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="recruiter_name">Recruiter Name :</label> <input type="text" class="form-control" value ={{ i.recruiter_name }} name="recruiter_name" id="id_recruiter_name" placeholder="Enter Recruiter Name"> </div> </div> {% comment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="id_last_name">Last Name :</label> <input type="text" class="form-control" name="last_name" id="id_last_name" placeholder="Enter Last Name"> </div> </div> {% endcomment %} <div class="row form-group"> <div class="col-md-12 mb-3 mb-md-0"> <label class="text-black" for="email">Email :</label> <input type="email" class="form-control" value ={{i.email }} name="email" id="id_email" placeholder="Enter Email"> </div> </div> <div class="row form-group"> <div class="col-md-12 … -
Add new parameters at Django rest framework pagination
I want to add 'isSuccess' at the pagination returns. For example, { "count": 1234, "next": "http://mydomain/?page=2", "previous": null, "isSuccess" : 'Success' # <---- this one "results": [ { 'id':123, 'name':'abc' }, { 'id':234, 'name':'efg' }, ... ] } I found this way but It didn't work. How can I add new parameters at Django pagination return? this is my try: class Testing(generics.GenericAPIView): queryset = Problem.objects.all() serializer_class = userSerializer pagination_class = userPagination def get(self, request): queryset = self.get_queryset() page = self.request.query_params.get('page') if page is not None: paginate_queryset = self.paginate_queryset(queryset) serializer = self.serializer_class(paginate_queryset, many=True) tmp = serializer.data tmp['isSuccess'] = 'Success' return self.get_paginated_response(tmp)