Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django web app "Not allowed to load local resource /.css file"
I cant load css file in my web page it just gives me a simple page without css elements as shown in the screenshot and says it cant load local resource Page and inspect elememt I've loaded the static files in settings STATIC_URL = '/static/' STATICFILES_DIRS=[ os.path.join(BASE_DIR,'static') ] STATIC_ROOT=os.path.join(BASE_DIR,'assets') added url static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) used this in html {%load static%} <head> <style> {% include "assets/styles/style.css" %} </style> <meta charset="UTF-8"> <title>LOGIN</title> <link rel="stylesheet" href="{% static 'assets/style.css' %}"> </head> also did manage.py loadstatic followed the docs dont know where i went wrong -
Django.db.utils.ProgrammingError: relation does not exist
Django.db.utils.ProgrammingError: relation does not exist an error is occurring. I am new to Heroku and trying to solve the issue. I found some resources on StackOverflow but it doesn't help me out with my problem. I also try to make migrations from Heroku run bash but the same error is shown while trying to perform makemigrations the access is getting denied from Heroku. this is the error capture from heroku run console. -
How can I import a python file coded by myself and then see what it does on a django website?
I am currently working on my website, which is a translator which you input a phrase and it gets translated into an invented language. Here's the code of the translator function: def translator(phrase): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper: translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper: translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper: translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper: translation = translation + "C" else: translation = translation + "c" return translation However, I am stuck in showing this funcion in my web, here's the code in views.py: from .translate import translator def translator_view(request): return render(request,'main/translator.html') def translated_view(request): text = request.GET.get('text') print('text:', text) translate = translator dt = translator.detect(text) tr = translated.text context = { 'translated': tr } return render(request, context, 'main/translated.html') Here's the template where you introduce the text: <form action="{% url 'translated' %}" method= "get"> <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> … -
Login with Django and Ajax does nothing
Here is my form: <form action="#" method="post"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Enter Username:</label> <input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off"> </div> <div class="form-group"> <label for="exampleInputEmail1">Enter Password:</label> <input type="password" class="form-control" id="password" name="password" placeholder="Password" autocomplete="off"> </div> <button class="btn btn-primary" id = 'login_button'>Login</button> </form> And the script: <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script> var login_button = $('#login_button') login_button.click(function(){ var username = $('#username').val() var password = $('#password').val() $.ajax({ url: '{% url 'td_app:do_login' %}', type: 'get', data: { 'username': username, 'password': password }, dataType: 'json', success: function (data){ console.log(data.result) } }).done(function (){ console.log(data.result) }) }) </script> In my views.py: def do_login(request): username = request.GET.get('username') password = request.GET.get('password') user = authenticate(username=username, password=password) data = {} if user: if user.is_active: login(request, user) data['result'] = 'success' return HttpResponseRedirect(reverse('td_app:index')) else: data['result'] = 'failed' return JsonResponse(data) And finally my urls.py: url(r'^api/do_login/$', views.do_login, name='do_login') However all of these doesn't work and it doesn't even give me any errors. It just completely refreshes the whole page and does nothing. I tried putting alerts but on the success and done section but it doesn't show it up. Any thoughts/advices? Thanks a lot! -
How to download videos on Django (youtube_dl)
I am making a website for downloading videos from YouTube and not only. For this I use the youtube_dl library. When the button is clicked, I redirect to the file link. I also made a site about programs for Windows, and when I redirect to a file link, it was downloaded. It doesn't work with video, the video just opens in the browser. So this is how to download videos? views.py: from django.shortcuts import render, redirect from .models import Video import youtube_dl import uuid def index (request): last_video = Video.objects.last () current_video = Video.objects.get (pk = last_video.pk) return render (request, 'main / index.html', {'current_video': current_video}) def video_loader(request, video_id): video_url = request.GET.get('url', '') filename = str(uuid.uuid4()) ydl_opts = { 'format': 'bestvideo', 'outtmpl': f'media/videos/{filename}.%(ext)s' } if video_url: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([video_url]) Video.objects.create(name = filename, url = video_url, file = f'videos/{filename}.mp4') else: pass current_video = Video.objects.get(pk=video_id) return redirect(current_video.file.url) Html form: <form class="banner__form" id="banner__form" method="POST" action="{% url 'video_loader' current_video.pk%}"> {% csrf_token %} <input class="banner__input" id="banner__input" type="text" placeholder="Enter link" autocomplete="off" name='url' maxlength="100"> <button type="submit" class="fas fa-search fa-2x banner__btn" id="banner__btn"></button> </form> If you still need something, I will throw it off. -
Splitting django project in two big modules and getting import problems
I want to start a new enterprise project which will be very large and will have a thorough business logic. I want to split it into two "sub-projects", one with the models, api and business logic (called "business"), and the other with the views for the web app (called "webapp"). The idea of separating the web app (views) from the models, api and business logic is because I want these 3 lasts to be the service for both web app and mobile too. The layout looks like this: project/ + business/ | + __init__.py | + rest_urls.py | + business_app_1/ | | + __init__.py | | + controllers.py | | + models.py | | + serializers.py | + business_app_2/ | | + __init__.py | | + controllers.py | | + models.py | | + serializers.py + project/ #this one is just the main configuration django app | + __init__.py | + settings.py | + urls.py | + wsgi.py + webapp/ | + __init__.py | + urls.py | + view_app_1/ | | + views.py | + view_app_2/ | | + views.py | + view_app_n/ | | + views.py I just ran a test because I never made a complex layout like … -
django-summernote codemirror theme setting
I would like to to set custom theme for 'codemirror' mechanism at django-summernote. In Readme.md of django-summernote it says (https://github.com/summernote/django-summernote/blame/master/README.md#L222): You have to include theme file in 'css' or 'css_for_inplace' before using it. I found codemirror themes there: https://codemirror.net/demo/theme.html https://github.com/codemirror/CodeMirror/tree/master/theme in settings.py I've added: SUMMERNOTE_CONFIG = { 'codemirror': { 'mode': 'htmlmixed', 'lineNumbers': 'true', 'theme': 'monokai', } } Question: where to put css files - somewhere in site-packages of django-summernote or inside my django app? If in my app - where in static/ folder. I've tried both above options but it didn't worked. How to do it properly? -
Would it be possible to filter results based on an aggregated child field using django-filter?
I have invoices with items in them. Item's have prices. Now I wish to sum the items and based on the sums, filter the invoices. Here are the models class Invoice(models.Model): title = models.CharField(max_length = 150) reciept_image = models.ImageField(upload_to='invoice_receipts/%Y/%m/%d', null = True, blank = True) date = models.DateTimeField(default=datetime.now) class Item(models.Model): invoice_id = models.ForeignKey(Invoice, on_delete=models.PROTECT) item_name = models.CharField(max_length = 150) amount = models.DecimalField(max_digits=9999, decimal_places=2) The Serializers are class InvoiceSerializer(serializers.ModelSerializer): item_set = ItemSerializer(many = True, read_only = True) class Meta: model = Invoice fields = ['id', 'title', 'reciept_image', 'date', 'item_set'] class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ['id', 'invoice_id', 'item_name', 'amount'] I simply cannot seem to wrap my head around this. I hope this isn't too advance a functionality for SQLite. -
duplicate key value violates unique constraint django rest framework
I have App named Company and in models.py there is a model named CompanyProfile models.py class CompanyProfile(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, verbose_name='ID',) full_name = models.CharField(max_length=255, unique = True, default='NA') contact_person_email = models.EmailField(unique=True, null=True, blank=True) def __str__(self): return str(self.full_name) serializers.py class CompanyProfileSerializer(serializers.ModelSerializer): """List all the Company Profile""" class Meta: model = CompanyProfile fields = '__all__' read_only_fields = ['id'] ``` views.py ````python class CompanyProfileViewSet(viewsets.ModelViewSet): """Update and Detail for Company Profile""" queryset = CompanyProfile.objects.all() serializer_class = CompanyProfileSerializer permission_classes = (permissions.IsAuthenticated,) lookup_field = 'id' def update(self, request, id ,*args, **kwargs): instance = self.get_object() import pdb; pdb.set_trace() if instance.full_name != request.data.get("full_name"): instance.full_name = request.data.get("full_name") if instance.contact_person_email != request.data.get("contact_person_email"): instance.contact_person_email = request.data.get("contact_person_email") instance.save() return super().update(request, *args, **kwargs) Now if you see above am actually comparing each field and checking weather update is possible there or if the field needs to be updated? 1. Doing this one each field is quite cumbersome as I have already set the required validation But now I have to check on each field whether the user has updated them or not! 2. If I don't have an update in any of the fields then it gives me this error already exists and sometimes as some field are marked unique in … -
Connecting Django 3.1 to MongoDB
I am working with Django 3.1 edition. As a Database, my choice is to go with any NoSQL database like MongoDB. I have tried two ways to connect MongoDB with Django 3.1. First One is using Djongo and the Second one is using Mongo Engine. But both the cases, I am unable to work with Django 3.1. In the case of Django, it's not supporting Django 3.1 but it switching me to Django 3.0.5, and in the case of mongo engine it's not supporting Django 3.1. Is there any third way to connect MongoDB with Django 3.1. Note that I have to use Django 3.1 only These are the docs I was following in Djongo and Mongo Engine. https://pypi.org/project/djongo/ https://django-mongodb-engine.readthedocs.io/en/latest/topics/setup.html -
localhost redirected you too many times in Django
I am using user_passes_test decorator. and the view blog_update_view redirects only if there is a post request. Then why am I getting so many redirects when a non admin user tries to update the blog? I def check_admin(user): return user.is_superuser @user_passes_test(check_admin) def blog_update_view(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) if request.method == 'POST': form = BlogForm(request.POST, request.FILES, instance=blog) if form.is_valid(): form.save() messages.success(request, 'Blog updated!!') return redirect(blog.get_absolute_url()) form = BlogForm(instance=blog) context = { 'form': form, 'blog': blog, } return render(request, 'blogs/blog_update.html', context) My urls.py: app_name = 'blogs' urlpatterns = [ path('category/<slug:category_slug>/', blog_category_view, name='blog_category'), path('tag/<slug:tag_slug>/', blog_tag_view, name='blog_tag'), path('new/', blog_create_view, name='blog_create'), path('<slug:blog_slug>/update/', blog_update_view, name='blog_update'), path('like/', like_blog_view, name='like_blog'), path('search/', SearchBlog.as_view(), name='search_blog'), path('<slug:blog_slug>/', blog_detail, name='blog_detail'), path('', blog_home_view, name='home'), ] -
Django bootstrap modal ajax: Modal not showing
I am trying to implement CRUD Using Ajax and Json following this tutorial. Here is my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.book_list, name="book_list"), path('books/create', views.book_create, name="book_create"), ] Here is my views.py from django.http import JsonResponse from django.template.loader import render_to_string from django.shortcuts import render from .models import * from .forms import BookForm def book_list(request): books = Book.objects.all() return render(request, 'books/book_list.html', {'books': books}) def book_create(request): form = BookForm() context = {'form': form} html_form = render_to_string('books/includes/partial_book_create.html', context, request=request, ) return JsonResponse({'html_form': html_form}) Here is my base.html {% load static %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bookstore</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> <body> {% include 'books/includes/header.html' %} <div class="container"> {% block content %} {% endblock %} </div> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> {% block javascript %} {% endblock %} </body> </html> Here is my book_list.html where action button is. {% extends 'books/base.html' %} {% load static %} {% block javascript %} <script src="{% static 'js/books.js' %}"></script> {% endblock %} {% block content %} <h1 class="page-header">Books</h1> <!-- BUTTON TO TRIGGER THE ACTION --> <p> <button type="button" class="btn btn-primary js-create-book"> … -
Django - Order itertools.chain object by date
I get the messages of 2 users Bob and John like this: urlparam = 'John' own_mx = Message.objects.filter(sender__username=request.user).filter(recipient__username=urlparam) his_mx = Message.objects.filter(sender__username=urlparam).filter(recipient__username=request.user) then I use itertools' chain function to combine both querysets into one: inbox = chain(own_mx,his_mx) The messages are now grouped by user, but I need them to be ordered by date. The django model Message has a DateTimeField: sent_at. How can I order inbox by sent_at? Thank you for any suggestions. -
Heroku & Django: Debug = False returns server error, I tried couple of solutions but nothing works
So I am trying to put my website into production applying variables to secretkey and debug value, after passing heroku config: set Secret_Key="(My key)" and heroku config: set Debug_value=False . My website returns server error 500. Every page of it returns same error. I've done adding my site URL in allowed host and done with collectstatic both on local and server. But still the error continues. Please help I am trying this for last 3days. Here is my settings.py """ Django settings for Calculator project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import django_heroku import mimetypes import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get("DEBUG_VALUE") == "True") #DEBUG = True ALLOWED_HOSTS = [ 'mathtools.herokuapp.com','127.0.0.1/','localhost' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'Calculator_base' ] … -
How to implement two different types of users with extended attributes in Django?
I am using python 3.8.3 and Django 3.0.8 I am building a project that allows students and teachers to login to it. Hence I have two different kinds of users. Also these two users have extended attributes and methods apart from the one that Django provides implicitly to its user model, like department, organisation, etc. How can I implement them? Most of the articles I come across are either very old and for outdated versions of Django and python or they don't combine my required functionality? How can I extend my user model to have more attributes and how do I implement two different kinds of users? And how do I separately enforce authentication for these two different kinds of users? -
Don't know how to convert the Django field recipes.Recipe.image (<class 'cloudinary.models.CloudinaryField'>)
I basically started working on a graphene-django website that uses cloudinary to hose images model: from django.db import models from cloudinary.models import CloudinaryField from tinymce.models import HTMLField class Origin(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name DIFFICULTY_CHOICES = [ ('Easy', 'Easy'), ('Moderate', 'Moderate'), ('Experienced', 'Experienced'), ('Hard', 'Hard') ] class Recipe(models.Model): name = models.CharField(max_length=150) image = CloudinaryField('image') origin = models.ForeignKey(Origin, related_name="recipes", on_delete=models.CASCADE) category = models.ForeignKey( Category, related_name="recipes", on_delete=models.CASCADE ) serves = models.IntegerField(blank=True, null=True) difficulty = models.CharField(max_length=11, choices=DIFFICULTY_CHOICES, default="Moderate") kcal = models.FloatField(max_length=6) fat = models.FloatField(max_length=6) saturates = models.FloatField(max_length=6) carbs = models.FloatField(max_length=6) sugars = models.FloatField(max_length=6) fibre = models.FloatField(max_length=6) protein = models.FloatField(max_length=6) salt = models.FloatField(max_length=6) instructions = HTMLField() def __str__(self): return self.name and the problem seems like that graphene is not sure how to convert the cloudinary field, and I'm not sure how to deal with that? I saw these questions that were close but still didn't quite get it. One Two -
How to translate numbers in django translation?
My head could not click how to translate numbers in django translation. It is not possible to translate by string id. I could print 2020 like: {% translate '2' %}{% translate '0' %}{% translate '2' %}{% translate '0' %} Obvioulsy, It is not the way. So, I am missing something. I would want something like: {% translate "2020"|number %} # may be It should be that, translation from 0 to 9. -
How to queryset the field with foreign key's ID in form in Django?
I have 2 models, Class and Attendance. Inside Attendance model I have 2 fields, student(ManytoManyField) and course(ForeignKey). Inside AttendanceForm I want to queryset student field with course's id. How can I do it? # models.py class Class(models.Model): student = models.ManyToManyField("account.Student") class Attendance(models.Model): student = models.ManyToManyField("account.Student") course = models.ForeignKey(Class, on_delete=models.CASCADE) # forms.py class AttendanceForm(forms.ModelForm): class Meta: model = Attendance fields = ['student', ] widgets = {'student': forms.CheckboxSelectMultiple()} def __init__(self, class_pk, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) current_class = Class.objects.get(id=class_pk) <- # try to get class's id here self.fields['student'].queryset = current_class.student # view.py class AttendanceFormUpdate(UpdateView): model = Attendance form_class = AttendanceForm def get_form_kwargs(self): kwargs = super(AttendanceFormUpdate, self).get_form_kwargs() if self.request.user.is_teacher: kwargs['class_pk'] = self.kwargs.get('pk') <-- # try to pass class's pk to form return kwargs As you can see what i'm doing inside get_form_kwargs is passing the id of the model not the id of course field. How can pass the course field id to the form? -
what are the steps to check before uploading a django project to github to secure the project
When I uploaded my project to GitHub it sends me an email saying that my secret key is exposed to the project. So what are the things to check before uploading a Django project to GitHub -
I don't understand that keyerror occurs in my code in django
I am using the django rest framework modelviewset to re-turn the entire post when I request get. But after writing the code, I sent the get request and the following error appears. Traceback (most recent call last): File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_except ion raise exc File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\feed\views.py", line 23, in list 'email': serializer.data['author_email'], KeyError: 'author_email' I have clearly stated this in the serializer, but I don't understand why a keyerror appears. Can you tell me what the problem is in my code? Here's my code. Thank in advance. views.py class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) def list (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) data = { 'author': … -
chnage url paramaters parameters in request by id
i wanna make urls with GET url pattern example.com/blog/?id=1 my current code views.py def home(request,blog_uuid): blogs = Blog.objects.get(pk=blog_uuid) return render(request,'home.html',{'blogs':blogs}) url pattern path('blog/<blog_uuid>/',views.home,name='Blog'), my current url now like this example.com/blog/1 -
open(file.read(), 'rb') raises UnicodeDecodeError
I'm creating a project with Django that involves user uploading images. To test for an image and how it's stored in Django's default storage, I'm using the combination of SimpleUploadedFile, io.BytesIO(), and the Pillow Image class. When I test for the successful creation of a model instance (Photo) a UnicodeDecodeError is raised. ERROR: setUpClass (photos.tests.test_models.TestPhotoModel) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\..\..\..\..\..\venv\lib\site-packages\django\test\testcases.py", line 1137, in setUpClass cls.setUpTestData() File "C:\..\..\..\..\..\photos\tests\test_models.py", line 23, in setUpTestData content=open(file.read(), 'rb') UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte I cannot figure out why this error is being raised. How can this be addressed so the test can run properly? from io import BytesIO from unittest.mock import Mock, patch from django.test import TestCase from django.db.models import ImageField from django.core.files.uploadedfile import SimpleUploadedFile from PIL import Image from ..models import Photo class TestPhotoModel(TestCase): @classmethod def setUpTestData(cls): file = BytesIO() image = Image.new("RGB", (50, 50), 'red') image.save(file, "png") file.seek(0) data = { 'title': "Title", 'image': SimpleUploadedFile( 'test_image.png', content=open(file.read(), 'rb') ) } cls.new_photo = Photo.objects.create(**data) def test_photo_instance_created(self): total_photos = Photo.objects.count() self.assertEqual(total_photos, 1) -
Multi Language DjangoCMS
I want use multi language in my project . I had install cms app core . But this app only English language. But I want multi language when I choose option . So I have to create anorther app or create new template or anything ? . I don't know how to do it . Let me know the solution -
Django: How to compare two different data table for datafield and get match exactly correct data?
Models.py class Newspaper (models.Model): newspaper = models.CharField(max_length=50) language = models.CharField(max_length=50, choices=Language) wh_price = models.DecimalField(max_digits=6,decimal_places=2) sa_price = models.DecimalField(max_digits=6,decimal_places=2) description = models.CharField(max_length=50) company = models.CharField(max_length=50) publication = models.CharField(max_length=50, choices=Publication) class Daily_Cart(models.Model): ac_no = models.CharField(max_length=32) newspaper = models.CharField(max_length=32) added_date = models.DateTimeField(max_length=32,auto_now_add=True) daily_update.py def bill(): current_time = datetime.datetime.now().day if current_time == 27: news = Newspaper.objects.all() daily = Daily_Cart.objects.all() for x in news: if x.publication=='Weekdays': for xc in daily: print(xc.newspaper, x) Daily_cart table have to compere with newspaper table. If data exits have to print newspaper AND ac_no. This result i expect to. Here you can see models /Newspaper/Daily_cart print(xc.newspaper, x) monnews monnews if use print(set(xc.newspaper)& set(x)) i got error Traceback (most recent call last): File "C:\Users\user\Documents\Project--Django\Pro_Venv\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job retval = job.func(*job.args, **job.kwargs) File "C:\Users\user\Documents\Project--Django\Pro_Venv\NewspaperAPI\invoice.py", line 18, in bill print(set(xc.newspaper)& set(x)) TypeError: 'Newspaper' object is not iterable -
How can I customize the response value of the {'get': 'list'} request in django?
I am making an API that gives the entire post when requested by get. After writing the code, the value was printed as follows when the request was sent. { "pk": int, "author_username": "", "author_email": "", "author_profile": "profile_url", "title": "", "text": "", "like": liker.count, "liker": [ pk ], "image": [ image_url , ] "view": 1 }, I would like to customize this to the following form. { "pk": int, "author: { "author_username": "", "author_email": "", "author_profile": "profile_url" } "title": "", "text": "", "like": liker.count, "liker": [ pk ], "image": [ image_url , ] "view": 1 }, How can I change the shape of json like this? Attach the code on views.py. Thanks in advance. class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user)