Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I'm Getting Bad Request Error After Uploading the Video
I'm uing Django and React to make a YouTube clone. I tried to post the video on the frontend side, and got an error in terminal: <QueryDict: {'title': ['Test Video Creation'], 'user': ['1'], 'description': ['Is it working?'], 'image': [<TemporaryUploadedFile: attachment.png (image/png)>], 'video': [<TemporaryUploadedFile: video-for-fatube.mp4 (video/mp4)>]}>Bad Request: /api/admin/create/ And the problem is not in the backend settings, because when I made a post request in the postman, the video was succesfully created. creat.js File on frontend side to create videos. import React, { useState } from 'react'; import axiosInstance from '../../axios'; import { useHistory } from 'react-router-dom'; //MaterialUI import Avatar from '@material-ui/core/Avatar'; import axios from "axios"; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; import IconButton from '@material-ui/core/IconButton'; import PhotoCamera from '@material-ui/icons/PhotoCamera'; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export default function Create() { const history = useHistory(); const initialFormData = Object.freeze({ … -
Error at /basic_app/ Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I am a beginner in HTML templates and Django. school_list.html {% extends "basic_app/basic_app_base.html" %} <!-- {% load static %} --> {% block body_block %} <h1>Here are the list of all the schools!</h1> <ol> {% for school in schools %} <h2><li><a href="{{school.id}}">{{school.name}}</a></li></h2> {% endfor % } </ol> {% endblock %} **Error:**TemplateSyntaxError at /basic_app/ Invalid block tag on line 10: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag? Views.py from django.shortcuts import render from django.views.generic import (View,TemplateView, ListView,DetailView) from . import models # from django.http import HttpResponse # Template views with CBV class IndexView(TemplateView): template_name='index.html' # List View class SchoolListView(ListView): context_object_name='schools' model=models.School template_name='basic_app/school_list.html' # Detail View class SchoolDetailView(DetailView): context_object_name='school_detail' model=models.School template_name='basic_app/school_detail.html' models.py from django.db import models from django.urls import reverse # Create your models here. class School(models.Model): name=models.CharField(max_length=256) principal=models.CharField(max_length=256) location=models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name=models.CharField(max_length=256) age=models.PositiveIntegerField() school=models.ForeignKey(School,related_name='students',on_delete=models.CASCADE) def __str__(self): return self.name urls.py from django.urls import include, re_path # from django.conf.urls import url from basic_app import views app_name='basic_app' urlpatterns = [ re_path(r'^$',views.SchoolListView.as_view(),name='list'), re_path(r'^(?P<pk>\d+)/$',views.SchoolListView.as_view(),name='detail') ] I need output like the following image, when clicking on school page : -
How to access Authorization code flow, Implicit Flow and Hybrid flow in Django oauth toolkit
I want to implement OpenID connect in my project. So I started using Django Oauth Toolkit. I was able to make the changes in Dajango Rest framework menu and was able to test the Resource owner password-based flow using the curl command curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/ After that I made all the changes as mentioned in the OpenId Connect menu. I have Generated RSA private key Added the changes as mentioned in the documentation Then I registered applications for each flow as mentioned in the documentation. Then the problem arise. I tried testing these flows the same way I tested Resource owner password-based flow eg: For Authorization code flow curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid" -u "rwOah6DU7PXPbpE7CWVokh16YeMIFsPCE4zv1ZUk:5p186YD3Wvf0nMz4bfXd9UJXbQnACMfpVzHwJ6AuneoPqnjJuoPUz4CiEM653gUIhCOMtV96Yymr1kLnAimdyfxWZMP2hOzslEH9kMpfoqyOorwviY8f1rs1BqcTSUtn" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For Implicit Flow curl -X POST -d "grant_type=password&username=user&password=aryan123&scope=openid&response_type=id_token" -u "qKgH4Bx5QzOdSdRo5h7vUSpSaivHk0SaccMa0coH:DyNdcoS52JuanNhjjqqbRnemGaq27sQrwa43C6ieYahxCdHYXXJt4Y5ZdwXVbNZdZmt89XoAJ7kBuFoDZanZvhCCza3WMLWlCwSy5qv09W1QyJsLmTEGUzRHkytU21s1" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For Hybrid flow curl -X POST -d "grant_type=password&username=user&password=aryan123" -u "YpKesUZnxyvOysKje4H2NNFhs45roO8z0SBu58Y5:Yf2IAsMRoLCbLrEUHsgPByLLnmFrNYPvqtYXuaZAJV5HbHioFZtbsTzh6Oj1W7jgWOKVU0PLsUwBPO0j5y7fhOLbUFiH2X9ZhdnQ3wJ7KxFOjTHYu2Cd52IxGO7U3iF3" http://localhost:8000/o/token/ I'm getting the error: { "error": "invalid_grant", "error_description": "Invalid credentials given." } For the development purpose I have generated the private key and stored it in a python file itself like this Note: The … -
Django - I want to store the data of 3 models into a single database in phpmyadmin (MySQL)
I have created 3 models (country, state and city) and the inputted data is getting stored in 3 different table. I want to store this data into a single table with following columns: Database Column Schema Models.py class Country(models.Model): id = models.AutoField(primary_key=True) parent_id = models.IntegerField(null=False) name = models.CharField(null=False, max_length=255) status = models.CharField(null= True, choices=Status_Choices, max_length=11, default='--Select Status--') added_by = models.IntegerField() updated_by = models.IntegerField() created_on = models.CharField(default=get_current_datetime_str , max_length=255) updated_on = models.CharField(default=get_current_datetime_str, max_length=255) def __str__(self): return self.name class State(models.Model): parent = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) def __str__(self): return self.name class City(models.Model): Country = models.ForeignKey(Country, on_delete=models.CASCADE) state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(null=False, max_length=255) def __str__(self): return self.name admin.py from django.contrib import admin from location.models import Country, State, City from django import forms from django.contrib import admin class CountryAdmin(admin.ModelAdmin): exclude = ('parent_id', 'created_on', 'updated_on', 'added_by', 'updated_by') def save_model(self, request, obj, form, change): user = request.user # Check if the user is authenticated (i.e. logged in) if user.is_authenticated: # If the user is authenticated, set the added_by field to the user's ID obj.added_by = user.id else: # The user is not authenticated, do something else ... if change: obj.updated_by = user.id # Save the model instance super().save_model(request, obj, form, change) admin.site.register(Country, … -
Dockerized python.django app does not run in the browser
I have a python-django app built in ubuntu OS that I am trying to containerize. Docker builds and runs with no error. But when I try to browse the site in a browser, I do not see it. This is my allowed hosts in settings.py ALLOWED_HOSTS = ["localhost", "127.0.0.1","0.0.0.0"] And this is my dockerfile #base image FROM python:3.10 # setup environment variable ENV DockerHOME=/home/app RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip3 install --upgrade pip # copy whole project to your docker home directory. COPY . $DockerHOME # run this command to install all dependencies RUN pip3 install -r requirements.txt # port where the Django app runs EXPOSE 8000 # start server CMD python3 manage.py runserver 0.0.0.0:8000 I tried to run it by the following commands with no luck. sudo docker run -p 8000:8000 myapp:v0 #also the following sudo docker run myapp:v0 I am browsing the site with http://0.0.0.0:8000/ I tried with the docker ip http://172.17.0.2:80000 So not sure what am I missing. Any idea would be very much appreciated. -
get size of data responsed to the browser in django?
I want get size of http data responsed to the browser in django. how to do that.? the destination i want is difference between gzip response and non-gzip response. -
How to run "AND" operator with "filter()" without "SyntaxError: keyword argument repeated:" error in Django?
I have Blog model below. *I use Django 3.2.16 and PostgreSQL: # "store/models.py" from django.db import models class Blog(models.Model): post = models.TextField() def __str__(self): return self.post Then, store_blog table has 2 rows below: store_blog table: id post 1 Python is popular and simple. 2 Java is popular and complex. Then, when writing the filter() code with 2 post__contains arguments in test() view to run AND operator as shown below: # "store/views.py" from .models import Person def test(request): print(Blog.objects.filter(post__contains="popular", post__contains="simple")) # Here return HttpResponse("Test") I got the error below: SyntaxError: keyword argument repeated: post__contains So, how to run AND operator with filter() without SyntaxError: keyword argument repeated: error in Django? -
Django logger refuse to show full traceback in file message
Currently, i'm setting up logging in Django following the document https://docs.djangoproject.com/en/2.2/topics/logging/ (I'm using Django 2.2 with python3.7) and Django rest framework. Here is my settings.py: # LOGGING LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {asctime} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/var/log/django_errors.log', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', }, }, } Here is my view using django-rest-framework: import logging logger = logging.getLogger(__name__) class Countries(APIView): permission_classes = () authentication_classes = [] def get(self, request): try: ... some API process except Exception as e: import traceback print(traceback.format_exc()) logger.error(traceback.format_exc()) return JsonResponse({'code': 500, 'message': str(e)}, status=500) From the console I can see the print() show the correct full stack traceback. But in the logging file, it doesn't show any traceback. django_errors.log: ERROR 2022-12-22 11:35:21,051 "GET /api/countries HTTP/1.1" 500 72 ERROR 2022-12-22 11:35:21,065 "GET /api/countries HTTP/1.1" 500 72 I also tried logger.exception() the same thing happens, file doesn't log full stack traceback I tried looking online for solutions and tried them but to no prevail, hope someone can help me figure out why expected log to show correct traceback for example like console print(): File … -
How to show the human readable form of choices in DRF
How to show the human readable form of choices in DRF. I have genders choices. I have used serializermethodField() to solve this but it's read only and cannot write. GENDER = ( ('M', "Male"), ("F", "Female"), ("O", "Other") ) so in response I get { "gender": "M", } response I want { "gender": "Male", } -
Django - How to store existing Data in Variable from Database and Update it with another variable
I am facing an issue for few days but could not get the findings to solve it. Suppose, I want to update a record into database using a form and want to keep the existing data into a variable and update it using form and keep the updated data into another variable. Please be inform that i made a solution using session but want another way to solve it. def client_edit(request, client_id): client = Client.objects.get(id=client_id) previous_client_name = client if request.method == 'POST': form = AddClientForm(request.POST, instance=client) if form.is_valid(): client2 = form.save(commit=False) client2.save() context = { 'user': request.user, 'client': client2, 'previous_client':previous_client_name, } return render(request, 'did_app/client_edit.html', context=context) else: return render(request, 'did_app/client_edit.html', {'form': form}) else: return render(request, 'did_app/client_edit.html', {'client': client}) I tried this way but both client and previous_client return the same data. Please suggest. Thanks in advance -
Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
I've seen other posts about this such as here but I still can't figure out my issue. File structure of relevant files: ba_django_project | docker-compose.prod.yml | |__app | Dockerfile.prod | manage.py | .env.prod | |__ba_django_project | __init__.py | settings.py | wsgi.py docker-compose.prod.yml: version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod image: 370950449536.dkr.ecr.us-east-2.amazonaws.com/ba_django_project:ba_django_project_web command: gunicorn ba_django_project.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: - ./app/.env.prod depends_on: - db db: image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./app/.env.prod.db nginx: build: ./nginx image: 370950449536.dkr.ecr.us-east-2.amazonaws.com/ba_django_project:ba_django_project_nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: settings.py: from pathlib import Path from decouple import config import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATIC_DIR = os.path.join(BASE_DIR, "static") # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/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 = int(os.environ.get("DEBUG", default=0)) ALLOWED_HOSTS = [ 'ec2-3-20-22-254.us-east-2.compute.amazonaws.com', '0.0.0.0', 'localhost', '127.0.0.1' ] # Application definition INSTALLED_APPS = [ 'crispy_forms', 'users.apps.UsersConfig', 'resume.apps.ResumeConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
django for-loop only displaying the last iteration
I'm building a book recommendation django application. I'm done integrating my machine learning model but the problem is that it gets the data from the csv file i used, not from my database. I have no problem displaying the titles of the recommended books but I would like to let the users view the details page of the said book. With that being said, I need to get the id of the recommended books from my Book model. I'm relatively new to Django so please excuse if my codes are messy. Thank you in advance! This is the excerpt from my views.py def s_detail(request, book_id): #student paper detail cosine_sim = joblib.load('cosine_sim-v5.pkl') #load the ml model data = pd.read_csv('try.csv', sep=',', encoding='utf-8') try: book = Book.objects.get(pk=book_id) fav = True if book.favorites.filter(id=request.user.id).exists(): fav=False def recommendations(book_id,n, cosine_sim = cosine_sim): recommended_books = [] idx = book_id score_series = pd.Series(cosine_sim[idx]).sort_values(ascending = False) top_n_indexes = list(score_series.iloc[1:n+1].index) for i in top_n_indexes: recommended_books.append(list(data.index)[i]) # data.index for book_id column return recommended_books recommend = recommendations(book_id, 3) for i in recommend: new = Book.objects.filter(id=i) #to get the Book id from the model print(new) #just to check if it's working except Book.DoesNotExist: raise Http404("Title does not exist") return render (request, 'books/s_detail.html', {'book':book, 'fav':fav, … -
Application and request contexts in Flask
I really need your help. I am currently doing a project with Flask and I have used the application and request contexts but to this day I have not been able to understand why it is necessary to use them? I don't understand how they work. Every time a request is made to a web app developed with Flask a new instance of the Flask class is created or really how a Flask app works under the hood. It would be very helpful if you help me solve this doubt that is driving me crazy. Thank you very much in advance. I've read everywhere and I still don't understand. -
Python Virtual Environment Help - Django
Error Message I am struggling to install Django to my new project using pipenv, it keeps telling me to run another virtual environment rather than actually installing Django. Please help :( I tried to do what it says to using the other virtual env but it still won't work. -
Django OAuth Authentication
I built an app (Django backend, React frontend) that whenever a client login it will generate JWT authentication. React will store the access token and client can use it to access Django backend database. Then I want to add in social login feature (Google) so I will get back access token from that as well. However, this access token is different from the JWT access token generated before, so I wonder how can I integrate both ways of logging in a user smoothly on both Django and React? For JWT I use djangorestframework-simplejwt For social login I use django-allauth I can run each individual way perfectly on React, but I don't know how to keep both the installations of JWT and allauth in Django settings. -
Django Template changing html attribute based on slug and current request
When I tried to iterate through a list of post titles to create links in a django template the urls never match the requested path (matching the current web page should alter the formatting on the page for that list item). When I try and change things, Django spits out a 404 error which doesn't let me diagnose the problem or it "works" but not as expected. the relevant url patterns: path('<slug:post>', views.blog_post, name='entries') the relevant views function: def blog_post(request, post): try: return render(request, 'blog/post.html', { 'post_title':post, 'post_content':blog_posts[], 'posts':blog_posts.keys }) except: raise Http404() the template: <ul> {% for post in posts %} {% url "blog:entries" "{{post}}" as blog_entry %} <li><a href="/blog/{{post}}" {% if request.path == blog_entry %} class="active"{% endif %}> <span class="item">{{post}}</span> </a></li> {% endfor %} </ul> I suspect the {% url "blog:entries" "{{post}}" as blog_entry %} in the template is not resolving correctly as when I replace the href with {% blog_entry %} it causes a 404 error. I have tried hard coding it in, I have tried different ways of writing the url, I have tried changing the syntax (in case I am doing it incorrectly. I have checked the page source when I have run tests. I … -
Django: how to write django signal to update field in django?
i want to write a simple django signal that would automatically change the status of a field from live to finished, when i check a button completed. I have a model that looks like this\ class Predictions(models.Model): ## other fields are here user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) status = models.CharField(choices=STATUS, max_length=100, default="in_review") class PredictionData(models.Model): predictions = models.ForeignKey(Predictions, on_delete=models.SET_NULL, null=True, related_name="prediction_data") votes = models.PositiveIntegerField(default=0) won = models.BooleanField(default=False) when i check the won button that is in the PredictionData model, i want to immediately changes the status of the Prediction to finished. NOTE: i have some tuple at the top of the model. STATUS = ( ("live", "Live"), ("in_review", "In review"), ("pending", "Pending"), ("cancelled", "Cancelled"), ("finished", "Finished"), ) -
How to save Request URL from inspector in Django Model
I'm trying to implement a web application in which the user fills out a form and separately there is a form that the user fills out and selects a route on the map. I use Mapbox for this. In HTML it looks like I have a separate form in the form element and a separate map in the div element. When I built a route in the inspector, I find a processed request with the GET method and the Request URL. My question is how to save this URL request together with the form, or at least separately? How do I even save this URL request to the Django Model. Part from my model.py:: class Route(models.Model): route_name = models.CharField(max_length=50) lvl = models.IntegerField(default=0) about = models.TextField(max_length=1500) total_distance = models.IntegerField(default=0) country = models.ForeignKey(Country, on_delete=models.CASCADE) def __str__(self): return self.route_name def __str__(self): return self.about class RoutesURL(models.Model): url = models.CharField(max_length=1000) def __str__(self): return self.url And my views.py: def getForm(request): form = RouteForm() if request.method == 'POST': form = RouteForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('home') return render(request, 'routes_form/route_form.html', {'form': form}) -
Select related is not returning all the values from the relation in Django
I'm doing this query SELECT [User].[User_Id], [User].[Client_id], [User].[EMail], [User].[First_Name], [User].[Family_Name], [User].[Telephone], [Clients].[Client_Id], [Clients].[Name], [Clients].[Organization_type] FROM [User] INNER JOIN [Clients] ON ([User].[Client_id] = [Clients].[Client_Id]) WHERE [User].[EMail] = 'birna@athygli.is' In the SQL server is working fine even when I print in django the queryset looks good, but, when getting the results is not getting it from the Clients` table, It has to be something with the relation between tables in Django but I really don't know where Here are my two models class V2_Clients(models.Model): Client_Id = models.CharField(primary_key=True, max_length=50) Name = models.CharField(max_length=255, null=True) Organization_type = models.CharField(max_length=128, null=True) class Meta: managed = True db_table = "[Clients]" class V2_Users(models.Model): User_Id = models.CharField(primary_key=True, max_length=50) Client = models.ForeignKey(V2_Clients, on_delete=models.CASCADE) EMail = models.CharField(max_length=250) First_Name = models.CharField(max_length=50, null=True) Family_Name = models.CharField(max_length=50, null=True) Telephone = models.CharField(max_length=50, null=True) class Meta: managed = True db_table = "[User]" This is where I do the query, even when I do print(v2_user.query) I get the same SQL shown at the top, but is not getting the values from the Clients table only the results from the User v2_user = V2_Users.objects.using('sl_v2').filter(EMail=jsonData['Client']['Client_Email']).select_related() What could be the issue? -
How do I use multi tag filters in Django REST Framework API response?
first of all I apologize if I did not ask a question using better words. I am building a DRF App, I have Products Model, ProductSerializer and ProductsSummaryView. Furthermore, I have Workspace Model (not going to talk about it as it is not related to the issue). Now, I want to return those products details in success response which are attached with a specific Workspace, filtered on some parameters. What I have done: I defined filterset_fields and filter_backends. It works fine. For example, if I go to this URL {{domain}}/path/?country__title=Japan, it filters the data for Japan and show me. But the problem is, I want to filter using multi-tag, such as let's say if I want to see details for Japan and Korea, so I want something like this {{domain}}/path/?country__title=Japan&country__title=Korea, but it is not working and it just returns all the details. I even tried adding empty list format in the URL and tried this URL {{domain}}/path/?country__title[]=Japan&country__title[]=Korea, but it still did not work. Can anybody help me in this? My Product Model is: class Product(BaseModel): """Product model to store all prices of a product and related brand and countries it's available in""" product = models.CharField(max_length=255) country = models.ForeignKey(Country, null=True, on_delete=models.DO_NOTHING) … -
Unexpected pylance behaviour with Django vscode
I have Django project written with VScode When I open it on another machine I'm starting to receive errors from pylance. I compared all settings. Example of mistake: "user" is not a known member of "None" "GET" is not a known member of "None" "ingredient" is possibly unbound All the packages from requirements.txt, the same version of python as original etc. screenshot I've reinstalled IDE, python and extensions. It didn't work, so I have no idea what's the reason. -
I am not able to export image in CSV file in Django Admin
Everytime I export the data all of it gets exported but for the image which is there I am only getting the url of the image and not actual image. Image of exported CSV file Database fields from where I export it I want the actual image to be exported in CSV file and not the image storage path. If anyone knows how to do it kindly help. -
Model Form not displaying
So I created a model form but it's not showing in the page but it's registered on the django admin site.views.py[forms.py (https://i.stack.imgur.com/Z3qud.png)models.py the error I keep getting I tried creating the models using django shell -
how can I rate and give review about doctor services?
I'm trying to give a rate and review for a doctor service and that rate will come from the patient which means I have two types of users so how could be the view my models.py class User(AbstractUser): is_doctor = models.BooleanField(default=False) is_patient = models.BooleanField(default=False) class Doctor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) number_phone = models.CharField( _('االهاتف :'), max_length=50, blank=True, null=True) last_login = models.DateTimeField(auto_now_add=True, null=True) class Patient(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) name = models.CharField(max_length=50, verbose_name="الاسم ") last_login = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s' % (self.user.username) class Comments(models.Model): created_by = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comment') # co_email = models.ForeignKey( # User, on_delete=models.CASCADE, related_name='comment') co_body = models.TextField(max_length=400, verbose_name='التعليق') rate = models.IntegerField(default=0) created_dt = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) post = models.ForeignKey( User, on_delete=models.CASCADE, related_name='comments') def __str__(self): return 'علق {} على {}'.format(self.created_by.username, self.post) forms.py class Commentair(forms.ModelForm): co_body = forms.CharField(widget=forms.Textarea( attrs={'rows': 3, 'placeholder': 'ما هو تعليقك عل الدكتور ؟'}), label='التعليق') class Meta: model = Comments fields = ('co_body','rate') html <div class="col-md-12"> <form action="" method="POST"> <div class="rate"> <input type="radio" name="rate" id="rate10" value="5" required /><label for="rate10" title="5"></label> <input type="radio" name="rate" id="rate8" value="4" required /><label for="rate8" title="4"></label> <input type="radio" name="rate" id="rate6" value="3" required /><label for="rate6" title="3"></label> <input type="radio" name="rate" id="rate4" value="2" required /><label for="rate4" title="2"></label> <input type="radio" name="rate" … -
Why am I getting the "Key error" in this code Django Rest Framework?
Well, I am trying to show ads after every 10th post in my feed in Django rest framework with both ad and post model separate. I'm actually stuck and will really appreciate anyone that will help me solve this problem. Here's my code: My Post & Ad Model class Post(models.Model): question = models.TextField(max_length=500) image = models.ImageField(upload_to='posts/', blank=True, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) # tags = models.ManyToManyField(Tag, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) upvote = models.ManyToManyField(User, related_name="like", blank=True) downvote = models.ManyToManyField(User, related_name="dislike", blank=True) is_ad = models.BooleanField(default=False) ordering = ["-created_at"] def __str__(self): return self.question class Ad(models.Model): # unique identifier for the ad id = models.AutoField(primary_key=True) # name of the ad name = models.CharField(max_length=255) # image for the ad image = models.ImageField(upload_to='ads/images/', blank=True, null=True) # additional images for the ad image_2 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_3 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_4 = models.ImageField(upload_to='ads/images/', blank=True, null=True) image_5 = models.ImageField(upload_to='ads/images/', blank=True, null=True) # URL that the ad should redirect to when clicked url = models.URLField() # start and end dates for the ad start_date = models.DateField() end_date = models.DateField() # targeting information for the ad targeting = models.TextField() # budget for the ad budget = models.DecimalField(max_digits=10, decimal_places=2) # ad delivery type (standard …