Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django render Dictionary
Why cant i acsess the dict that i am making here: def kalkuler(request): fotlister = Produkt.objects.filter(under_kategori__navn__iexact="lister") kalkuler = ProduktKalkureing.objects.all() beregning = {} if request.method == "POST": omkrets = request.POST['omkrets'] print(omkrets) for i in kalkuler: kalk = math.ceil((int(omkrets)/i.lengde)*1000) add = ({'produkt_tittel': i.produkt.produkt_tittel, 'produkt_bilde': i.produkt.produkt_bilde, 'produkt_info': i.produkt.produkt_info, 'produkt_link': i.produkt.produkt_link, 'pris_heltall': i.produkt.pris_heltall, 'antall_kalk': kalk, 'total_kost': kalk * i.produkt.pris_heltall }) beregning.update(add) print(beregning) context = {'kalkuler': kalkuler, 'beregning': beregning} return render(request, 'frontend/kalkuler/fotlist_kalkuler.html', context) With the standard django code? {% for b in beregning %} {{b.produkt_bilde}} {% endfor %} Also when i make the dictionary it only adds the last value. How do i make it so it adds every value. -
Django graphene GraphQL mutation to create foreign key with get_or_create
Is it possible to write a Graphql mutation with get_or_create I have models: class Person(models.Model): name = models.CharField() address = models.CharField() class Blog(models.Model): person = models.ForeignKey('Person', on_delete=models.CASCADE, blank=False, null=False) text = models.TextField() name = models.CharField() and for schema.py class PersonType(DjangoObjectType): class Meta: model = Person class BlogType(DjangoObjectType): class Meta: model = Blog I want to create a mutation for Blog where I create Person if it is missing: class CreateBlog(graphene.Mutation): blog = graphene.Field(BlogType) class Arguments: person=graphene.String() name = graphene.String(required=True) text = graphene.String() @staticmethod def mutate(root, info, **input): person = Person.objects.get(name=person) blog = Blog.objects.get(person=person, name=name,text=text) blog.save() return CreateBlog(blog=blog) Mutation query: mutation{ CreateBlog(name:"Harry Potter", person:"JK Rowing", text:"HI HI HI"){ blog{ name text person{ name } } } } Is it possible to use get_or_create to create the foreign key person if unavailable and get the id if it is with a single query? I tried the following but got "local variable 'doc' referenced before assignment" class CreateBlog(graphene.Mutation): blog = graphene.Field(BlogType) class Arguments: person=graphene.String() address =graphene.String() name = graphene.String(required=True) text = graphene.String() @staticmethod def mutate(root, info, **input): person, _ = Person.objects.get_or_create(name=person, address = address) blog, _ = Blog.objects.get_or_create(person=person, name=name,text=text) blog.save() return CreateBlog(blog=blog) Query: mutation{ CreateBlog(name:"Harry Potter", person:"JK Rowing", address: "address", text:"HI HI HI"){ … -
How redirect to alogin page in html Django if user is not authinticated
How to in HtMl to redirect user if it is noit registered using this template. I want to redirect if not registered to Login page {% if user.is_authenticated %} <p>Authenticated user</p> {% else %} redirect to 'login' page {% endif %} I have in settings.py LOGOUT_REDIRECT_URL = 'login' -
Install django-simple-captcha have some error
Install Django-simple-captcha via pip: pip install Django-simple-captcha - success Add captcha to the INSTALLED_APPS in your settings.py - Done! Run python manage.py migrate - have some problem File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\thoma\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'captchausers' Who can tell me what can I do? -
In Django for loop in html template is not working correctly
i want the report name in the dropdown menu but i'm not able to fetch the items for dictionary views.py def add(request): report_item = {} if request.method == "POST": src=request.POST['src'] width=request.POST['width'] height=request.POST['height'] name=request.POST['name'] report_item = {'src':src, 'width':width, 'height':height, 'name':name} #template = loader.get_template('report_one.html') #context={'report_item':report_item} return render(request, 'report_one.html', report_item) else: return render(request, 'report_one.html', report_item) index.html {% for key, value in report_item.items %} <li> <a href="{% url 'report:add' %}">{{ value.name }}</a> </li> {% endfor %} -
How to iterate on Django prefetch related queries?
So I have written a query which is : queryset = Professional.objects.filter( slug=slug ).prefetch_related( Prefetch('educations', queryset=ProfessionalEducation.objects.filter(is_archived=False).order_by('-enrolled_date')), Prefetch('skills', queryset=ProfessionalSkill.objects.filter(is_archived=False).order_by('skill_name')), Prefetch('work_experiences', queryset=WorkExperience.objects.filter(is_archived=False).order_by('-start_date')), Prefetch('portfolios', queryset=Portfolio.objects.filter(is_archived=False).order_by('created_at')), Prefetch('memberships', queryset=Membership.objects.filter(is_archived=False).order_by('created_at')), Prefetch('certifications', queryset=Certification.objects.filter(is_archived=False).order_by('-issue_date')), Prefetch('references', queryset=Reference.objects.filter(is_archived=False).order_by('created_at')) ) I can iterate on this queryset like: for obj in queryset: print(obj.full_name) print(obj.email) etc. But How can I able to get the value of like prefetch educations value or skills value? I am tried many way but couldn't succeed. -
Django Rest framework request.data is not working
I have gone through several solutions on stackoverflow but couldn't solve this that's why asking this type of question again: My code : @api_view(['POST']) def RegisterUserAPI(request): print("\n\n=================== 1 =====================") print("Request : ",request) print("DATA : ",request.data) print("================ 2 ========================= .... .... I was trying to debug but request.data is the reason for the error, I want take some values from request and want to perform some other tasks that's why trying to see request.data Error: =================== 1 ===================== Request : <rest_framework.request.Request object at 0x000001F800E3C978> Internal Server Error: /api/register/ Traceback (most recent call last): File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\base.py", line 158, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\LocalProject\myvenv\lib\site-packages\django\core\handlers\base.py", line 156, in _get_response response = response.render() File "D:\LocalProject\myvenv\lib\site-packages\django\template\response.py", line 106, in render self.content = self.rendered_content File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 724, in render context = self.get_context(data, accepted_media_type, renderer_context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 680, in get_context 'content': self.get_content(renderer, data, accepted_media_type, renderer_context), File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 413, in get_content content = renderer.render(data, accepted_media_type, renderer_context) File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\renderers.py", line 103, in render allow_nan=not self.strict, separators=separators File "D:\LocalProject\myvenv\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\91762\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\91762\AppData\Local\Programs\Python\Python36\lib\json\encoder.py", … -
Django admin not loading individual app pages
I've just set up a new local version of my django application, and all working fine until I checked on the django admin. 127.0.0.1:8000/admin works fine and brings up the usual Django Admin homepage with full list of apps, but when I click into any of the individual app elements it breaks. The URL changes, but instead of displaying that app's admin site it shows an oddly rendered version of the admin homepage, with the app list collapsed on left side of screen (see screenshots below) Can't immediately see which parts of codebase could be relevant here, so please request copies of any code you want to see. The correctly displayed Django Admin homepage How it renders when I click into any of the individual app/model admin sites As above, with list of all apps expanded from left -
Django custom added permissions is not working - Django
I have implemented some custom permissions for my model. Custom added permissions are reflecting on Admin panel and im able to assign the same to Group/User. But when im trying to use those permissions in template then its not working. Please find the below codes and help. Thanks in advance. Model : class Painter(models.Model): user = models.OneToOneField('main.CustomUser', on_delete=models.CASCADE, related_name='+') code = models.CharField(max_length=100, unique=True) painter_or_not = models.CharField(choices=(('Yes', 'Yes'), ('No', 'No')), null=True, max_length=20) tse_verified = models.CharField(choices=(('Yes', 'Yes'), ('No', 'No')), max_length=20) registration_via = models.CharField(choices=(('App', 'App'), ('Admin', 'Admin'), ('Offline', 'Offline')), max_length=20) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile = models.CharField(max_length=10, unique=True) dob = models.DateField(null=True) address = models.CharField(max_length=300) state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) pincode = models.CharField(max_length=6) dealer = models.ForeignKey(Dealer, on_delete=models.SET_NULL, null=True) balance = models.FloatField(default=0) bank_ac = models.CharField(max_length=50, null=True) ifsc = models.CharField(max_length=11, null=True) bank_name = models.CharField(max_length=100, null=True) aadhar = models.CharField(max_length=20, null=True) aadhar_front = models.ImageField(upload_to='media/addhar', null=True, blank=True, default=None) aadhar_back = models.ImageField(upload_to='media/addhar', null=True, blank=True, default=None) tse = models.ForeignKey(TSE, on_delete=models.SET_NULL, null=True) date_created = models.DateField(auto_now=True, null=True) profile_image = models.ImageField(upload_to='profile_pic', default='user.png') class Meta: permissions = ( ('edit painter', 'Can edit painter'), ('upload painter', 'Can upload painter'), ('download painter', 'Can download painter'), ) Template: {% if perms.users.upload_painter %} <li><a href="{% url 'upload_painter' %}" style="margin-right: 5px;" class="pull-right btn … -
Django referencing object ID before object creation
I have a question about object creation in django. I have a generator, for simplicity's sake say it is a list, of strings: ['a','b','c'...'n'] Additionally I have a model class which shall reference its id against this list. i.e. model.id = 1 | list[1] = 'b' But my problem is, self.id is only created after saving the object, not upon calling the init method. So overwriting the classes' __init__(self) method and calling self.list_ref = self.id does not work, because model is not yet saved. Also creating a method which may be called afterwards and returns the referenced list entry afterwards does not work properly. def get_list_ref(self): list_ref = list[self.id] self.save() # does nothing, should enter list_ref=list[self.id] into db return list_ref # returns correct referenced list entry So my question is: How do I go about this? I thought of adding a method which overwrites the save method. Is this good practice? Because I always add info to the model which needs not to be updated with every query. A global variable as a counter of the created models (which counts parallel to the db entries) could be another option. I see some possible shortcomings with this, such as keeping objects … -
How to patch value of instance?
I have web-application. On Frontend I do patch request to Backend to update value. On Backend I have class in views that manages user. views.py class ManageUserView(generics.RetrieveUpdateAPIView, mixins.CreateModelMixin): """Manage the authenticated user""" serializer_class = UserSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get_object(self): """Retrieve and return authenticated user""" return self.request.user def perform_create(self, serializer): """Create a new company""" serializer.save(company=self.request.company) The error is in perform_create function. How can I modify it? Or should I use CreateApiView class? class CreateApiView(generics.CreateAPIView): """Create a new user in the system""" serializer_class = UserSerializer On Frontend I do patch to '/me/' url. urls.py from django.urls import path from user import views app_name = 'user' urlpatterns = [ path('create/', views.CreateApiView.as_view(), name='create',), path('token/', views.CreateTokenView.as_view(), name='token'), path('me/', views.ManageUserView.as_view(), name='me'), path('logout/', views.LogoutView.as_view(), name='logout'), ] Server response 400 Bad Request with message - company: ["Incorrect type. Expected pk value, received str."]. And my serializers.py file, but I think you do not have to need this code to help me :) class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" class Meta: model = get_user_model() fields = ('id', 'email', 'name', 'surname', 'company') extra_kwargs = {'password': {'write_only': True, 'min_length': 5}} def create(self, validated_data): """Create a new user with encrypted password and return it""" return get_user_model().objects.create_user(**validated_data) def … -
Django User Model Inheritance not working
In my Django app, i have two models Retailer and Customer. The model fields for both are different but for authentication the common fields are email and password. So for that I used User Model Inheritance. This is my code looks like Reason for Inheritance : I want to implement Token Authentication models.py class User(AbstractUser): email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Retailer(User, PermissionsMixin): name = models.CharField(max_length=255) phoneNUMBER = models.CharField(max_length=10) verificationSTATUS = models.BooleanField(default=False) dateJOINED = models.DateField(default=timezone.now) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'phoneNUMBER',] objects = RetailerManager() def __str__(self): return self.name class Customer(User, PermissionsMixin): name=models.CharField( max_length=255, null=False,) phone_Number=models.CharField( max_length=10, null=False) address=models.TextField(max_length=255,null=False) pin_Code=models.CharField( max_length=6,null=False ) anniversary_Date=models.DateField(blank=True,null=True) hobbies=models.TextField(blank=True,null=True) profession=models.CharField(blank=True,max_length=20,null=True,) created_At=models.DateField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name', 'phoneNUMBER', 'address', 'pin_Code'] objects = CustomerManager() def __str__(self): return (self.name) managers.py class UserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() … -
Errors with Django LoginView
I'm fairly new to coding & Django. I'm following a tutorial that uses an older version of Django. In the tutorial there is the following code in the views.py from django.contrib.auth import views as auth_views def login(request, **kwargs): if request.user.is_authenticated: return redirect('/cadmin/') else: return auth_views.login(request, **kwargs) I have tried replacing the auth_views.login(request, **kwargs) with auth_views.LoginView(request, **kwargs) and also auth_views.LoginView.as_views(request, **kwargs) but both of theses give me errors. Please can anyone tell me what I should be putting. Thankyou -
SERVER 500 error in my django app through heroku
Showing SERVER ERROR 500 When my django app is deployed through heroku and when i try to enter details through post method into postgresql database `def register(request): ' if (request.method=="GET"): return render(request,'register.html',{'curl':curl,'output':''}) else: name=request.POST.get('name') email=request.POST.get('email') password=request.POST.get('password') address=request.POST.get('address') mobile=request.POST.get('mobile') city=request.POST.get('city') gender=request.POST.get('gender') dt=time.asctime(time.localtime(time.time())) query="insert into(name,email,password,address,mobile,city,gender,role,status,dt) register values('%s','%s','%s','%s','%s','%s','%s','user',0,'%s')" %(name,email,password,address,mobile,city,gender,dt) models.cursor.execute(query) models.db.commit() import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText me = "hellomatcraft@gmail.com" you = email msg = MIMEMultipart('alternative') msg['Subject'] = "Verification Mail MatCraft" msg['From'] = me msg['To'] = you html = """ Welcome to MatCraft You have successfully registered , please click on the link below to verify your account Username : """+email+""" Password : """+str(password)+""" Click here to verify account """ s = smtplib.SMTP('smtp.gmail.com', 587) s.starttls() #login() part2 = MIMEText(html, 'html') msg.attach(part2) s.sendmail(me,you, str(msg)) s.quit() print("mail send successfully....") return render(request,'register.html',{'curl':curl,'output':'Verification Mail Successfully Send....'})' 2020-08-24T10:44:19.917608+00:00 heroku[router]: at=info method=POST path="/register/" host=matcraft.herokuapp.com request_id=9255fbcd-a4dd-4be2-a059-5473259002ca fwd="157.34.125.241" dyno=web.1 connect=2ms service=58ms status=500 bytes=473 protocol=https THIS IS ERROR ` -
How to save name of superuser as an author of a post?
I have two fields i.e 'title' and ' content' which come from the form. When a form is submitted, I want these two fields stored in the database along with the name of superuser as author. -
How to store automatically csv file to oracle database in django without model?
I want to store data in csv files in an oracle database without going through the model or defining the fields to store because the fields vary from one csv to another any help please ?? -
Is there a way to debug Django urls?
I have a problem with Django urls that I cannot get to the bottom of. I have tried the recommendations given in the answers to this question, but they don't help. <project>/urls.py urlpatterns = [ ... path('duo/', include('duo.urls')), path('users/', include('users.urls')), ] duo/urls.py urlpatterns = [ ... path('', include('users.urls')), ... ] users/urls.py urlpatterns = [ path('', views.SelectPartner.as_view(), name='select-partner'), ... ] when I use the url http://192.168.1.138:8000/duo/ I get taken to the page http://192.168.1.138:8000/accounts/login/?next=/duo/ which does not exist. I cannot think what is going on here because the word accounts does not exist anywhere in the project Is there some tool that I can use to find out what is happening? -
py command not working but python command is working in cmd
I have python version 3.8.0 and the .exe is added to the path but I am trying to create a django project and need to use py -m venv command to create a virtual environment but it says py is not recognized as an internal or external command, operable program or batch file. -
Deployed Django App Not Working On Ubuntu NGinx/Gunicorn
When following this tutorial (https://rahmonov.me/posts/run-a-django-app-with-gunicorn-in-ubuntu-16-04/), everything worked for a basic website. This at least proves the firewall rules are working as expected. However, when deploying my Django web app, I'm simply receiving the message: "This site can't be reached." I've checked the Nginx error and access logs, and they don't contain anything since the 13th August when I last looked into this issue, and when the website repeatedly gave me errors about missing modules that have since been installed. Is there anywhere else I can check to see why the Django app now isn't loading via the web page? Just for peace of mind, below are all my config details. /etc/nginx/sites-available/terraformdeploy: server { listen 8000; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /opt/envs/terraformdeploy; } location / { include proxy_params; proxy_pass http://unix:/opt/envs/terraformdeploy/terraformdeploy.sock; } } I've run: sudo ln -s /etc/nginx/sites-available/terraformdeploy /etc/nginx/sites-enabled sudo nginx -t returns: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful service nginx status returns: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Drop-In: /etc/systemd/system/nginx.service.d └─override.conf Active: active (running) since Thu 2020-08-13 15:44:44 … -
How to remove pre-populated extra forms from django admin inlines
for example, suppose I have these two models: class Comment(models.Model): content = models.TextField() post = models.ForeignKey('Post', on_delete=models.CASCADE) class Post(models.Model): content = models.TextField() and I have set Comment as Inline for Post admin, like: class CommentInline(admin.StackedInline): model = Comment extra = 3 @admin.register(Post) class PostAdmin(admin.ModelAdmin): inlines = [CommentInline] Now, I want to set initial values into the extra 3 forms of comment inlines. and I have accomplished that by CommentInline's get_formset method like: def get_formset(self, request, obj=None, **kwargs): # this list will be generated dynamically initial = [ {"content": "dynamic data 1"}, {"content": "dynamic data 2"}, {"content": "dynamic data 3"} ] formset = super().get_formset(request, obj, **kwargs) formset.__init__ = curry(formset.__init__, initial=initial) # from django.utils.functional import curry return formset now inline forms are populating by dynamic data as expected. but the problem is there are no buttons for removing the form. I can add new comments, edit initial comment, but I can't delete any comment from those pre-populated comments! my questions are: How can I remove extra inline form before saving into DB? Is my approach is ok for populating initial values? -
How do I create a Blog mdel in django2.1, So that I don't need to use tags <p>,<h3>,<b> and all, Each time write blog I have to add html tags
I have to add html tags each time when I added the blog to my website. I don't then it do not consider line change,heading and other things. Model code class Blog(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog') updated_on = models.DateTimeField(auto_now= True) body = models.CharField(max_length=150) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) def __str__(self): return self.title Admin Panel Html tag includedadmin view Published blogPublished blog Without use of html tagsadmin panel. Published blog blog published Plz let me know I it don't make sense. -
How to update your django page by looking for new data in the db?
I try to create a dashboard using django and chart.js. My modul looks like: class Sets(models.Model): time = models.DateTimeField(default=timezone.now) set1 = models.IntegerField() set2 = models.IntegerField() set3 = models.IntegerField() my views: from .function_sum import get_sets from .models import Sets def home(request, *args, **kwargs): sets = Sets.objects.all() time = [] set1 = [] set2 = [] set3 = [] time, set1, set2, set3= get_sets() data = { "sets" : sets, "time": time, "set1": set1, "set2": set2, "set3": set3 } return render(request, "pages/home.html", data) class ChartData(APIView): authentication_classes = [] permission_classes = [] sets = Sets.objects.all() time = [] set1 = [] set2 = [] set3 = [] time, set1 , set2 , set3 = get_sets() def get(self, request, format=None): data = { "time": self.time, "set1": self.set1, "set2": self.set2, "set3": self.set3 } return Response(data) get_sets is getting the current data from my Set datatable. my html file which is included in layout page: <div class="col-xl-6" url-endpoint='{% url "chart-data" %}'> <div class="card mb-5"> <div class="card-header"><i class="fas fa-chart-line mr-1"></i>Chart</div> <div class="card-body"><canvas id="SetChart" width="100%" height="40"></canvas></div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script> <script> var endpoint ='chart/data' var labels = [] var set1 = [] var set2 = [] var set3 = [] $.ajax({ … -
Django admin opening directly
I'm facing an issue when i'm hitting http://127.0.0.1:8000/admin/ it's not asking for login, admin page gets open directly. I've only one user i.e "root", i restarted my browser, cache/cookies clean, system restart but noting working out. I want whenever i hit http://127.0.0.1:8000/admin/ for first time in fresh browser session it should ask for login. Any idea why this is happening? -
How to fetch particular column from database using ajax in django
Here is my views.py def contact(request): number= listing_model.objects.only('phone') data=serializers.serialize('json', number) return JsonResponse( data, safe=False ) I am getting output "[{"model": "listings.listing_model", "pk": 2, "fields": {"title": "PG1", "address": "XYZ", "city": "Hyderabad", "state": "Telangana", "price": 4000, "pincode": 789654, "sqfoot": 300, "rooms": 3, "image": "images/th_SHFuSrw.jpg", "phone": 456789123}}, {"model": "listings.listing_model", "pk": 3, "fields": {"title": "PG2", "address": "DEF", "city": "TVM", "state": "KERELA", "price": 6000, "pincode": 456963, "sqfoot": 300, "rooms": 1, "image": "images/th.jpg", "phone": 123456789}}]" I don't want all these fields I just want to display phone field. Please help me. Thanks in advance. -
How to validate data with custom key fields with a serializer in django?
The format of the data looks somthing like this { "data": { "example1": { "priority": 10 }, "example2": { "priority": 10 } } } Here example1 and example 2 are the variable key names and the number of such keys and their names changes with depending on the request. Thanks in advance.