Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No Leasson matches the given query. Django
The project structure is as follows: Category: Subcategory: Object. implemented the system next-prev(cat-sub-obj) with difficulty. how can i optimize this code when an object ends up in a subcategory. I can't immediately jump to the next item in the next subcategory. def leasson(request, course_slug, section_slug, leasson_slug): leasson = get_object_or_404(Leasson, course__slug=course_slug, section__slug=section_slug, slug=leasson_slug) section = get_object_or_404(Section, course__slug=course_slug, slug=section_slug) try: next_leasson = leasson.get_next_by_date_added(section__slug=section_slug) except Leasson.DoesNotExist: next_leasson = None try: next_section = section.get_next_by_date_added(course__slug=course_slug) except Section.DoesNotExist: next_section = None try: prev_section = section.get_previous_by_date_added(course__slug=course_slug) except Section.DoesNotExist: prev_section = None try: prev_leasson = leasson.get_previous_by_date_added(section__slug=section_slug) except Leasson.DoesNotExist: prev_leasson = None context = { 'leasson': leasson, 'next_leasson':next_leasson, 'prev_leasson':prev_leasson, 'next_section':next_section, 'prev_section':prev_section } return render (request, 'leasson.html', context) path('<slug:course_slug>/<slug:section_slug>/<slug:leasson_slug>/', leasson, name="leasson") {% if prev_leasson %} <a href="{% url 'leasson' leasson.course.slug leasson.section.slug prev_leasson.slug %}">{{ prev_leasson.title }}</a> {% else %} This is first leasson {% endif %} {% if next_leasson %} <a href="{% url 'leasson' next_leasson.course.slug next_leasson.section.slug next_leasson.slug %}">{{ next_leasson.title }}</a> {% else %} This is last leasson {% endif %} {% if prev_section %} <a href="{% url 'section' prev_section.course.slug prev_section.slug %}">{{ prev_section }}</a> {% else %} This is first section {% endif %} {% if next_section %} <a href="{% url 'section' next_section.course.slug next_section.slug %}">{{ next_section }}</a> {% else %} This is … -
One template for all errors. django
One template to catch all errors on the project and show the information to the user I would like to create a single template to catch and show, to the user, all or at least most of the errors that may occur on the website; but I don't find information about it, and maybe you can help me. -
Django channels not recalling old messages from channel
I am using Django channels to create a chat app. When the chat page is refreshed, the past messages disappear. Also, when I reconnect to the channel, the old messages do not show up. Everything else seems to work fine, messages can be sent and received by the other user, message data is being saved into the database for each specific channel. No error is thrown back. managers.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) models.py from django.db import models from app_users.models import User from app_chat.managers import ThreadManager class TrackingModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField( max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField(User) objects = ThreadManager() def __str__(self): if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' class Message(TrackingModel): thread = models.ForeignKey(Thread, on_delete=models.CASCADE) sender = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField(blank=False, null=False) def __str__(self) -> str: return f'From <Thread - … -
Is there a specific way to deny anyone else from logging in to an already logged in account?
I just created my website but facing some issues, is there a way to check if someone is already logged in to an account and if so, user should be redirected to login page so that he/she can log in to a different account if he/she wishes. I'm using python with Django. -
Django Html Raise ValidationError
In my models.py I have: class Post(models.Model): res_person_1 = models.TextField(max_length=40, verbose_name="User") When I load form I run script: $("#id_res_person_1").replaceWith("<select name='res_person_1' id='id_res_person_1' class='form-control' required></select>") $("#id_res_person_1").append("<option>" + '---------' + "</option>") //append options where I create dropdown menu and fill it with users from DB. Problem is, in my models.py and when I run script, I put that field as required. On all other required fields in the form, when I submit, I get error 'Required field', but never on that one. How can I raise an error or show any kind of message to tell the user that he should select something from the dropdown menu. So far I tried (but it did not work): def clean_res_person_1(self): if self.res_person_1 == '' or self.res_person_1 == '---------': raise forms.ValidationError("self.fields['res_person_1'].error_messages['invalid']") return self.cleaned_data -
For each item update database
I'm a total beginner with Python/Django and trying to understand why this isn't working. I have a function that contains a for loop, doing some logic and then updating a model. but when I have more than 1 item in the loop I get a UNIQUE constraint failed: app_token.token_name error. So I think I'm misunderstanding how the loop is working? function tokens = Token.objects.all() for item in tokens: if item.token_contract_address is not None: token = Token.objects.get(pk=item.id) parameters = { 'address':token.token_contract_address } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) resp = json.loads(response.text) token_id = (resp['data'][next(iter(resp['data']))]['id']) logo = (resp['data'][next(iter(resp['data']))]['logo']) url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' parameters = { 'id':token_id } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) id = str(token_id) price = (json.loads(response.text)['data'][id]['quote']['USD']['price']) market_cap = (json.loads(response.text)['data'][id]['quote']['USD']['market_cap']) change = (json.loads(response.text)['data'][id]['quote']['USD']['percent_change_24h']) r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) I'm expecting the this Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) to update the model based on the item loop? The model is very simple: class Token(models.Model): token_name = models.CharField(max_length=50, blank=False, unique=True) token_slug = models.CharField(max_length=50, blank=True,null=True) token_price = models.FloatField(blank=True,null=True) token_capture_date = models.DateField(blank=True,null=True) token_contract_address = models.CharField(max_length=50, blank=True,null=True) def __str__(self): return str(self.token_name) I'm using the update on the objects and have tried removing the token_name, … -
Apache2: 'AH01630: client denied by server configuration' with referer?
I'm trying to setup a django website but for some reason when I try to access the admin page it shows up without an CSS, I dug a bit further and ensured that my file permissions where correct by just making the entire project directory accessible to everyone chmod -R 777 ./survey_server But it still just isn't working for me for some reason, I'm not sure what's going on. I've checked, rechecked, and triple checked my apache config file to no avail. This is my config file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com # ServerName crimjusticesurvey.org ServerAdmin webmaster@crimjusticesurvey.org DocumentRoot /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server <Directory /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server> Require all granted </Directory> <Directory /home/ubuntu/Workspace/github/crimjusticesurvey/survey_server/survey> Require all granted </Directory> # Available loglevels: … -
Return the category value as null in Django (json)
Why does my category return null when I receive Jason output? enter image description here enter image description here enter image description here enter image description here -
Faster way than .csv to upload data into Django app
Right now I copy a whole table from a website, paste it into a cell on an excel spreadsheet and it formats it into a .csv file. After the .csv is made I upload the file into my database via a Django app. I also have a model form if I wanted to enter the data manually. What I was wondering is if there is a way to skip a step to make the process faster. Maybe copy the table from the web and paste it into a form cell and it gets formatted like excel does. Any tips or ideas are greatly appreciated. -
accessing 2 foreign key fields at the same time in django serializers
I have the following models in my django rest framework project. in this project there are products and they have producers and importers. # models.py class Product(models.Model): name = models.CharField(max_length=255) producer = models.ManyToManyField(Company, related_name='producer') importer = models.ManyToManyField(Company, related_name='importer') class Company(models.Model): name = models.CharField(max_length=255) I need to make an API which retrieves an instance of the "Company" model and gives me a list of the products they have produced and another list for the products that they have imported Now I know to do this with only one manytomany field, I can do the following: class CompanyRetrieveSerializer(serializers.ModelSerializer): class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('name',) product_set = ProductSerializer(read_only=True, many=True,) class Meta: model = Company fields = '__all__' but since there are two fields in the product model that reference the company model, this doesn't work. Is there any way to fix this issue? -
Why isn't my javascript not working with django
I am a beginner in django. I have no problem with the back-end but my front-end has some problem with javascript (specifically addEventListener doesn't work). I've tried everything from adding External js to adding internal js nothing seems to work. But the js connect with django and its being loaded, but the function doesn't work and no error seems to log in the console. It is just a click function, which should toggle a classname in html while clicked. By the way I'm inheriting my nav file. i hope that doesn't cause any problem. My internal js file: <script type="text/javascript"> // EVENT LISTENER FOR NAV FUNCTION let nav_btn = document.querySelector('.user-pr') nav_btn.addEventListener('click', navfunc) function navfunc() { nav_btn.classList.toggle('active') console.log("click") } </script> My Settings.py file (Static Config): STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I've checked StackOverflow for similar questions, but nothing match my scenario. -
404 Not Found nginx/1.18.0 (Ubuntu) when deploying django in aws
I'm trying to deploy a django project on aws using nginx server any (and aws RDS mysql database). After configuration I'm getting 404 Not Found nginx/1.18.0 (Ubuntu) error. When I try to access any the pages of the application except the url for the home page (/). That's, I can access only the base url, others are showing page not found root /var/www/html; # Add index.php to the list if you are using PHP index index.php index.html index.htm index.nginx-debian.html; server_name ip_address; location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. include proxy_params; proxy_pass http://unix:/var/www/html/django/app.sock; try_files $uri $uri/ =404; } # pass PHP scripts to FastCGI server location /phpmyadmin/{ root /usr/share/; index index.php; try_files $uri $uri/ =404; } location /static/ { autoindex on; alias /var/www/html/django/staticfiles/; proxy_pass http://unix:/var/www/html/django/app.sock; try_files $uri $uri/ =404; } location ~ \.php$ { include snippets/fastcgi-php.conf; # # # With php-fpm (or other unix sockets): fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # # With php-cgi (or other tcp sockets): # fastcgi_pass 127.0.0.1:9000; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } } I developed the … -
How to set celery in docke-compose.yml
I am trying to integrate celery, rabbitmq with my django app and run it using docker, below is my docker-compose.yml file: version: '3.4' services: db: image: postgres:13.4 env_file: - ./docker/env.db ports: - 5432:5432 app: &app build: context: . dockerfile: ./docker/Dockerfile env_file: - ./docker/env.db - ./.env volumes: - .:/opt/code ports: - 8000:8000 - 3000:3000 depends_on: - db - rabbitmq command: bash ./scripts/runserver.sh rabbitmq: image: rabbitmq:3.7-alpine container_name: 'rabbitmq' ports: - "5672:5672" celery: <<: *app command: celery -A app worker --loglevel=info ports: [] depends_on: - rabbitmq However,I am getting this error: celery_1 | [2022-01-22 07:03:36,373: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. celery_1 | Trying again in 6.00 seconds... (3/100) What should I do? Help would be much appreciated. Thank you! -
Django Pass through Table field data to Serializer
I have the following models: class Disease(models.Model): name = CICharField("Disease Name", max_length=200, unique=True) symptoms = models.ManyToManyField(Symptom, through='DiseaseSymptom', related_name='diseases') class Symptom(models.Model): name = CICharField("Symptom Name", max_length=200, unique=True) PRIORITY = ( (0, 'Normal'), (1, 'Low'), (2, 'Medium'), (3, 'High'), (4, 'Key'), ) class DiseaseSymptom(models.Model): disease = models.ForeignKey(Disease, on_delete=models.CASCADE, related_name='disease_to_symptom') symptom = models.ForeignKey(Symptom, on_delete=models.CASCADE, related_name='symptom_to_disease') priority = models.PositiveSmallIntegerField('Priority', choices=PRIORITY, default=0) On the front-end, I have multiple select boxes where users can select multiple Symptoms to find disease and that will pass to Disease model as symptoms_selected params. I have the following get_queryset on Disease > views.py def get_queryset(self): params = self.request.query_params query_symptoms = self.request.GET.getlist('symptoms_selected') if query_symptoms: queryset = Pattern.objects.filter( symptoms__id__in=query_symptoms ).annotate( matches=Count('symptoms') ).order_by('-matches') else: queryset = Disease.objects.all() return queryset serializer_class = DiseaseSerializer I am using Django REST API to pass the result data. class DiseaseSerializer(serializers.ModelSerializer): symptoms_matches = serializers.SerializerMethodField() class Meta: model = Disease fields = ('id', 'name','symptoms_matches') def get_symptoms_matches(self, obj): return getattr(obj, 'matches', None) For eg: Disease Data: Disease A: Got Symptoms: A (priority=4), B (priority=2), C (priority=3), D (priority=2) Disease B: Got Symptoms: A (priority=1), D (priority=2), P (priority=4), Q (priority=2) Currently, if Users select 2 symptoms: A, D. I want queryset will return the count of key symptoms matched i.e. symptom … -
I have 2 forms on the same page that uses django-recaptcha ReCaptchaV2Invisible, when I submit the "2nd" form the "1st form is submitted instead
Hi I have two forms on my home page, the one is a "contact form" and the other one is a "subscribe to mail list form". I used the "django-recaptcha ReCaptchaV2Invisible" field on both forms. The contact form works fine, but if I submit the second form (the mail list one) the first form is submitted and I get and invalid form error (obviously). Has anyone experience the same problem? any recommended fixes? Thanks -
Google Cloud Django Postgres: could not connect to server: Connection refused
I've deployed a Django project to Google App Engine Flexible Environment and using postgress for database connection. I followed this https://cloud.google.com/python/django/flexible-environment I've successfully setup it on my local machine but when I deploy on cloud I'm getting following error: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? Here is my database setup in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/INSTANCE_CONNECTION_NAME', 'NAME': 'DB_NAME', 'USER': 'DB_USERNAME', 'PASSWORD': 'DB_PASSWORD', 'PORT': '5432', } } when I start server in local db: ./cloud_sql_proxy -instances="PROJECT_NAME:REGION:INSTANCE_NAME"=tcp:5432 I get this : Listening on 127.0.0.1:5432 for PROJECT_NAME:REGION:INSTANCE_NAME"=tcp:5432 and when try on local i tried like this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/INSTANCE_CONNECTION_NAME', 'NAME': 'DB_NAME', 'USER': 'DB_USERNAME', 'PASSWORD': 'DB_PASSWORD', 'PORT': '5432', 'HOST': '127.0.0.1' } This works on my local computer and I can access DB. but when I remove 'HOST': '127.0.0.1' for deployment. after deployment I'm getting connection refused error -
IntegrityError at /apis/addtoCart NOT NULL constraint failed Django and API?
i am trying to insert data into my OrderItem() model: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) with an api with json data as follows: { "username": "admin", "item": "Kavya", "quantity": "1" } and i my view i am recieving this data and updating like: class addtoCart(APIView): # permission_classes=[IsAuthenticated,] # authentication_classes=[TokenAuthentication,] def post(self,request): username=request.data["username"] itemname=request.data["item"] quant=request.data["quantity"] #inserting data to cart article = OrderItem() article.User = username article.Item = itemname article.quantity=quant article.save() query=OrderItem.objects.filter(user=username) serializers=OrderItemSerializer(query,many=True) return Response(serializers.data) but whenever i try to do so i get an error: IntegrityError at /apis/addtoCart NOT NULL constraint failed: core_orderitem.item_id i dont know what causing this error can someone please help <3. -
How to use proxy with vite (vue frontend) and django rest framework
So, you know when you access a view with django rest api on the browser, you get an html page, and when you send something like an ajax request, you get the json? I'm trying to figure out how to mess with the proxy setting for vite, but I can't find a single decent documentation around it. I want to redirect '/' to 'http://localhost:8000/api', but there's really weird behavior going on. If I do this: //vite.config.js export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': { target: 'http://localhost:8000', changeOrigin: true, rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') } } } } }) //todo-component.vue export default { data() { return { todos: [] } }, components: { TodoElement }, beforeCreate() { this.axios.get('/').then((response) => { this.todos = response.data }) .catch((e) => { console.error(e) }) } } and make requests using '/api', it works as expected. However, if I do export default defineConfig({ plugins: [vue()], server: { proxy: { '/': { target: 'http://localhost:8000/api', changeOrigin: true, rewrite: (path) => { console.log(path); return path.replace('/^\/api/', '') } } } } }) import TodoElement from "./todo-element.vue" export default { data() { return { todos: [] } }, components: { TodoElement }, beforeCreate() { this.axios.get('/').then((response) => … -
fetching data from firebase and displaying in django templates (in table format)
hello am new to firebase i just want to fetch data from firebase and display in django(in table) db look like: enter image description here code in view.py look like: enter image description here code in html look like enter image description here o/p look like while running sever enter image description here please help me out by: displaying n no of node in templates in table format -
Is there a a function to implement when dealing with django image or filefield? Please help me out
I create a filed which contain Imagefield in my models but when I am trying to add the image to the to the field in my admin page it is telling me function not implemented This is how my models look like from django.db import models # Create your models here. class Image(models.Model): name = models.CharField(max_length = 40) img = models.ImageField(upload_to = 'images/') def __str__(self): return self.name This is my root MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') And this is the exception I got anytime I try to upload image to the models in my admin page OSError at /admin/imageapp/image/add/ [Errno 38]Function not implemented Request. Method: POSTRequest. URL:http://127.0.0.1:8000/admin/imageapp/image/add/ DjangoVersion:3.2.11 Exception Type:OSError Exception Value:[Errno 38] Function not implemented Exception. Location:/data/data/com.termux/files/home/ imagetest/lib/python3.10/ site-packages/django/core/files/locks.py, line 117, in unlockPython. Executable:/data/data/com.termux/files/home/imagetest /bin/pythonPython Version:3.10.2Python Path: ['/storage/emulated/0/imagetest', '/data/data/com.termux/files/usr/lib/python310.zip', '/data/data/com.termux/files/usr/lib/python3.10', '/data/data/com.termux/files/usr/lib/python3.10/lib- dynload', '/data/data/com.termux/files/home/ imagetest/lib/python3.10/site-packages'] Server time:Fri, 21 Jan 2022 16:13:45 +0000 -
Can't save chat messages with django and websocket
So I've been following this tutorial to build a chat feature between two users using Django and WebSockets/Channels: https://www.youtube.com/watch?v=lHGcSOkrKw0&t=122s&ab_channel=AaravTech Everything seems to work fine except for saving the chat messages. When I refresh the page the chat disappears. From checking the database, the thread instance is created but nothing is saved into it. It is just an empty {}. The thread instance can be called and has an ID. No new thread instance is created when I am trying to connect with a user with whom I already connected. app_chat/managers.py from django.db import models from django.db.models import Count class ThreadManager(models.Manager): def get_or_create_personal_thread(self, user1, user2): threads = self.get_queryset().filter(thread_type='personal') threads = threads.filter(users__in=[user1, user2]).distinct() threads = threads.annotate(u_count=Count('users')).filter(u_count=2) if threads.exists(): return threads.first() else: thread = self.create(thread_type='personal') thread.users.add(user1) thread.users.add(user2) return thread def by_user(self, user): return self.get_queryset().filter(users__in=[user]) app_chat/models.py from django.db import models from app_users.models import User from app_chat.managers import ThreadManager class TrackingModel(models.Model): created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) class Meta: abstract = True class Thread(TrackingModel): THREAD_TYPE = ( ('personal', 'Personal'), ('group', 'Group') ) name = models.CharField(max_length=50, null=True, blank=True) thread_type = models.CharField( max_length=15, choices=THREAD_TYPE, default='group') users = models.ManyToManyField(User) objects = ThreadManager() def __str__(self): if self.thread_type == 'personal' and self.users.count() == 2: return f'{self.users.first()} and {self.users.last()}' return f'{self.name}' … -
Django CBV template ignores the override
First, settings.py set url conf: ROOT_URLCONF = "myproject.urls" , and INSTALLED_APPS includes: "myproject.apps.accounts", , which, in turn, has its urls.py set up with: app_name = "accounts" and path("login/", auth_views.LoginView.as_view(template_name="accounts/login.html", form_class=UserLoginForm), name="login"), manage.py check doesn't report any problems, and yet both routes don't work, though But browser reports on route of :accounts/login' reports: TemplateDoesNotExist at /accounts/login/ registration/login.html , where the name it misses is not the one I've put in template_name. I see this in the docs: template_name: The name of a template to display for the view used to log the user in. Defaults to registration/login.html. , which is why I'm overriding, right?... What am I doing wrong? Thanks! -
Django ManyToMany field object automatically pre-fills
I have an PaypalOrder model that is created when someone orders from a website, and it has a ManyToManyField that connects it to multiple OrderItems. Whenever I create a PaypalOrder, it automatically lists every OrderItem that exists in the django admin panel. How do I only list the objects that I set it to connect to? my models.py: class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField() is_a_subscription = models.BooleanField(default=False) subscription = models.ForeignKey('Subscription', on_delete=models.CASCADE, null=True, blank=True) class PaypalOrder(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) items_and_quantities = models.ManyToManyField(OrderItem, blank=True, related_name="paypalorder") full_name = models.CharField(max_length=100) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250, null=True, blank=True) city = models.CharField(max_length=100) zipcode = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) total_paid = models.DecimalField(max_digits=10, decimal_places=2) order_id = models.CharField(max_length=100, null=True, blank=True) subscription_id = models.CharField(max_length=100, null=True, blank=True) email=models.CharField(max_length=100, null=True) country_code = models.CharField(max_length=100) state = models.CharField(max_length=50, null=True) my view: order = PaypalOrder.objects.create( user = user, full_name= resp['subscriber']['name']['given_name'] + " " + resp['subscriber']['name']['surname'], email = resp['subscriber']['email_address'], city = resp['subscriber']['shipping_address']['address']['admin_area_2'], state = resp['subscriber']['shipping_address']['address']['admin_area_1'], address1 = resp['subscriber']['shipping_address']['address']['address_line_1'], address2 = addr2, zipcode = resp['subscriber']['shipping_address']['address']['postal_code'], country_code = resp['subscriber']['shipping_address']['address']['country_code'], total_paid = resp['billing_info']['last_payment']['amount']['value'], order_id = "product_ID: " + resp['id'], subscription_id = resp['plan_id'], created_at = resp['create_time'], ) order.save() subscription = Subscription.objects.create(user = request.user, paypal_order = order) order.items_and_quantities.set(OrderItem.objects.filter(pk=100)) -
How to get required fields as a list of json by DRF serializer
I am trying to acieve simple nested json. serializer.py class CurrencyMasterSerializer(serializers.ModelSerializer): class Meta: model = CurrencyMaster fields = ["id", "name"] { "id": 1, "name": "USD - United States Dollar" }, { "id": 2, "name": "EUR - Euro Members" }, { "id": 3, "name": "JPY - Japan Yen" }, This is I got response by postman. But I expect output like below, { "country-codes": [ { "id": 1, "name": "USD - United States Dollar" }, { "id": 2, "name": "EUR - Euro Members" }, { "id": 3, "name": "JPY - Japan Yen" }] } How can i achieve this???? -
How to access request data in Nested Serializer?
I am trying to create writable nested serializer to create posts. I want to create multiple model instances of Image and Video. However, I don't know how to access request.data in the nested serializer which is necessary for the many=True condition #serializers.py class PostSerializer(serializers.ModelSerializer): images = ImageViewSerializer(many=True) videos = VideoViewSerializer(many=True) class Meta: model = Post fields = ['caption', 'user', 'images', 'videos'] extra_kwargs = { 'caption': {'required': False}, 'images': {'required': False}, 'videos': {'required': False} } def create(self, validated_data): return super().create(validated_data) I want to make it like so... class PostSerializer(serializers.ModelSerializer): images = ImageViewSerializer(many=isinstance(request.data,list)) videos = VideoViewSerializer(many=isinstance(request.data,list)) ...