Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a Django model for a chatroom in python?
Just letting you all know that I am very inexperienced with web development and so I decided to start a project in which I am making an application similar to Discord in which people can go to chat rooms and voice chat each other. From research, I decided to use Django (now with sockets). I started my project making the models first since that is the easiest for me to understand now. I was easily able to create a User Profile like so: from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver import django class UserProfile(models.Model): user_name = models.OneToOneField(User, related_name='user profile', on_delete=models.CASCADE) photo = models.ImageField(null=True, blank=True, default='random_14-512.webp') status = models.CharField(default='This is my status', max_length=255) is_online = models.BooleanField(default=False) objects = models.Manager() @receiver(post_save, sender=User) def create_user_profile(self, sender, instance, created, *args, **kwargs): if (created): UserProfile.objects.create(user_id=instance.pk) class ChatRoom(models.Model): pass but I have no idea how I can create a model for the chatroom. I can give it a name easily and such, but if I use models.CharField, the first parameter is the user. If anyone can point me in the right direction on how I can create the model for the chat room, that would be much … -
Im having trouble with the variable of a for loop in javascript in a django template
what i am trying to do is make an animation by looping throught some images in my static file folder with javascript in django. but something keeps screwing their adress up my code looks something like this {% load static %} <img id="image_1" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/62/Solid_red.svg/512px-Solid_red.svg.png?20150316143248"> <button onclick="animation()">Click me</button> <script> function animation(){ for(var i=0; i < 10; i++){ changeImg(i); } } function changeImg(number){ let text = number.toString(); document.getElementById("image_1").src = "{static 'img" + text + ".png' %}"; } </script> if the images in static look like this: img1.png img2.png img3.png and so forth... and the adress of the image was this afterward img%22%20%2B%20text%20%2B%20%22.png -
React-redux cannot get user information for the profile
I am working on an e-commerce project(react, django) and register/login system is working well, but I when I started to work on update profile form, first I decided to get some info of the user. I am getting Authentication credentials were not provided error message. In console i am getting a 401 Unauthorized error: "GET /api/users/profile/ HTTP/1.1" 401 58. userReducers.js: export const userDetailsReducer = (state = { user: {} }, action) =>{ switch (action.type) { case USER_DETAILS_REQUEST: return { ...state, loading: true } case USER_DETAILS_SUCCESS: return { loading: false, user: action.payload } case USER_DETAILS_FAIL: return { loading: false, error: action.payload} default: return state } } userActions.js: export const getUserDetails = (id) => async (dispatch, getState) => { try{ dispatch({ type: USER_DETAILS_REQUEST }) const { userLogin: { userInfo }, } = getState() const token = userInfo.token const config = { headers:{ 'Content-type': 'application/json', Authorization: 'Bearer'+token, } } const { data } = await axios.get( '/api/users/'+id, config ) dispatch({ type: USER_DETAILS_SUCCESS, payload: data }) }catch(error){ dispatch({ type:USER_DETAILS_FAIL, payload:error.response && error.response.data.detail ? error.response.data.detail : error.message, }) } } ProfileScreen.js: import React, {useState, useEffect} from 'react' import { Link, useNavigate, useParams, useLocation } from 'react-router-dom' import { Form, Button, Row, Col } from 'react-bootstrap' … -
Error When Parsing Incoming Email Via SendGrid
I am successfully set up a webhook with django/python to parse incoming SendGrid emails. However, I am getting an error and cannot parse the data I receive. The error suggest the body I am receiving is empty, which is not the case. @csrf_exempt def receive_email_hook(request): print("request.body: ",request.body) try: data = json.loads(request.body.decode('utf-8')) sender = data['from'] recipient = data['to'] subject = data['subject'] body = data['html'] print("SUBJECT: "+str(subject)) return HttpResponse(status=200) except Exception as e: print("ERROR: "+str(e)) return HttpResponse(status=400) My error is: ERROR: Expecting value: line 1 column 1 (char 0) When I print the request.body, I get: request.body: b'--xYzZY\r\nContent-Disposition: form-data; name="headers"\r\n\r\nReceived: (...) The full print has all the information from the email and all the data I would expect. Just seems to be an error on the parsing but can't figure it out. I asked Chat GPT but got some whack ass answers, so fellow human, can you help? -
I´m trying to include a local javascript in my react component, and the functionality of said component is inconsistent
I have a component in react called consentBottom, where I am trying to import an external javascript file called consent. I can get the functionality of the consent file to work, but once I press the "go back" button and then immediately "go forward" button in the browser, the functionality from the javascript file stops working. Bear in mind that there is no function to export manually from this file. It´s full of functions, using jquery, that get invoked when buttons or forms that have a particular class or id names are pressed or submitted. This is a file integraded from another environment, and the project is being transferred from flask to the setup with django on the backend and react on the frontend. The pipeline of my project now is: index.html -> (calls element by div with id=root) index.js -> has the following call to the App component: <React.StrictMode\> <App /> </React.StrictMode\> App.js -> has the following url routes: <BrowserRouter> <Route path='/' element={<Home languageState={languageState}/>} /> <Route path='/consent' element={<Consent languageState={languageState}/>}/> <Route path='/authenticate-presenter' element={<AuthenticatePresenter languageState= {languageState}/>}/> <Route path='/main-complaints' element={<MainComplaints languageState={languageState}/>}/> <Route path='/questions' element={<Questions languageState={languageState}/>}/> </BrowserRouter> Home (url="/") -> Has a main component homeMainPage, which calls another component homeBody inside the jsx … -
Cytoscape.js not loading graph in Django
I am trying to show graph in the HTML template of my Django application, I first tried with the actual data that I am working with (I am using the Neomodel to fetch the data from Neo4J and then transforming it to right JSON for cytoscape), but it did not work with it. After that I tried with the mock data but it did not after that either. I don't understand what I am doing wrong. This is my graph.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Graph View</title> <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.23.0/cytoscape.min.js" integrity="sha512-gEWKnYYa1/1c3jOuT9PR7NxiVI1bwn02DeJGsl+lMVQ1fWMNvtjkjxIApTdbJ/wcDjQmbf+McWahXwipdC9bGA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>--> <script src="https://cdnjs.cloudflare.com/ajax/libs/cytoscape/3.8.4/cytoscape.min.js" integrity="sha512-gn5PcEn1Y2LfoL8jnUhJtarbIPjFmPzDMljQbnYRxE8IP0y5opHE1nH/83YOuiWexnwftmGlx6i2aeJUdHO49A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <style> #cy { width: 300px; height: 250px; display: block; background-color: #fff; } </style> </head> <body> {{data}} <div id="cy"></div> <div id="test"></div> <h2>Hello</h2> <script> var cy = cytoscape({ container = document.getElementById('cy'), elements: { nodes: [ { data: { id: 'a', name: 'Sheraton Cherry' } }, { data: { id: 'a1', name: 'Rosacea'}}, { data: { id: 'a2', name: 'Dentate' } }, { data: { id: 'a3', name: 'Pinnate' } }, { data: { id: 'b', name: 'Pineapple Guava' } }, { data: { id: 'b1', name: 'Myrtaceae'}}, { data: { id: 'b2', name: 'Entire' } }, { data: { id: 'a3', name: … -
Django Admin display Count of related field
I am building a Django project for a workshop (car/motorcycle). Have a customer class in models and a service class. In the admin I want to display the number of services per customer, I am taught to use the get_queryset and define a variable for that count, but it doesn't want to work, probably its like a really easy fix but I can't get my head around it! Hope someone here knows, thanks a lot! :-) MODELS.PY from django.db import models # Create your models here. class Fordonsregister(models.Model): regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False) namn = models.CharField(max_length=255, null=True, blank=True) tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True) email = models.EmailField(null=True, blank=True) kund_sedan = models.DateTimeField(auto_now=True) kund_points = models.IntegerField(default=0) def __str__(self) -> str: return self.regnr class Meta: ordering = ['regnr'] class ServiceTypes(models.Model): typ = models.CharField(max_length=255, primary_key=True, blank=False) pris = models.DecimalField(decimal_places=2, max_digits=6, null=False, blank=False) beskrivning = models.CharField(max_length=255, null=True, blank=True) def __str__(self) -> str: return self.typ class Meta: ordering = ['typ'] class FordonsService(models.Model): regnr = models.ForeignKey(Fordonsregister, on_delete=models.CASCADE) typ = models.ForeignKey(ServiceTypes, on_delete=models.CASCADE) service_datum = models.DateTimeField() bokat_datum = models.DateTimeField(auto_now=True) kommentar = models.CharField(max_length=1000) class Meta: ordering = ['-service_datum'] ADMIN.PY from django.contrib import admin from django.db.models import Count from django.http import HttpRequest from .models import Fordonsregister, ServiceTypes, FordonsService … -
How to change the time format when providing an initial value in Django?
I made a form in Django and provided an initial value to the time field when rendering the form, the format is HH:MM:SS but if I do not provide any initial value the format is HH:MM. I want to specify an initial value and want the format to be HH:MM. class SearchTimeSlotsForm(forms.Form): available_from = forms.TimeField( widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(0) ) available_till = forms.TimeField( widget=TimeInput(attrs={'class': 'unbold-form'}), initial=time(23,59,59) ) Can someone please help me with this? -
How to decrease an image size when loading the page in Django backed web application?
My classic Django application is a simple blog post website showing the posted images line on a start page. I allow users to upload images to their posts up to 100 Mb to have the ability to download the image if someone likes it. But I encountered a significant loading time on the start page due to image sizes. I use CSS object-fit feature to make images small for good fitting on a common start page, but the image size in Mb doesn't change. It is still downloading full-sized images and after just shaping them with CSS. As a result, I have very slow page loading. I used a standard model pattern in the Django backend: image = models.ImageField...and then just render it on a page template with post.image.url tag. So I want the original-sized image loads if users click on the image only. Please advise how to fix that. -
How to configure multiple sites with django and apache server with wsgi
I configure two sites in my server, but when trying access to my second site apache2 redirect me to first site, I want to serve tow sites in the same server but not working This is my configuration of my first site: GNU nano 5.4 first_site.com.conf <VirtualHost first_site.com:80> #ServerAdmin admin@soporte.localhost ServerName inscripcion.uepbi.com #ServerAlias www.first_site.com #DocumentRoot /home/sites/first_site #DocumentRoot /var/www ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /favicon.ico /home/sites/first_site/staticfiles/favicon.ico Alias /static/ /home/sites/first_site/staticfiles/ <Directory /home/sites/first_site/staticfiles> Require all granted </Directory> Alias /uploads/ /home/sites/first_site/uploads/ <Directory /home/sites/first_site/uploads> Require all granted </Directory> <Directory /home/sites/college_system/college_system> <Files wsgi.py> Require expr %{HTTP_HOST} == "first_site.com" Require expr %{HTTP_HOST} == "www.first_site.com" Options </Files> </Directory> WSGIDaemonProcess first_site python-path=/home/sites/first_site python-home=/home/sites/first_site_env #WSGIPythonHome /home/sites/first_site #WSGIPythonPath /home/sites/first_site WSGIProcessGroup first_site WSGIScriptAlias / /home/sites/first_site/first_site/wsgi.py process-group=first_site application-group=%{GLOBAL} Redirect "/" "https://first_site.com/ RewriteEngine on RewriteCond %{SERVER_NAME} =www.first_site.com [OR] RewriteCond %{SERVER_NAME} =first_site.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] #RewriteCond %{SERVER_NAME} !on [OR] #RewriteCond %{SERVER_NAME} ^www\. [NC] #RewriteRule ^ https://first_site.com%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> This my configuration for my second site: <VirtualHost second_site.com:8080> #ServerAdmin admin@soporte.localhost ServerName second_site.com #ServerAlias www.second_site.com #DocumentRoot /home/sites/second_site ErrorLog ${APACHE_LOG_DIR}/error_demo_college.log CustomLog ${APACHE_LOG_DIR}/access_demo_college.log combined Alias /favicon.ico /home/sites/second_site/staticfiles/favicon.ico Alias /static/ /home/sites/second_site/staticfiles/ <Directory /home/sites/second_site/staticfiles> Require all granted </Directory> <Directory /home/sites/second_site/static> Require all granted </Directory> Alias /uploads/ /home/sites/second_site/uploads/ <Directory /home/sites/second_site/uploads> Require all granted </Directory> <Directory /home/sites/second_site/second_site> <Files wsgi.py> Require expr … -
Django navigation problems because of url
I have created a web app using the Django framework. I created a function to iterate through my installed apps and display the desired apps as links to said app, without having to hard-code the link to each app (the function finds the link and displayed app name) On my home page I have links to my other apps, and they all work, but once I enter an app, the links to every other app do not. The function still does what it is supposed to, but when the links are clicked, the url of the clicked app is appended to the end of the current url instead of replacing it and directing me to the desired app. How to I get the clicked url to replace the current url and not just append to it? I designed the names of my urls and apps to work with this function, and that works, but I did not expect the clicked links to append themselves to the current url. -
DRF and Html {% render_form serializer %}
I worked with django rest framework and I have problem with generics.ListCreateAPIView when I want to add template_name for form I can't {% render_form serializer %} and I get error. in browser enter image description here in terminal enter image description here index.html {% load rest_framework %} <html><body> <form action="{% url 'post:posts' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> <li>{{ id }}</li> <li>{{ title }}</li> <li>{{ body }}</li> <ul> {% for list in results %} <li>{{ list.id }}</li> <li>{{ list.title }}</li> <li>{{ list.body }}</li> ------------ {% endfor %} </ul> </body></html> view.py class PostList(generics.ListCreateAPIView): # queryset = Post.objects.all() permission_classes = (IsAuthenticated,) serializer_class = PostSerializer # Add Template renderer_classes = [renderers.TemplateHTMLRenderer] template_name = 'index.html' filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter ] filterset_fields = ['id','title','body'] search_fields = ['id','title','body'] ordering_fields = ['id','title','body'] def perform_create(self, serializer): return serializer.save(owner=self.request.user) def get_queryset(self): return Post.objects.filter(owner=self.request.user) I would try with DRF documents, but I couldn't. -
Django and Js framework as FrontEnd
What is the best way to integrate Django with React or Vue.js Framework? Using the framework as a template (in the template folder) in Django or creating API and then consume with the framework? How does Django's integration with Js framework works in the real world projects? I'm new Django programmer and have this question. -
Application Error - Heroku logs - Need Help Interpreting
I created a django project months ago deployed it to Heroku. It functioned well for quite a few months, but when Heroku changed to a paid service my site was knocked off. I've been trying to resurrect it and have gotten part of the way. The website allows students to practice reading musical pitches on the note staff and finger board (for orchestra instruments). When I visit my site after deployment, it takes me to a landing page where I can choose to sign up, login, or go to a free games page. Both Login and Registration pages load, but when clicking submit the redirect times out. It should go to the main orch_quiz page which contains the quizzes for the students. Instead I get an Application Error page that suggests I use the heroku logs --tail command. When I run that, I understand the H12 is a timeout error code, but it does not explain why the timeout is happening. I'm a novice at building websites so any assistance or guidance would be greatly appreciated! The project is deployable and does without noticeable error. The issues seems to be in accessing the orch_quiz app. I've run pip freeze to … -
how to make the central postgres db handle these concurrent connexions more efficiently?
we have 100 separate python scripts connecting at the same time to a central postgres database to perform multiple operations like reads and writes postgres creates a separate process for each of these clients, which is not efficient and consumes too much resources. -
Django handler404 not called on raise Http404
I've setup a custom 404 handler in my Django views @api_view(["GET"]) def handler_404(request: HttpRequest, exception: Exception = None): return Response({"status": 404, "error": "Not Found"}, status=404) It works perfectly if I visit an invalid path; however it is not called when I raise Http404 exceptions, for example with the get_object_or_404 method - the default 404 response is returned instead. I implemented a workaround by adding a 404 handler in my middleware but I'd like to know if there's something I'm doing wrong and how to intercept Http404 exceptions with it def process_response(self, request, response): if response.status_code == 404: # for some reason views.handler_404 doesn't catch Http404 Exceptions return JsonResponse({"status": 404, "error": "Not Found"}, status=404) This is what my urls file looks like (as I said the handler works fine on most 404 responses) handler400 = api.views.handler_400 handler403 = api.views.handler_403 handler404 = api.views.handler_404 handler500 = api.views.handler_500 To sum it up, I tried adding the handler in my urls file but it is not called upon Http404 exceptions. Thank you for the help -
Fix mixed content from frontend or backend
I built the frontend of my website using React, and it is hosted on netlify. Here is an example of a call I make to my API. fetch(`http://....com/all/`, { method: "GET", headers: { 'Content-Type': 'application/json', } }).then((res) => { return res.json(); } ).then((data) => { let informations = data.restaurant; // do stuff with data }).catch((err) => { console.log(err); }) This site is hosted on an https domain, provided by netfily. Then, my backend is a Django app, built with Docker compose and hosted on digital ocean droplets, that serves via HTTP. But each time I can the API with the site, it returns that Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http:...'. This request has been blocked; the content must be served over HTTPS. How is it fixable? I am not able to figure out a way to put https into my backend, and the frontend is not working properly. Please help -
How can I consume and HTTP API in my HTTPS website
I built the frontend of my website using React, and it is hosted on netlify. Here is an example of a call I make to my API. fetch(`http://blabla.com/all/`, { method: "GET", headers: { 'Content-Type': 'application/json', } }).then((res) => { return res.json(); } ).then((data) => { let informations = data.restaurant; // do stuff with data }).catch((err) => { console.log(err); }) This site is hosted on an https domain, provided by netfily. Then, my backend is a Django app, built with Docker compose and hosted on digital ocean droplets, that serves via HTTP. But each time I can the API with the site, it returns that Mixed Content: The page at 'https://...' was loaded over HTTPS, but requested an insecure resource 'http:...'. This request has been blocked; the content must be served over HTTPS. How can I fix this? Is there anything that can be done on the frontend to allow it? Otherwise, how do I put the HTTPS stuff on digital ocean droplets and django? Because I spent almost three hours trying to figure it out, without being able to do so. Please help me -
Changing the location where my domain resolved to on a Nginx server
I have my DND set to my domain name and I want to load a installation of a Django website I have installed. When I load www.mywebsite.com it loads a mydomain but from /var/www/html but I want it to load from /home/myname/kkappDashboard; I'm using a Nginx server and here is the sites-available configuration server { listen 80; server_name 151.236.222.57 www.mywebsite.com mywebsite.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/myname/kkappDashboard; } location / { include proxy_params; proxy_pass http://unix:/home/myname/kkappDashboard/kkappDashboard.sock; } } server { listen 443 ssl http2; server_name www.mywebsite.com; # redirect return 301 https://mywebsite.com.com$request_uri; } server { listen 443 ssl http2; server_name mywebsite.com; } -
Django JWT token auth: What does JWT_AUTH_COOKIE do
I am trying to use JWT auth method for authentication. I checked dj-rest-auth has the setting JWT_AUTH_COOKIE and JWT_AUTH_REFRESH_COOKIE whats the role of these tokens. I dont see any mention of these tokens in the documentation of djangorestframework-simplejwt https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html -
What should Authenticate Fetch from a User?
I joined a group that has been using Django and I was just curious for some performance aspects of user fetching for Authentication. The User objects have some foreignkeys/manytomany fields attached to them. I learned about the prefetch_related / select_related. So if I want to get everything of a user instance, that would result to about 10 queries. So my question is about API / REST Design. Should my auth only do 1 Query ( select User) or should it fetch alle the stuff that could be useful for other endpoints? Each endpoint uses the CustomAuthentication, so the queries would be executed for each API call. Is ist better to let people take care of a second well designed query at the endpoint, or should I provide them with alle variables on each endpoint autmatically ? Thanks in advance. This question is performance related. I tracked the requests with SILK and was not happy about the performance for retrieving Users -
How to return a list of objects using a Django REST API post request?
I am new to using REST API's and am trying to create an API where I can make a POST request containing keywords, which should then return a list of articles related to that keyword. The reason I can't use a GET request is because I am not GETting anything from a database, I am creating the list of articles based on the keyword from the POST request. Views.py: def article_get(request): if request.method == 'POST': serializer = serializers.ArticleListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) classes.py: class Article: title = "" url = "" def __init__(self, url, title): self.title = title self.url = url class ArticleList: keywords = "" articles = [] def __init__(self, keywords, articles): self.keywords = keywords self.articles = articles self.articles.append(serializedArticle) The self.articles.append(serializedArticle) line appends a serialized article to the articles list, which I hoped would simply add an article in JSON format to the articlelist, but instead it produces the following error: Object of type ArticleSerializer is not JSON serializable serializers.py: class ArticleSerializer(serializers.Serializer): title = serializers.CharField(max_length=300) url = serializers.CharField(max_length=300) def create(self, validated_data): return classes.Article(**validated_data) class ArticleListSerializer(serializers.Serializer): articles = serializers.ListField() keywords = serializers.CharField(max_length=100) def create(self, validated_data): return classes.ArticleList(**validated_data) As I mentioned, I am FAR from being … -
How to create link in Djano?
here i was stuck to link this page to another page, bacause because here I use forloop to make a content. So, how i can solve this ? here my index.html {% extends 'main.html' %} {% block content %} <main> <section class="py-5 text-center container"> <div class="row py-lg-5"> <div class="col-lg-6 col-md-8 mx-auto"> <h1 class="fw-light">Qatar's Album</h1> <p class="lead text-muted"> Something short and leading about the collection below—its contents, the creator, etc. Make it short and sweet, but not too short so folks don’t simply skip over it entirely. </p> <p> <a href="#" class="btn btn-primary my-2">Main call to action</a> </p> </div> </div> </section> <div class="album py-5 bg-light"> <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for isi in listContent %} <div class="col-md-4 mb-3"> <div class="card" style="width: 18rem"> <div class="card-body"> <h5 class="card-title text-center">{{ isi.title }}</h5> <p class="card-text text-center">{{ isi.desc }}</p> <a href="{{ what should i write here ?}}/" class="btn btn-primary d-flex justify-content-center">Details</a > </div> </div> </div> {% endfor %} </div> </div> </div> </main> {% endblock %} here is my function in views.py def index(request): listContent = Table_Content.objects.all().values() data = { "listContent" : listContent } template = loader.get_template('index.html') return HttpResponse(template.render(data, request)) and here is my urls.py in app urlpatterns = [ path('', views.index, name='index'), … -
Field 'id' expected a number but got 'S' django
view.py `@login_required(login_url="signin") def editproduct(request,pk): if request.user.is_superuser == 1: category = Category.objects.all() product = Product.objects.get(id=pk) data = { "categories":category, "product":product, "url":"products" } if request.method == "POST": name = request.POST.get('product_name') description = request.POST.get('description') product_category = request.POST.get('category') homepage = request.POST.get('homepage') if name is None or name == "": return render(request,"admin/editproduct.html",{ "error":"Ürün Adı Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) if description is None or description == "": return render(request,"admin/editproduct.html",{ "error":"Ürün Açıklaması Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) if product_category is None or product_category == "": return render(request,"admin/editproduct.html",{ "error":"Kategori Boş Bırakılamaz!", "categories":category, "product":product, "url":"products" }) product.product_name = name product.description = description if homepage == "on": product.homepage = True else: product.homepage = False product.save() product.category.set(product_category) print(pk) return redirect('editproduct',pk) return render(request,"admin/editproduct.html",data) else: return redirect('/')` The category the product belongs to appears 2 times in the category selection section and if I choose the 2nd one, the pk value becomes the first letter of the category's name and gives this error, how is this possible? -
django rest framework serializer, create an object for some model field
I have a serializer which looks like this: class ListingSerializer(serializers.ModelSerializer): class Meta: model = Listing fields = '__all__' My Listing model have some field: name, price, description, etc.., street_address, postal_code, city, etc... I would like my serializer to return an object like this: { "name": "Prestige", "price": 12, "description": "lorem ipsum", "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" }, ... } instead of the basic: { "name": "Prestige", "price": 12, "description": "lorem ipsum", "street": "123 Main St", "city": "New York", "state": "NY", "zip": "10001" ... } What I want is encapsulate all "address" field into an "address" object in my response.