Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin Sidebar Bug
I've been having this weird issue with my Django site for a few weeks now that I can't quite figure out. Whenever I go to the admin page on my local machine (DEBUG=True) it's completely unusable because the sidebar is filling the entire screen as pictured below: This began happening when I upgraded to Django 3.1 if that matters (this project started on 2.1) This does not happen on my live/production site. When I switch DEBUG=False on my local machine it works as expected as well however I can't figure out for the life of me what's causing this. I've tried other browsers as well to no avail. -
Django: issue with template path for tenant
I have an app where depending on its category, a tenant is either directed to the app (and templates) at /dashboard/templates/dashboard or /dashboard2/templates/dashboard2. somehow, for dashboard2, the app is not found by django and it tries to find those templates under dashboard. here is a dashboard2/views.py @method_decorator(login_required, name='dispatch') class SupplierPage2(LoginRequiredMixin,APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_ress', None) print(query) context = {} #if query and request.method == 'GET': Supplier = supplier2.objects.filter(supplier = query) print(Supplier) labels = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(labels) default_items = Item2.objects.filter(fournisseur = query).values_list('number_of_sales', flat=True)[:10] print(default_items) label1s = Item2.objects.filter(fournisseur = query).values_list('reference', flat=True)[:10] print(label1s) default_item1s = Item2.objects.filter(fournisseur = query).values_list('number_of_orders_placed', flat=True)[:10] print(default_item1s) context.update({'Supplier' : Supplier, 'labels':labels, 'default_items':default_items,'label1s':label1s, 'default_item1s':default_item1s}) return render(request, 'Supplier2.html',context) and the error: TemplateDoesNotExist at /Supplier2.html Supplier2.html Request Method: GET Request URL: https://uname.website.net/Supplier2.html Django Version: 3.0.5 Exception Type: TemplateDoesNotExist Exception Value: Supplier2.html and the traceback: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/ubuntu/website/dashboard/templates/dashboard/dashboard2/templates/dashboard2/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/customers/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django/contrib/auth/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/dashboard/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/tenantlogin/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/website/uploadfiles/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django_tenants/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/rest_framework/templates/Supplier2.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/ubuntu/exo/lib/python3.6/site-packages/django_tables2/templates/Supplier2.html … -
GraphQL queries naming when performing CRUD operations on Django models
When performing CRUD operations on Django models will it best practice to name queries like createModelName, updateModelName, deleteModelName? -
Error importing Path from unipath in Django
I am making a program with Django and following some tutorials, unipath is used for the routes and when calling it in the python configuration file it sends me the following error from unipath import Path ValueError: source code string cannot contain null bytes I still do not understand why, if when verifying that it is installed, it does appear in the environment and it seems that the error appears in that line when importing -
Using django objects.filter to filter on db with a datetime field but for date only and based on local time not UTC
I have a model that created a simple table, the checkin date and the checkout date are datetime fields that store items in UTC format from a django form. I want to send a report later on of everyone who checked in or checked out for the whole day (Send out the report like at 11:55pm local time) the problem is that a full day local time is two days in UTC (there is a roll over) not sure how to handle that nad get the data I need using django: What I am trying to do: def select_users(): currentTime = timezone.now() loggedIn = OnSiteLog.objects.filter(autoCheckin=False, checkIn = currentTime, checkOut = currentTime).count() #just a countfor now to test print(str(loggedIn)) The problem is two fold: I believe that timezon.now() is getting a time also of like midnight. So my equals will fail. I really want to filter on day only and ignore time stamp. (Without changing the model though) I want that data still just not for this report. I had something almost similar working in SQLite where I could cast the field to just a DATE not sure how to do that in django. Then the second issue is that 5am … -
Web development, start parsing from web site
everyone. I am new in web development.I have question. Imagine, I have work web site written om Django. I would like to make new app for parsing other web site. When task ends result sends to user via email. Is it possible and ok, if server will parse it? How it will work when several users start parsing in one moment of time? Every task will be handled parallel? Or should I create something like queue and every task will be handled one after another. What's better and correct? Could you suggest good solve or ideas for it? -
I'm getting an File not found error in the command pyRAPL.setup() while using the pyRAPL library in python
I'm trying to install and use the pyRAPL package library in Python in-order to measure the power, energy CO2 emission of a code on my laptop. I'm getting a FileNotFoundError: [Errno 2] No such file or directory: '/sys/devices/system/cpu/present' while using the pyPAPL.setup() command. What may be the problem ? I have installed the pyRAPL package in through my Jupiter Notebook. The package is installed, it can be imported as well but I'm getting an error. Please let me know where I'm going wrong ?. !pip install pyRAPL import pyRAPL pyRAPL.setup() FileNotFoundError Traceback (most recent call last) in ----> 1 pyRAPL.setup() ~\anaconda3\lib\site-packages\pyRAPL\pyRAPL.py in setup(devices, socket_ids) 37 :raise PyRAPLBadSocketIdException: if the given socket in parameter doesn't exist 38 """ ---> 39 pyRAPL._sensor = Sensor(devices=devices, socket_ids=socket_ids) ~\anaconda3\lib\site-packages\pyRAPL\sensor.py in init(self, devices, socket_ids) 57 for device in tmp_device: 58 try: ---> 59 self._device_api[device] = DeviceAPIFactory.create_device_api(device, socket_ids) 60 self._available_devices.append(device) 61 except PyRAPLCantInitDeviceAPI: ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in create_device_api(device, socket_ids) 184 """ 185 if device == Device.PKG: --> 186 return PkgAPI(socket_ids) 187 if device == Device.DRAM: 188 return DramAPI(socket_ids) ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in init(self, socket_ids) 135 136 def init(self, socket_ids: Optional[int] = None): --> 137 DeviceAPI.init(self, socket_ids) 138 139 def _open_rapl_files(self): ~\anaconda3\lib\site-packages\pyRAPL\device_api.py in init(self, socket_ids) 66 :raise PyRAPLBadSocketIdException: the machine where is … -
Django 3.1.1 NOT NULL constraint failed with Date
I'm getting this error on Django 3.1.1 while trying to define a model with an optional date field: class Tickets(models.Model): subject = models.CharField(max_length=255) content = models.TextField(blank=True) category = models.ForeignKey("TicketCategories", on_delete=models.PROTECT, related_name='ticket_category') openDate = models.DateTimeField(auto_now_add=True) closeDate = models.DateTimeField(blank=True, null=True) class Meta: verbose_name_plural = "Tickets" def __str__(self): return f"{self.id} {self.subject}" In this case closeDate should accept null and the user should be able to leave it empty on the admin panel. Unfortunately I am getting this error: NOT NULL constraint failed: api_tickets.closeDate Am I doing something wrong? -
Registration - sequence item 0: expected str instance, NoneType found
Django Version: 3.0.8 - Python Version: 3.7.8 I discovered an error on my Django site recently. When a user wants to create an account it returns this error: sequence item 0: expected str instance, NoneType found Operation: account creation (check if username does not already exist on the DB) creation user Active = False sends an email for confirmation of account creation. Error appears in the first step, the account is created (Active = False), no email is sent and error displayed. Traceback (most recent call last): File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/eodj89/DjangoPro/user/views.py", line 45, in signup user.save() File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/eodj89/DjangoPro/user/models.py", line 479, in create_user_profile UserProfile.objects.create(user=instance) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/eodj89/virtualenv/DjangoPro/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 433, in create obj.save(force_insert=True, using=self.db) File "/home/eodj89/DjangoPro/user/models.py", line 346, in save … -
How can I upload profile picture in user extended model in Django
I am not getting any error while uploading cover image to the Django's User extended model but I cannot see what is wrong I'm doing because it's not giving any error and not even updating my model. Here I am giving the source code forms.py class UpdateCoverImageForm(forms.ModelForm): class Meta: model = Memer fields = ['cover'] views.py def profile(request, username): try: user = User.objects.get(username=username) user_ = User.objects.filter(username=username) memer = Memer.objects.filter(user=user_[0].id) except User.DoesNotExist: raise Http404("Memer does not exist.") context = { 'user_': user_, 'memer': memer, } if request.method == "POST": bioForm = EditBioForm(data=request.POST, instance=request.user.memer) coverImageForm = UpdateCoverImageForm(data=request.FILES, instance=request.user.memer) if bioForm.is_valid(): memer_ = bioForm.save(commit=False) memer_.save() messages.success(request, "Bio successfully updated your profile") return redirect('/profile/'+user_[0].username) elif coverImageForm.is_valid(): memer_ = coverImageForm.save(commit=False) memer_.save() messages.success(request, "Cover Image has been updated successfully!") # print(coverImageForm) return redirect('/profile/'+user_[0].username) else: messages.error(request, "Something wrong happend") return redirect('/profile/'+user_[0].username) return render(request, 'profile.html', context) profile.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ UpdateCoverImageForm }} <input type="submit" value="save"> </form> -
The order of inherited classes matters in Python?
I came across this error in my django application after hitting submit on a create or edit form: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.. This was confusing because I have a get_success_url passed down through inheritance. To be clear, I have found the issue, but have no earthly idea why my solution worked. Here was the code causing the error inside .../views.py: class FormViews(): model = Ticket form_class = TicketForm def get_success_url(self): return reverse('tickets:index') class TicketCreate(CreateView, FormViews): template_name = 'tickets/ticket_create_form.html' model = Ticket form_class = TicketForm class TicketUpdate(UpdateView, FormViews): model = Ticket form_class = TicketForm template_name_suffix = '_update_form' I created the FormViews class so there would not be any repeated code for the model, form_class, and get_success_url. I was able to resolve this error by switching the parameters in my function definitions: class TicketCreate(CreateView, FormViews) became class TicketCreate(FormViews, CreateView) class TicketUpdate(UpdateView, FormViews) became class TicketUpdate(FormViews, UpdateView) This fixed it. Now I redirect to the index page without any issues. Why is it that the get_success_url is recognized after switching the listed parent classes? I would have thought that the attributes and functions are inherited and recognized by Django regardless … -
How to create a dynamic choice field without refreshing the server? Django
I'm creating a form which takes in one of their fields the list of categories the user created. But i'm having problems with that, the list is working but if i create a new category, it will not be shown in the form field until i refresh the server. So how can i make this without refreshing the server? This is my models: class Category(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) thumb = models.ImageField(default='default_notes.png', upload_to='notes_pics') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:category-detail', kwargs={'pk': self.pk}) def __str__(self): return 'Notes: {}'.format(self.status) class Meta: verbose_name = 'Category' ordering = ['created_date'] class Notes(models.Model): PR = 'PRIVATE' OPTIONS_CHOICES = ( ('PRIVATE', 'PRIVATE'), ('PUBLIC', 'PUBLIC'), ) UN = 'ESCOGE UNA CATEGORIA' CAT_CHOICES = Category.objects.all().values_list('title','title') title = models.CharField(max_length=100) content = models.TextField(blank=True) created_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name = 'Category', choices=CAT_CHOICES, null=True, default=UN) notes_options = models.CharField(max_length=40, choices=OPTIONS_CHOICES, default=PR) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:notes-detail', kwargs={'pk': self.pk}) def __str__(self): return 'Notes: {}'.format(self.status) Thank you very much for your help! -
Can't deploy Django application to AWS wsgi.py
I'm deploying from codepiple with git and I keep getting this error for the last 2 hours been looking for solutions but I'm still enctountering it Target WSGI script not found or unable to stat: /opt/python/current/app/invgen/wsgi.py -.ebexstentions django.config -django -django wsgi.py manage.py -venv .gitignore req.txt django.config looks like this : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django.wsgi:application I also tried option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django/wsgi.py And option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django/django/wsgi.py -
Adding fonts to reportlab in docker container
I have an application running in 3 separated containers. One for django app, one for postgresql and the third one is for nginx. In my docker-compose file I have volume for static files where I put my font.ttf file. I checked the container and the file is there, however it is not being loaded. Here is the settings for web container: web: image: ashowlsky/foodgram:latest restart: always command: gunicorn foodgram.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/code/static/ - ./media:/code/media/ ports: - "8000:8000" depends_on: - db env_file: - ./.env And here is the part of view: pdfmetrics.registerFont(TTFont('OS', '/code/static/OpenSans-Regular.ttf')) What do I do wrong? -
Django TypeError Field 'id' expected a number but got <class 'account.models.User'>
Error: TypeError: Field 'id' expected a number but got <class 'account.models.User'>. I have been reading the authentication documentation and I keep getting that error. I have tried a few different permutations of this but I'm really not sure what is going wrong other than its obviously a type error. The end goal is to just return the 'id' and 'email' of the newly created user, along with the token, I haven't been able to test the token returning yet, because of this error, but I imagine it should be good. What is working though is it is successfully posting a new user to the database with a token in another table with a matching key and now I have about 50 users from just testing and messing around. Side note I have overridden the default User Django sets you up with, but I followed the documentation so that code should be solid, but if need I can obviously post it Views.py from rest_framework import status from .models import User from .serializers import UserSerializer, RegisterSerializer from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework.authtoken.models import Token @api_view(['POST',]) def RegisterAPI(request): if request.method == 'POST': serializer = RegisterSerializer(data = request.data) if serializer.is_valid(raise_exception=True): … -
Django Registration - errors messages don't appears
I try to understand why errors don't appears on my template. I'm using classical registration with checks (email and username). If email already exists = error and the same for username. The thing is error appear if it's about password (ex. password are not the same, ...) but for email and username nothing appears. template <form method="post" class="user-log"> {% csrf_token %} {% if form.errors %} <div class="alert alert-warning alert-dismissible fade show" role="alert"> Oupss <a data-toggle="collapse" href="#collapseExample" class="alert-link" style="text-decoration:none;">something wrong</a>! <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true" style="color: #ffd14c;">&times;</span> </button> <div class="collapse" id="collapseExample"> {% for field in form %} {% if field.errors %} <strong>{{ form.label }}</strong> {{ field.errors|striptags }} {% endif %} {% endfor %} </div> </div> views def signup(request): if request.method == 'GET': return render(request, 'register.html') if request.method == 'POST': form = RegisterForm(request.POST) # print(form.errors.as_data()) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your registration' message = render_to_string('user_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return redirect ('user:user_registration_process') else: form = RegisterForm() return render(request, 'register.html', {'form': form}) forms class RegisterForm(UserCreationForm): username = forms.CharField(max_length=50) email = forms.EmailField(max_length=50) password1 = forms.CharField() … -
Video-chat using Django or Python
I want to build a video-chat using Django. Are there any 'batteries included' solutions? If there are no - what libraries or technologies should I use? -
How can I see the buttons in the navbar?
I'm currently coding my first django website and I'm stuck with the navbar. Well, I've downloaded from bootstrap a navbar just like this one. However, when i run the server, the navbar looks like this. I'd like to see the buttons in the navbar. Here's the code: <nav class="navbar fixed-top navbar-light" style='background-color: snow;'> <a class="navbar-brand" href="#"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-link active" href="#">Home <span class="sr-only">(current)</span></a> <a class="nav-link" href="#">Features</a> <a class="nav-link" href="#">Pricing</a> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </div> </div> </nav> </nav> -
deploying Django project -beginner
please help me I'm a beginner and this is the first time I want to deploy a website I want to use pythonanywhere but I don't know which folders of my project I have to upload hm trying to deploy the site for hours but going nowhere please help this is my source : inside my main project, I have this folder please help me how can i deploy my site -
Sending django single api logs via email
In my django project, I have many REST APIs. But I want to send the logs only for a specific API over email. Also, we have our own project(API) for sending emails which we use in all our django projects for sending the email. I have 2 questions here - how can I send logs only for a specific django api, and not whole project ? How to use our email api(REST) for sending the email if using the logging settings https://docs.djangoproject.com/en/3.1/topics/logging/ ? Thanks in advance. -
DJANGO, Calling one class from another Class by urls
I have a file that n ame is tes.py and in this file has a program class . and program class changes sqlite.db table and processes the data and that give me a table that I need to . so I want make the url for this and when I call the url, the process begin in this class and the the tables will change . I defined url.py : from django.urls import path , include from .tes import Program urlpatterns = [ path('newgp/', Program, name='Program' ), ] but I dont know how to write this line: path('newgp/', Program, name='Program' ) when i run this code i get this error: TypeError: Program() takes no arguments -
Django admin login not working when creating new User structure
I am trying to create a new User model with 'AbstractBaseUser' and 'BaseUserManager' but for soemw reason now when creating a new super user, logging in does not work and shows this error: Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive. Error Image here. Here is my code. models.py from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager from django.db import models class UserManager(BaseUserManager): def create_user(self, email, firstName, lastName, phoneNumber, is_active=True, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address.") if not password: raise ValueError("Users must have a password.") user_obj = self.model( email=self.normalize_email(email) ) user_obj.set_password(password) user_obj.save(using=self._db) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active return user_obj def create_staffuser(self, firstName, lastName, phoneNumber, email, password=None): user = self.create_user( email, firstName, lastName, phoneNumber, password=password, is_staff=True, ) return user def create_superuser(self, firstName, lastName, phoneNumber, email, password=None): user = self.create_user( email, firstName, lastName, phoneNumber, password=password, is_staff=True, is_admin=True ) return user class User(AbstractBaseUser): objects = UserManager() firstName = models.CharField(max_length=255, unique=True, blank=True, null=True) lastName = models.CharField(max_length=255, unique=True, blank=True, null=True) nickName = models.CharField(max_length=255, unique=True, blank=True, null=True) phoneNumber = models.IntegerField(unique=True, blank=True, null=True) email = models.EmailField(max_length=255, unique=True) confirmed_email = models.BooleanField(default=False) confirmed_phoneNumber = models.BooleanField(default=False) timeStamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) … -
How do I write script to send the reports on my mail
I am building a Django report page, and whenever user reports something, I want the message to be sent on my mail box. How can I achieve this using either python or javascript. -
Can I access the choice category in a Django model?
Let's say I have this class PaymentType(models.Model): INSCRIPTION = 'INS' JANUARY = 'JAN' FEBRUARY = 'FEB' MARCH = 'MAR' APRIL = 'APR' MAY = 'MAY' JUNE = 'JUN' JULY = 'JUL' AUGUST = 'AUG' SEPTEMBER = 'SEP' OCTOBER = 'OCT' NOVEMBER = 'NOV' DECEMBER = 'DEC' NAME_CHOICES = [ ('Months'), ( (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March'), (APRIL, 'April'), (MAY, 'May'), (JUNE, 'June'), (JULY, 'July'), (AUGUST, 'August'), (SEPTEMBER, 'September'), (OCTOBER, 'October'), (NOVEMBER, 'November'), (DECEMBER, 'December') ) ('Others'), ( (INSCRIPTION, 'Inscription'), ) ] amount = models.FloatField() payment_type = models.CharField(max_length=3, choices=NAME_CHOICES) Is there a way that I can access the 'Months' or 'Others' category? For example I would like the user to be able to add more payment types to 'Others' or add/update the amount for all the 'Months' -
Django Form 'WSGIRequest' object has no attribute 'seller'
I'm doing a rating system inside of a group (channel) of two users. How I can automatically fill seller? As I do for consumer & channel. I use self.request.user for consumer because only consumer can give a grade. Pleas be kind, even if this question appears really simple. class ChannelReview(generic.DetailView, FormMixin): model = Channel context_object_name = 'channel' template_name = 'channel_review.html' form_class = ChannelRatingForm def get_context_data(self, **kwargs): context = super(ChannelReview, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): #seller = form.instance.channel = self.object form.instance.consumer = self.request.user form.instance.seller = seller form.save() return super(ChannelReview, self).form_valid(form) else: return super(ChannelReview, self).form_invalid(form) models.py class Channel(models.Model): consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True) name = models.CharField(max_length=10) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller") ... class Rating(models.Model): channel = models.OneToOneField(Channel,on_delete=models.CASCADE,related_name="rating_channel") consumer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_consumer') seller = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.CASCADE,related_name='rating_seller') is_rated = models.BooleanField('Already rated', default=True) comment = models.TextField(max_length=200) publishing_date = models.DateTimeField(auto_now_add=True) ratesugar = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return self.channel.name