Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
IDE to develop jinja templates
I am looking for an environment to develop jinja2 for django app. I currently use pycharm but I am missing a lot of features. At least I would like live reload for the webpage (reload after template modification) or perhaps a way to set value to template variables manually without backend (for testing purposes). Any tips for jinja development in any IDE are welcome. -
Documenting UML class diagrams for a Django MVT project
What is the best way to create a UML class diagram for a Django project that uses the MVT design pattern, especially when using the function-based views in the project? Is it correct to treat views as classes even if they're function-based ones? I have a mix of class-based and function-based views, so the option looks convenient, but I'm not sure if that's correct from a technical perspective. Also, can I treat the templates as the classes? -
Django Cannot import 'main_app' although its already in INSTALLED_APPS
I can't run my Django app due to the error about the main_app cannot be imported. However, I already have included main_app on the INSTALLED_APPS on settings.py. I have also tested recreating the error and it always comes up whenever I include the main_app inside he INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.main_app', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.main_app.urls')), ] main_app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index-home'), ] views.py def index(request): return render(request, 'index.html') Error file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Github\SwiftUrl\env\lib\site-packages\django\apps\config.py", line 244, in create app_module = import_module(app_name) File "c:\users\jerome\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main_app' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\jerome\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\jerome\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "D:\Github\SwiftUrl\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\Github\SwiftUrl\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in … -
Why Django does not import models? [closed]
I have to run a test, but for some reason Django doesn't want to import models. -
After rewriting Django models to remove unecessary primary keys got InvalidCursorName error message
After learning most of my primary keys did not have to be hardcoded in Django models, I decided to remove them all. In order to have Django-admin up and running I had to solve a few issues first, which I did by deleting all migrations files. Once those issues were out of the way, after making migrations and migrating sucessfully again, while in Django admin trying to add data to a particular model, right after clicking the add button I got this error message: Traceback (most recent call last): File "C:\Users\fsoar\urban_forest_box\virtualenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column app_species_catalog_nome_popular.id does not exist LINE 1: ...188_sync_1" NO SCROLL CURSOR WITH HOLD FOR SELECT "app_speci... This lead to a series of exceptions which ledd to another series of exceptions of which the last erros message was: psycopg2.errors.InvalidCursorName: cursor "_django_curs_17188_sync_1" does not exist models.py is a bit long, so I am pasting only the main model of this app, which is the one I was using to add data when it happened, and which speaks for itself regarding my Python/Django skills level :) I would like to understand what is going on, and I imagine it will take several months before … -
Suppress warning about on_delete=CASCADE in Django Admin
I have some foreign keys to auth-User with on_delete=CASCADE. If someone deletes a user, Django displays this warning. Is there a way to avoid this warning? It would be great if I could avoid it for every ForeignKey indiviually. -
Problem with Django — ModuleNotFOundError: No module named 'hellodjango' (app)
(hello is the name of the app) Here's how my files look right now: I'm getting the error in the title whenever I run python manage.py runserver. I also ran python manage.py makemigrations, to confirm what is missing, and got the same result (ModuleNotFoundError: no module named 'hellodjango'). Problem with Django: No module named 'myapp' was similar, but in my case hello is already within myproject so it doesn't apply. Plus, where is 'hellodjango' even coming from? The app is named 'hello'. What am I missing? -
Background image does not want to load in css
I am creating a website in Django. I downloaded a html homepage template design on the internet that I want to improve upon and use for my website. since its been designed it came with a CSS file. now when I try to make the improvements specifically add a background image in one of the elements. it refuses to do so. the other elements respond to the CSS style but the background image refuses too. since I'm using Django i had to set up the static files and 'collect static' which I did but when I set that those pics to my background image in my CSS it refuses. here is the html file & css. html <!DOCTYPE html> <!-- Created by CodingLab |www.youtube.com/c/CodingLabYT--> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> Home </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <!-- Boxicons CDN Link --> <link href= 'https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'> <meta name="viewport" content="width=device-width, initial- scale=1.0"> </head> <section class="home-section"> <div class="main" > </div> the class="main" is where I'm trying to add the background-image too. CSS .home-section .main{ background-image: url('https://www.pexels.com/photo/singer- singing-on-stage-beside-guitar-player-and-bass-player- 167636/'); padding: auto; margin: auto; background-size: 50pc; } @media (max-width: 700px) { .sidebar li .tooltip{ display: none; } } I've tried everything but … -
how to create table with dynamically rows and columns with number field in template django
i want to create dynamically rows and columns table in django with number. like the picture below <table border="1"> {% for i in row %} <tr> {% for x in columns %} <td>????</td> {% endfor %} </tr> {% endfor %} </table> -
No idea where I'm getting NoSuchMethodError: '[]'
I am making a demo login app using python framework-django, graphql, flutter like below. This is a very simple app for a test but I'm getting "NoSuchMethodError='[]'", and I'm already spending a number of hours on this issue. Error messages I am getting are below. The user wants to create an account with dsafds@asdfasd.com and dasdfadsf dart_sdk.js:28087 There was an error! Uncaught (in promise) Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: [0] at Object.throw_ [as throw] (:58141/dart_sdk.js:5348) at Object.defaultNoSuchMethod (:58141/dart_sdk.js:5793) at Object.noSuchMethod (:58141/dart_sdk.js:5788) at callNSM (:58141/dart_sdk.js:5521) at Object._checkAndCall (:58141/dart_sdk.js:5523) at Object.callMethod (:58141/dart_sdk.js:5601) at Object.dsend (:58141/dart_sdk.js:5604) at main._LoginPageState.new._createAccountPressed (:58141/packages/auth_frontend/main.dart.lib.js:1003) at _createAccountPressed.next (<anonymous>) at :58141/dart_sdk.js:39230 at _RootZone.runUnary (:58141/dart_sdk.js:39087) at _FutureListener.thenAwait.handleValue (:58141/dart_sdk.js:34073) at handleValueCallback (:58141/dart_sdk.js:34633) at Function._propagateToListeners (:58141/dart_sdk.js:34671) at _Future.new.[_completeWithValue] (:58141/dart_sdk.js:34513) at async._AsyncCallbackEntry.new.callback (:58141/dart_sdk.js:34536) at Object._microtaskLoop (:58141/dart_sdk.js:39374) at _startMicrotaskLoop (:58141/dart_sdk.js:39380) at :58141/dart_sdk.js:34887 Flutter doctor result is below Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1165], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 31.0.0) [√] Chrome - develop for the web [√] Android Studio (version 4.1.0) [√] VS Code (version 1.60.0) [√] Connected device (2 available) • No issues found! My flutter project … -
How to solve Django form redirect not working?
I created a form. I want to when the user fills the form and then sends it, redirect a specific page. But in my case, the form is saving successfully but does not redirect the page. How can I solve it? views.py def setup_wizard(request): form = SetupForm(request.POST or None) if request.method == 'POST': if form.is_valid(): setup = form.save() setup.user = request.user setup.save() redirect('dashboard') else: form = SetupForm() context = { 'form': form, } return render(request, 'setup_wizard.html', context) dashboard.urls.py urlpatterns = [ path('', dashboard, name="dashboard"), path('setup', setup_wizard, name="setup"), ] mainproject.urls.py urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('dashboard.urls')), ... ] -
How to fix the "detail":"Invalid Token" issue in django_rest_framework
I tried to implement a simple login/register API with django_rest_framework using DRF authToken module and here's my code : models.py class User(AbstractUser): username =models.CharField(max_length=100) email =models.EmailField('email address', unique=True) first_name =models.CharField('First Name', max_length=255, blank=True, null=False) last_name =models.CharField('Last Name', max_length=255, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.models import BaseUserManager User = get_user_model() class UserLoginSerializer (serializers.Serializer): email = serializers.CharField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True) class AuthUserSerializer(serializers.ModelSerializer): auth_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_active', 'is_staff') read_only_fields = ('id', 'is_active', 'is_staff') def get_auth_token(self, obj): token = Token.objects.create(user=obj) return token.key class EmptySerializer(serializers.Serializer): pass class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'first_name', 'last_name') def validate_email(self, value): user = User.objects.filter(email=value) if user: raise serializers.ValidationError("Email is already taken ...") return BaseUserManager.normalize_email(value) def validate_password(self, value): password_validation.validate_password(value) return value class PasswordChangeSerializer(serializers.Serializer): current_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_current_password(self, value): if not self.context['request'].user.check_password(value): raise serializers.ValidationError('Current password does not match ...') return value def validate_new_password(self, value): password_validation.validate_password(value) return value views.py from django.contrib.auth import get_user_model, logout from django.core.exceptions import ImproperlyConfigured from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import AllowAny, … -
Django add a list of other model for cart and product
i am trying to create a shop where users can add products on sale and other users can add them to their cart i can't figure out how can i make a cart contain multiple products and their quantities. class Product(models.Model): name = models.TextField() description = models.TextField() price = models.FloatField() quantity = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Cart(models.Model): #list of products #list of quantities user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
autogenerate form for function based view
i would like to generate a form using my serializer fields for the browsable api. I've checked and i have seen a way to do it for the class based view(Here is an example for class based view), i am currently using a function based view, i want to the same thing done in that link with a function based api_view. Here is my serializer and my views.py @api_view(["POST"]) def store_notice(request): serializer = CreateNoteV2Serializer(data=request.data) if serializer.is_valid(): response = Database.save("Test_notice", notice_data=serializer.data) if response and response.get("status_code") == 201: return Response( data=response, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) class CreateNoticeV2Serializer(serializers.Serializer): creator=serializers.CharField(max_length=100) title = serializers.CharField(max_length=100) text = serializers.CharField(max_length=250) photo_url = serializers.CharField(max_length=50) video_url = serializers.CharField(max_length=50) audio_url = serializers.CharField(max_length=50) published = serializers.BooleanField(default=False) date_added = serializers.DateTimeField(default=timezone.now()) last_modified = serializers.DateTimeField(default=timezone.now()) viewed_by = serializers.CharField(max_length=5000, allow_blank=True) def __str__(self): return f"{self.title}-{self.creator}" -
Use multiple JavaScript package in a script tag(mainly bootstrap 5)
hi this is probably a stupid question but I cant find an answer, I am using vanilla js, without any bundler I need to use the Toast bootstrap class, how do I load a js package into a tag script? <script type="text/javascript" src="../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> If I write my script tag as in the code above, I can use the Bootstrap Toast class in the code inside the script tag, but I can't use any other js package, knowing that I can't use an import statement, I am lost but I'm pretty sure it's basic knowledge. What I need is how to use bootstrap5 inside a script tag without using src, there is no bootstrap object on the window object. Keep in mind that I have already import bootstrap5 css and Js elsewhere on the page, I just need to access objects from the package. -
Updating select dropdowns in Bootstrap modal view
I have tried creating a dynamic modal form where a donation type is dependent on an organisation. I am trying to write up my Javascript so that when an organisation is selected the donation types are modified to match this value. Another thing I should mention is I'm working in Django and have template tags attached to both html and javascript. Here are snippets of my code: Javascript window.addEventListener('load', function() { document.getElementById("id_organisation").onchange = function () { var orgs = document.getElementById("id_organisation"); var dTypes = document.getElementById("id_donation_type"); if (orgs[orgs.selectedIndex].value == '-----') { dTypes.disabled = true; dTypes.options.length = 0; dTypes.value = "-----"; return null; } else { dTypes.disabled = false; var orgNames = orgs.getElementsByTagName("option"); var dTypeNames = eval('{{ donation_types|safe }}'); dTypes.options.length = 0; dTypes.options[0] = new Option("-----", "-----"); for (let i=0; i < dTypeNames.length; i++) { if (dTypeNames[i][0] == $(this).val()) { dTypes.options[dTypes.options.length] = new Option(dTypeNames[i] [1],dTypeNames[i][1]); } } console.log(dTypes); return dTypes; } }); HTML Template <div class="row mb-3"> <label for="id_organisation" class="col-md-4 col-form-label text-end"><strong>{{language.forms.organisationLabelName}}</strong></label> <div class="col-md-7"> <select id="id_organisation" name="organisation" class="form-select {{form_values.errorlist.organisation}}" aria-label="Default select example" value="form.fields.organisation.initial" required> <option value="-----" selected>-----</option> {% for id, organisation in form.fields.organisation.choices %} {% if form.fields.organisation.initial == organisation %} <option value="{{ organisation }}" selected>{{ organisation }}</option> {% else %} <option value="{{ organisation … -
Shared authentication across multiple django sites
I have 3 django sites and they are deployed in 3 subdomains let's say like this: a.example.com b.example.com c.example.com They all have 95% things in similar just uses 3 different database and have user login. Problem is I need to login to all 3 of them, why can't I login to one and share it with other 2 sites? I tried using multiple database/routing as described in Django documentation but I cannot share User model across multiple database. So how does sites like google does it? I login to one of their services and all others automatically log me in. Can someone give me proper guideline how to achieve this? -
What is the difference between 'defs' and 'classes' in views?
I wanted to start a new Django project And when I wanted to create my view section, the question came to me which one should I use now? I want to know when we use defs and classes. -
create function for copy object in django model
i need create function to copy object of my model my code: class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.CharField(max_length=None) author = models.ForeignKey(Author ,on_delete=models.CASCADE) data_created = models.DateTimeField(auto_now_add=datetime.now) def copy(self): new_post = BlogPost.objects.get(id=self.id).update(data_created=datetime.now) new_post.save() return new_post.id class Comment(models.Model): blog_post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) text = models.CharField(max_length=500) def copy in BlogPost class for copy obejcts and create new object and update data_created to now Which after that i have 2 objects but dosent work what can i do? -
Django rest framework how to change: "This field may not be blank." error message
When I am trying to create a new user model, I am getting the following validation error response: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/JSON Vary: Accept { "phone": [ "This field may not be blank." ], "name": [ "This field may not be blank." ] } What I want to do is how to change the error message to a custom one. Here is my user serializer code: from rest_framework import serializers from django.contrib.auth import get_user_model class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = '__all__' read_only_fields = ('last_login',) I already override the validate method but that didn't work neither using this solution: extra_kwargs = {"phone": {"error_messages": {"required": "A valid phone number is required"}}} views.py: class UserList(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer (Custom user) User.py: class User(AbstractBaseUser): """ Custom user model based on phone number as the only identifier """ phone = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=50, blank=False) password = None USERNAME_FIELD = 'phone' objects = UserManager() def __str__(self): return self.name User manager.py: class UserManager(BaseUserManager): """ Custom user model manager where the phone is the unique identifier """ def create_user(self, phone, name, **extra_fields): """ Create and save a User using the given phone number and country … -
Django set random password for user once
I have created an extended User model and a form to register it. Since the form is filled out by an admin and not a user, the UserCreationForm has a random password generator to fill out password1 and 2, then set new password. This is great for a new user, but every time an admin edits the user profile, it will set a new password. I've looked at a few dozen examples here and on big G but can't seem to find a usable solution to know if the user has a password set. I am re-using this form for update view, which is where I don't want the random password to be generated again. I tried doing the same if statement check as the username but it doesn't work the same way as the auth\form.py user.set_password is looking for password1. class EmployeeRegistrationForm(UserCreationForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Email address'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'First name'})) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Last name'})) password1 = None password2 = None class Meta: model = User fields = ['email', 'first_name', 'last_name'] def clean(self): password = User.objects.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') self.cleaned_data['password1'] = password self.cleaned_data['password2'] = password return super().clean() def … -
django-mptt: Unknown column 'goods_category.lft' in 'where clause'
After updating django-mptt from 0.11.0 to 0.13.3, I getting an error Unknown column 'goods_category.lft' in 'where clause' goods/models.py class Category(MPTTModel): ... class Product(models.Model): category = TreeForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) ... goods/views.py categories = Category.objects.add_related_count( Category.objects.filter(is_public=True), Product, 'category', 'count', cumulative=True ) goods/templates/goods/sidenav.html {% recursetree categories %} <li> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}> {{ node.name }} </a> {% if not node.is_leaf_node %} <ul class="nested vertical menu {% if node.slug not in path %}display-none{% endif %}"> <li class="hide-for-large"> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}>Show all </a> </li> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} manage.py makemigrations - No changes detected manage.py migrate - No migrations to apply -
Django Celery, App import error only on production
I have a file structure like this: myapp artist_applications tasks.py tasks celery.py # settings.py INSTALLED_APPS = [ 'myapp.artist_application', ... # celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings.production') app = Celery("tasks") app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() # tasks.py from tasks.celery import app as celery_myapp from django.apps import apps from django.conf import settings import requests @celery_esns.task(name='sample_task') def sample_task(): print('TESTING CELERY') @celery_esns.task(name='publish_artist_task') def publish_artist_task(payload, artist_id): r = requests.post(settings.PUBLISH_URL, json = payload) if r.status_code == 200: apps.get_model('artist_application', 'Artist').objects.filter(unique_id=artist_id).update(published=True) else: raise Exception("Error publishing artist with id: " + artist_id) On development all is running fine when I start Celery with: celery -A myapp.tasks worker -Q celery -l info But on production I run the command (in a virtualenv) and I get the error: django.core.exceptions.ImproperlyConfigured: Cannot import 'artist_application'. Check that 'myapp.artist_application.apps.ArtistApplication.name' is correct. Any ideas where to look? I don't get how 'runserver' is loading the apps differently then wsgi? -
category_id expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager
Looks like error is because of obj.category_id in serializer have something to do with many to many relationship. Error: TypeError: Field 'category_id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager object at 0x0000025BB1C23EE0 Here is my code: modles.py: class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) category_icon = models.CharField(max_length=500, null=True, blank=True) category_image = models.CharField(max_length=500, null=True, blank=True) category_description = models.CharField(max_length=1000, null=True, blank=True) active_status = models.BooleanField(default=True) def __str__(self): return str(self.category_id) +" -"+ str(self.category_name) class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) # parent_id = models.ForeignKey("Services", on_delete=models.CASCADE, default=0) # parent_id = models.IntegerField(default=0) service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) def __str__(self): return str(self.service_id) +" -"+ str(self.service_name) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) views.py: class ServicesList(viewsets.ViewSet): def retrieve(self, request, pk=None): queryset = Category.objects.get(category_id=pk) querysetSerializer = CategoryServiceListSerializer(queryset) return Response({"status":200,"message":"Success","data":querysetSerializer.data}) serialziers.py: class ServiceListSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class VariantServiceSerialzier(serializers.ModelSerializer): # service_id = ServiceListSerializer(many=True) # Getting all service data, #i want only data for perticular … -
Redirect to next post after form submit
I am building a Blog App and I am trying to implement a feature - In which a user can rate blogs in one page and after user click Save Rate then user will redirect to next review blog page and user will ratenext blog. But it is not redirecting to next rate blog page. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) Rating_Choice = [('1','1'), ('2','2')] class Rate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) ratings = models.CharField(max_length=1, choices=Rating_Choice) views.py def rate_blog_post(request, blog_id): obj = get_object_or_404(Blog, pk=blog_id) next_blog = Question.objects.filter(rate__ratings=None) if request.method == 'POST': form = Form(data=request.POST) if form.is_valid(): post= form.save(commit=False) post.user = request.user post.blog = data post.save() # redirect here return redirect('rate_blog_post', pk=data.id) else: form = Form() context = {'obj':obj, 'form':form} return render(request, rate_blog_post.html', context) Form is working fine, it is saving the ratings What have i tried so far ? : I have tried using a next_blog like :- return redirect('rate_blog_post', rate_blog_post=question_id) But it showed Reverse for 'rate_blog_post' with keyword arguments '{'pk': 2}' not found I have tried many times but did't worked for me. I will really appreciate your Help. Thank You So, i made a choices of reviews. And User will redirect …