Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF reverse action url from viewset
I have an issue reversing the URL of ViewSet actions in the DRF my codes are below, I try some methods to reverse URLs but also you can see it's not working for me view.py class Device_API(ViewSet): def list(self, request) -> Response: ... def update(self, request, pk) -> Response: ... def create(self, request) -> Union[Response, Http404]: ... def destroy(self, request, pk) -> Union[Response, None]: ... @ action( detail=False, methods=["GET"], url_path=r"filter/(?P<type>\w+)", url_name="filter_type", ) def filter(self, request, type) -> Union[Response, Http404]: ... @ action(detail=True, methods=["GET"], url_name="data") def data(self, request, pk) -> Union[Response, Http404]: ... urls.py from rest_framework.routers import DefaultRouter, SimpleRouter from .views import Device_API Router = DefaultRouter() app_name = "api" Router.register("device", Device_API, basename="Device") urlpatterns = Router.urls and I try to reverse the URL like below but I get an error view = Device_API() view.basename = "Device" view.request = None url = view.reverse_action('filter') or url = reverse('Device-filter') Error django.urls.exceptions.NoReverseMatch: Reverse for 'Device-filter' not found. 'Device-filter' is not a valid view function or pattern name. I and also tried this url = reverse('api:Device-filter') Error Traceback (most recent call last): File "/home/nova/Documents/projects/webserver/ENV/lib/python3.8/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'api' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Django pass Varibals brack the url
Hi there I'm following a youtube tutorial of Django 3.0 to learn but I'm using Django 4.0 something and in this particular code I'm getting an error the code in getting the error on urlpatterns = [ path('update_order<str:pk>', views.updateorder, name ='updateorder'), ]` the code doesn't give me an error urlpatterns = [ path('update_order', views.updateorder, name ='updateorder'),] so if I try to pass any veribals its give me error of "NoReverseMatch at / Reverse for 'updateorder' with no arguments not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)\\Z']" my views def updateorder(request,pk): form = OrderForm() context = {"form":form} return render(request, 'order_form.html', context) if you need any other information please ask in the comment. Thanks in advance -
Get user input values in a Mathquill environment with a Form
I just started using Mathquill in my Django app. I want to get a user input value from Django.views.py. Until now, I don't have a way to get these input values. E.g in the code below, how do I place the Mathquill expression inside a form such that when a user clicks submit, I get the values of x and y from my views.py <span id="fill-in-the-blank"> \sqrt{ \MathQuillMathField{x}^2 + \MathQuillMathField{y}^2 }</span> <input type="submit"/> <script> var fillInTheBlank = MQ.StaticMath(document.getElementById('fill-in-the-blank')); fillInTheBlank.innerFields[0].latex() // => 'x' fillInTheBlank.innerFields[1].latex() // => 'y' val = $(document.getElementById("fill-in-the-blank")); </script> -
Third Party AP in DRF
Im trying consulting http://ip-api.com/json/ with parameter QUERY,like localhost:8000/api?24.48.0.1 but only received ''"query": [ "This field is required."'' views.py: @api_view() def my_view(request): input = MyInputSerializer(data=request.GET) input.is_valid(True) tp_api = "http://ip-api.com/json{}".format(input.data['query']) response_data = requests.get(tp_api).json() my_serializer = MyOutputSerializer(data=response_data, many=True) my_serializer.is_valid(True) return Response(data=my_serializer.data) Serializers.py class MyInputSerializer(serializers.Serializer): query = serializers.CharField() class MyOutputSerializer(serializers.Serializer): query = serializers.CharField() country = serializers.CharField() Urls.py from django.urls import path from . import views urlpatterns = [ path('api',views.my_view), ] -
Django "o termo '/usr/bin/env python' não é reconhecido como nome de cmdlet..." manage.py [closed]
Estou aprendendo Django e, quando tento rodar o arquivo manage.py, esse erro aparece: /usr/bin/python : O termo '/usr/bin/python' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente. No linha:1 caractere:1 /usr/bin/python "c:\Users\mathr\Desktop\Coding Projects\Django\hello_ ... + CategoryInfo : ObjectNotFound: (/usr/bin/python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Estou usando uma virtualenv e não mexi em nada no código original do arquivo, apenas dei runserver no terminal. Alguém sabe o que fazer? -
Django MySQL - Setting an index on a Textfield
I have a database of articles that I want to search through. I had been using normal Django ORM to search, which was getting way to slow and then I got to know a little about Indexes in Django. I'm using MySQL and I now know that with MYSQL I cannot put an index field into a TextField as described here in this stack question which I was facing. However in my case I can't change this to CharField. I was reading through the MyQSL Docs which stated MySQL cannot index LONGTEXT columns specified without a prefix length on the key part, and prefix lengths are not permitted in functional key parts. Hence I was of the understanding that since TextField in Django is LONGTEXT for MYSQL, I came across this Django-MySQL package here and thought that using this if I could change the LONGTEXT to a MEDIUMTEXT using this package, this might get resolved. So my updated model I did this class MyModel(Model): ........ document = SizedTextField(size_class=3) However, I still see the same error while applying python manage.py makemigrations django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'document' used in key specification without a key length") How can I go about resolving this? -
How do you pass data into a Django form?
I'm using Django 4.0 and I'm trying to create a web app where the user selects a choice from a dropdown Django form. However, the choices will vary depending on the question and I want the form to be able to adapt to this. This is what I have in forms.py: class QuestionAnswerForm(forms.Form): def __init__(self, q_id, *args, **kwargs): self.q_id = q_id super(QuestionAnswerForm, self).__init__(*args, **kwargs) q_id = self.q_id # this line throws an error question = Question.objects.get(pk=q_id) choice = forms.ChoiceField(choices=get_choices(question)) However, I get the error: name 'self' not defined. I just want to know an easy way to pass the question id to the form so that the get_choices function can then return the choices that need to be displayed on the form. In views.py, the start of my view for the question sets the form in this way: def question_detail_view(request, q_id): print(f"Question id is {q_id}") form = QuestionAnswerForm(request.POST or None, q_id=q_id) -
django admin page disable def response_change
I would like to replace function of save button in admin page. Default is update, but I would like to insert new value to db. models.py class user_with_full_info(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) branch = models.ForeignKey(branch, on_delete=CASCADE) team = models.ForeignKey(team, on_delete=CASCADE) position = models.ForeignKey(position, on_delete=CASCADE) date = models.DateTimeField(default=now) add_button.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} <!-- hide default save button --> <!-- {{ block.super }} --> <div class="submit-row"> <input type="submit" value="Save" name="_change_position"> </div> {% endblock %} admin.py class UserFullInfoAdmin(admin.ModelAdmin): list_display = ('get_salary_number', 'user', 'branch', 'team', 'position', 'get_active') change_form_template = "information/user_button.html" def response_change(self, request, obj): if "_change_position" in request.POST: user_with_full_info.objects.create( user = user.objects.get(id = request.POST['user']), branch = branch.objects.get(id = request.POST['branch']), team = team.objects.get(id = request.POST['team']), position = position.objects.get(id = request.POST['position']) ) return HttpResponseRedirect(".") return super().response_change(request, obj) This code is working fine with insert new value, BUT it's always update the selected value too. How can I disable IS_POPUP_VAR in response_change function to not update selected value. -
Using OAuth in an Android app with custom
I am developing an Android app with a REST API. The REST API needs authentication for security. I would like to use Google's OAuth2 provider since I the client will be on Android. I don't want to store passwords myself. I'm trying to understand how the flow should work at a conceptual level. Authenticate to OAuth2 services describes how to get an OAuth token in the Android app. But then what? Do I need a route that accepts this token? I am implementing the API with Django and Django Rest Framework. I found python-social-auth to implement OAuth flows for the API. It works great when I test manually in a browser going to http://localhost:8000/social/login/google-oauth2/. When I request that URL with a HTTP client, it returns HTML for a Google login page. In the Android app, should I load that in a WebView? And then what? That doesn't seem quite right to me since I'd rather use the Android OAuth API that I linked earlier. What am I missing here and how do I solve this? -
Why the name of the form variable is being displayed? django
I have this form form.py from django import forms from .models import User LETTERS= [ ('a', 'a)'), ('b', 'b)'), ('c', 'c)'), ('d', 'd)'), ('e', 'e)'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=LETTERS) and this view views.py from django.shortcuts import render from questoes.models import Questao from .forms import CHOICES # Create your views here. def prova(request): questoes = Questao.objects.order_by('?')[:5] form = CHOICES if request.method=='POST': dados = { 'questoes': questoes, 'form':form(request.POST) } return render(request,'provas/prova.html', dados) else: dados = { 'questoes': questoes, 'form':form } return render(request,'provas/prova.html', dados) I can't figure out why the name NUMS (the form's variable name) is being rendered in the HTML. :( -
Deselection in django forms
Is that possible to deselect selected object in forms.SelectMultiple in Django? My model instance accept the field be None, but when in form i select some object I can't deselect it. -
Django FieldError : Cannot resolve keyword 'total_sales' into field
This is the query I am running to get Total Sales for each party. Party.objects.annotate(total_sales=Sum('sales__salestransaction__total_cost')) It shows correct results. But when I try to apply in my view with get_queryset, it is not working and shows a FieldError which is: Cannot resolve keyword 'total_sales' into field. Choices are: party_address, party_id, party_name, party_phone, sales My View class PartyListView(ListView): paginate_by = 2 model = Party template_name = 'mael/parties.html' def querystring(self): qs = self.request.GET.copy() qs.pop(self.page_kwarg, None) return qs.urlencode() def get_queryset(self): qs = super().get_queryset() if 'q' in self.request.GET: search_txt = self.request.GET['q'] qs = qs.filter(party_name__icontains=search_txt).annotate(total_sales=Sum('sales__salestransaction__total_cost')) return qs.order_by('total_sales') def get(self, request): form = PartyForm() party_list = self.get_queryset() qrstring = self.querystring() paginator = Paginator(party_list, 5) page_number = request.GET.get('page') party_list = paginator.get_page(page_number) return render(request, self.template_name, {'form': form, 'party_list': party_list, 'querystring': qrstring}) Models class Party(models.Model): party_id = models.BigAutoField(primary_key=True) party_name = models.CharField(max_length=128) party_phone = models.CharField(max_length=128) party_address = models.CharField(max_length=128) def __str__(self): return self.party_name class Sales(models.Model): invoice_no = models.BigAutoField(primary_key=True) invoice_date = models.DateField(default=date.today) party = models.ForeignKey(Party, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) class SalesTransaction(models.Model): sales = models.ForeignKey(Sales, on_delete=models.CASCADE) item_qty = models.PositiveIntegerField(default=0) total_cost = models.PositiveIntegerField(default=0) def __str__(self): return self.item_name What is a problem with the get_queryset function and how can I solve this error? Please help. -
Create database using docker-compose django
I have a Django application that is dockerized and using Postgres for the database and I want that every time someone builds the docker-compose so the app should create the database inside db container if the database is not already existed there, and also I have some static data inside some tables and I want to insert that data if the same data doesn't exist in the tables. docker-compose.yml version: "3.8" services: db: container_name: db image: "postgres" restart: always volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - dev.env ports: - "5432:5432" app: container_name: app build: context: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./core:/app - ./data/web:/vol/web env_file: - dev.env ports: - "8000:8000" depends_on: - db volumes: postgres_data: Dockerfile FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # COPY ./core /app WORKDIR /app EXPOSE 8000 COPY ./core/ /app/ COPY ./scripts /scripts RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt && \ adduser --disabled-password --no-create-home app && \ mkdir -p /vol/web/static && \ mkdir -p /vol/web/media && \ chown -R app:app /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts USER app CMD ["/scripts/run.sh"] /scripts/run.sh #!/bin/sh set -e ls -la /vol/ ls -la /vol/web whoami python manage.py … -
Error The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'
I have 3 model. 2 model for creating user. 1 model get primary key from user model my model class CustomUser(AbstractUser): user_type_data=((1,"AdminHOD"),(2,"Managers"), (3,"Teamleaders"),(4,"Admins"),(5,"Supports"), (6,"Callers"),(7,"Fields"),(8,"Tester") ) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) class Callers(models.Model): id=models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) gender=models.CharField(max_length=225) profile_pic=models.FileField() address=models.TextField() team_id=models.ForeignKey(ListofTeam,on_delete=models.CASCADE,default=1) group_id=models.ForeignKey(ListofGroup,on_delete=models.CASCADE,default=1) objects=models.Manager() class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="admin.username") my error when i makemigrations testwebsite.report.nhan_vien: (fields.E312) The to_field 'admin.username' doesn't exist on the related model 'testwebsite.Callers'. I try username only class report(models.Model): id=models.AutoField(primary_key=True) so_hd=models.ForeignKey(testimport, on_delete=models.CASCADE, to_field="so_hd") nhan_vien=models.ForeignKey(Callers, on_delete=models.CASCADE, to_field="username") It still error testwebsite.report.nhan_vien: (fields.E312) The to_field 'username' doesn't exist on the related model 'testwebsite.Callers'. How can I get username as to_field in model Thanks for your reading -
How to add the same data to list of users?
Let us suppose the I have list 10000 Users in my website And there field "new_notification" (just for example) Now i want a certain notification to the every user in the list not for in the other users data. let us suppose list user = ['user1','user2',] data= 'new post is out' Now one way is this for i in user: i.data = data i.save() But according this is time consuming for 10000 running the for loop is not good according if i am wrong then please correct. I hope you understand my problem Is there more fast alternative of for loop? Thanks in advance. -
when am working on a formA, How i can get a value of a field from modelB after select a Many2Manyfield of a modelB on Django
I have modelA that contain some fields,one of the those fields is type "ManyToManyField"(call another modelB that has 3 fields, one of them defined as"sigma"), the story that in the formA I want when i select option from the ManyToManyField(modelB) , I get the value of sigma of this ManyToManyField selected. enter image description here ---> I have tried to do that but always i get the last value of the sigma(get the sigma from last example added on the admin page of the modelB) entered on the admin page and not the value of sigma that correspond the many2manyfield selected by the user. **PS:**the data of the modelB i have added it throw the admin page to be displayed when i work with the formA on my localhost. Here is the code in the models.py: code of the ModelA: class ModelA(models.Model): description = models.CharField(verbose_name=" Description ", max_length=60) modelelement = models.CharField(verbose_name=" Mode Element ", max_length=60) element = models.ManyToManyField(ModelB) code of the ModelB in the models.py: class ModelB(models.Model): designation = models.CharField(verbose_name="designation", max_length=60) resistance = models.CharField(verbose_name='resistance W', max_length=50) sigma = models.FloatField(verbose_name='Sigma', max_length=50) def __str__(self): return self.designation + " " + self.resistance in forms.py : class ModuleForm(ModelForm): class Meta: model = ModelA fields … -
Django Authentication without Django Admin functionality
I am working on a Rest API using Django Rest Framework. I want to add registration and authentication, but I don't know how to do it. There is a bunch of methods of doing that in official docs, but they all seem to be using Django Admin functionality (by inheriting their User classes from AbstractBaseUser), which I don't want to use. I want to do it from scratch, have my own Person class which does not use any Django Admin functionality. I am planning to disable Django Admin in my project. Is there a way to do that? -
Django - How can I send absolute url for a model from views.py to another python script?
I'm pretty new to Django and am trying to make a breadcrumbs module. It works pretty well, except I'm having trouble trying to link back to URLs which need a primary key. I've got a breadcrumbs.py file which simply looks up the list of keywords in a list and adds HTML in the form of list items. The problem is to link back to, for example, the profile of a user, I need to send the absolute_url for that profile to breadcrumbs.py. However, since I'm calling the get_breadcrumbs function from within views.py, I can't directly send the request object as an argument in extra context. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.ForeignKey(Role, on_delete=models.SET_DEFAULT, blank= True, default=Role.get_default) image = models.ImageField(default='profile_pics/default.png', upload_to = 'profile_pics') def __str__(self) -> str: return f"{self.user.username}'s profile" def get_absolute_url(self): return reverse("profile", kwargs={"pk": self.pk}) views.py: from apps.backend_utils.breadcrumbs import get_breadcrumbs class ProfileView(LoginRequiredMixin, DetailView): model = Profile template_name = 'users/users_profile.html' extra_context = { 'breadcrumbs': get_breadcrumbs(['home']), 'page_title' : 'Profile', } breadcrumbs.py: from django.urls import reverse_lazy breadcrumb_lookup = { 'home': { 'title' : 'home', 'url_name': 'home', 'icon_class' : 'fas fa-home', }, 'profile': { 'title' : 'Profile', }, ...[Code omitted]... } for k, v in breadcrumb_lookup.items(): if 'url_name' in v.keys(): v.update({'url': … -
Problem with Select a valid choice. That choice is not one of the available choices
in my form.py I have a class StudentsForm: class StudentsForm(ModelForm): def __init__(self, *args, **kwargs): students = kwargs.pop('students ') course = kwargs.pop('course ') super().__init__(*args, **kwargs) CHOICE_LIST = [('', '----')] i = 1 for itm in students: CHOICE_LIST.append((i, itm)) i += 1 self.fields['students'].choices = CHOICE_LIST self.fields['students'].initial = [''] self.fields['course'].choices = [(1, course), (2, '----' )] self.fields['course'].initial = [1] class Meta: model = StudCourse fields = ( 'course', 'students', ) widgets = { 'course': forms.Select(attrs={'class': 'form-control', 'placeholder': 'Select course', 'style': 'color: crimson; background-color:ivory;' }), 'students': forms.SelectMultiple(attrs={'class': 'form-control' , 'placeholder': 'Select students', 'style': 'color: crimson; background-color:ivory;' }), } my view.py def test(request): #team = get_team(request) # here the second students is a query set of model Student, 2nd course is an object of model #Course form = StudentsForm(students=students, course=course) if request.method == 'POST': form = StudentsForm(request.POST, students=students, course=course) if form.is_valid(): form.save() return redirect('home') if team.exists(): return render(request, 'app/students_goal_form.html', {'form':form}) my students_goal_form.html {% block content %} <section id="students_form"> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <div class="col-3"></div> <div class="col-6"> <div class="form-group"> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success"> <i class="icon-circle-arrow-right icon-large"></i> Save </button> </form> </div> </div> <div class="col-3"></div> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> </div> <div class="row"> <p>&nbsp</p> … -
Django Rest Framework how to check an object is exists or not?
I'm trying to check if an object is exists or not and this is how I do: try: control = Card.objects.filter(cc_num = cc_number)[0] exists = True except (IndexError): exists = False It works but I wonder if there is a more practical way to do? (The reason I use except(IndexError) is I'm finding the object with typing [0] to end of model.objects.filter().) -
Neomodel: ValueError: Can't install traversal 'source' exists on NodeSet
enter image description here I used django_neomodel to connect the Neo4j graph database. The graph data in Neo4j database is above which is the relationships between genes. This is my model for data. class Genes(StructuredNode): id = StringProperty() name = StringProperty() source = Relationship('Genes', 'Interaction') target = Relationship('Genes', 'Interaction') When I run len(Genes.nodes) in python shell, it throws an error: Traceback (most recent call last): File "<console>", line 1, in <module> File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\util.py", line 344, in __get__ return self.getter(type) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\core.py", line 266, in nodes return NodeSet(cls) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\match.py", line 581, in __init__ install_traversals(self.source_class, self) File "G:\software\anaconda\envs\flybase\lib\site-packages\neomodel\match.py", line 172, in install_traversals raise ValueError("Can't install traversal '{0}' exists on NodeSet".format(key)) ValueError: Can't install traversal 'source' exists on NodeSet Anybody knows why? -
How to get the instance of a model from inlines in django ModelAdmin
Example: Suppose I have two models: from django.db import models # Create your models here. class Author(models.Model): name = models.CharField(max_length=5, default='admin') def __str__(self): return self.name class Book(models.Model): active = models.BooleanField(default=True) name = models.CharField(max_length=5, default='admin') author = models.ForeignKey(Author, null=True, on_delete=models.CASCADE) upload = models.FileField(upload_to ='uploads/', null=True) def __str__(self): return self.name And this is my admin setup: from django.contrib import admin from .models import Author, Book class BookInLine(admin.StackedInline): model = Book extra = 0 @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['name'] inlines = [BookInLine] def get_inline_object(self, request): inlineObject = self.get_inline_instances(request)[0] #this gives me access to BookInLine object. #an example of what I need to get is: return inlineObject.instance The problem is, ModelInLine objects have no attribute instance associated with them. I can get the parent instance, that is the instance of the Author model by writing the following method in the BookInLine class: def get_parent_object_from_request(self, request): resolved = resolve(request.path_info) if resolved.kwargs: return self.parent_model.objects.get(pk=resolved.kwargs["object_id"]) return None this will give me the instance of the Author model, what I need is to access the instance of Book model associated with that change_view. I can't get any info on how to do that? Can someone please help me with this? -
Django getting data from database using foreign key
I am working on a django blog app and i want to access all the fields of database through foreign key of other database . class User(AbstractUser): about_user = models.TextField(("Profile"),blank = True) def __str__(self): return self.username class Post(models.Model): author = models.ForeignKey("account.User",on_delete=models.CASCADE) status = models.BooleanField(("Status"),default = False) Now I want to access all the data of user database from post something like posts = Post.objects.filter(status = True) posts.author.about_author or user = User.objects.filter(username = post.author) user.about_author what i am trying here in my template all the content of post will display and after that i want the about_author (whoever wrote the post ).kinda like how stackoverflow shows every questions. Thanks in advance and any advice would be much appreciated. -
My first app with django for books autors
I am totaly new with django and i'm trying to create (for learning) a webapp like this:To my site first i need to connect. Once connected i see searche bar and a create option. For searche i use an intenger. I would like to create autors. Foe each autor an id. When i searche for an id i get the autor page with all his informations. On the bottom of the page i have links. One where i can add the autors book. One wher i can add resumes and the last link i can add comments. Can someone give me somme clous how to create this webapp? TNX all!! -
Product() got an unexpected keyword argument 'product_price'
I have created a fruit selling website in django and i got the following error, Error Photo my views file is as under, def seller_add_product(request): if request.method=="POST": seller=User.objects.get(email=request.session['email']) Product.objects.create( seller=seller, product_name=request.POST['product_name'], product_price=request.POST['product_price'], product_image=request.FILES['product_image'], product_desc=request.POST['product_desc'], ) msg="Product Added Successfully" return render(request,'seller_add_product.html',{'msg':msg}) else: return render(request,'seller_add_product.html') My model file is as under, class Product(models.Model): seller=models.ForeignKey(User,on_delete=models.CASCADE) product_name=models.CharField(max_length=100) prodcut_price=models.PositiveIntegerField() product_image=models.ImageField(upload_to="product_images/") product_desc=models.TextField() def __str__(self): return self.seller.name+"-"+self.product_name now whats wrong, pls help