Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where to make API call with Vue/Django project
I have a Vue project and have previously used Django as a backend API only to access a database, but I have a project now where I reach out to the Yelp API. This API doesn't allow client-side(JS) API access because of CORS. Does it make sense that I would have to make an API call from Vue to Django to pass user input and then another API call from Django to Yelp. This sounds like bad practice, but is there a better way to do this other than integrating a Django form to the page? -
Comments on Django Post won't save
I am trying to post comments to a post in Django, but my form is never valid. I have discovered that this is because my request.method is always a GET and not a POST. I would like to allow a user to add a new comment and have it automatically save to the database and display on my post's detail view. views.py def add_comment_to_post(request, pk): print("REQUEST METHOD", request.method) post = get_object_or_404(Post, pk=pk) if request.method == "POST": print("POST") print(request.POST) form = CommentForm(request.POST) if form.is_valid(): print("HREE") comment = form.save(commit=False) comment.author = request.user comment.date_posted = timezone.now() comment.post = post comment.save() return redirect('post_detail', pk=comment.post.pk) else: print("ELSE") form = CommentForm() # Note the indentation (this code will be executed both if NOT POST # and if form is not valid. return render(request, 'main/add_comment_to_post.html', {'form': form, 'post':post}) forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['author', 'content'] models.py class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') comment_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) # approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() class Meta: ordering = ['date_posted'] def __str__(self): return 'Comment {} by {}'.format(self.content, self.author.first_name) class Post(models.Model): run_id = models.AutoField(primary_key=True) author = models.ForeignKey(Profile, on_delete=models.CASCADE) title = models.TextField(max_length=100, blank=False, … -
login authentication in django
I want to use the authenticaton for custom user model in django. i just created the authentication for custom user model. but it's not validating the username and password. anyone help for that where i was mistaken the code. Here it is my views.py file : from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login def loginpage(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] post = User.objects.filter(username=username, password=password) user = authenticate(post) if user is not None: if user.is_active: login(request, user) if post and user: username = request.POST['username'] password = request.POST['password'] request.session['username'] = username request.session['username'] = password return redirect("profile") else: return render(request, 'login.html', {}) return render(request, 'login.html', {}) -
docker network not connecting my services together
I am having an issue with docker network not connecting my services together, I have a postgres image and a python image that need them to connect but at the moment when I call to connect to postgres service from python service my connection is denied. I have tried to open port 5432 and all host to see if I could get any connection but the same error would occur, tried using the service name to connect to it and the same issue continues to happen. anyone have any ideas why ? =========================================Django settings.py============================================== DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } ...... ALLOWED_HOSTS = ['*'] ========================================Error========================================================== ERROR: Service 'web' failed to build: The command '/bin/sh -c python manage.py makemigrations' returned a non-zero code: 1 Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.7/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: No address associated with hostname The above exception was the direct cause of the … -
How to request a filtered viewset in django restframwork
I need to retrieve a filtered set of data by calling an HTTP request using Django rest framework. here are my API codes: urls.py urlpatterns = [ path('api/get_products/', views.get_products), ] Views.py @api_view(["GET", ]) def get_products(request): category_name = request.data['category_name'] category_obj = Category.objects.get(name=category_name) products_list = Product.objects.filter(category=category_obj) serializer = ProductSerializers(products_list) return Response(serializer.data) and finally the serialierz.py class CategorySerializers(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = ['name', 'id'] class ProductSerializers(serializers.HyperlinkedModelSerializer): category = CategorySerializers() class Meta: model = Product fields = '__all__' and am trying to call it using a get request with the argument: {'category_name':'the_name_of_the_category' } and it returns this error: KeyError at /categories/api/api/get_products/ 'category_name' -
Django TypeError/ in views.py (expected str, bytes or os.PathLike object, not list)
following this youtube tutorial: https://www.youtube.com/watch?v=psvU4zwO3Ao . Which builds a template on Django server. Pretty confident I followed it precisely, however receiving this error in views.py which is based in the app directory. Code in Views.py in app directory: from django.shortcuts import render def home(requests): return render(requests, 'home/welcome.html') Traceback (most recent call last): File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "c:\Users\popec\PycharmProjects\djangoproject\mysite\home\views.py", line 5, in home return render(requests, 'home/welcome.html') File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\popec\AppData\Local\Programs\Python\Python38-32\lib\ntpath.py", line 78, in join path = os.fspath(path) Exception Type: TypeError at / Exception Value: expected str, bytes or … -
PPT view on Website By Using Django Framework
How to view PPT files on the website using Django Framework? Please share the code on how to do it by using the Django Framework. Sorry, I don't have any examples of what I am looking for. -
React JS render the element to the Dom of only one html page in my Django app
I have a Django app with frontend in ReactJS.. In which I have two html files and one App.js with two classes.. My Issues is that React executes in the App.js only the first render line segment , and didn't render the element in the second line to the other html page?! It only renders two elements if i have the two id`s in the same html file! how to solve this ?! first html page: index.html {% extends 'base.html' %} {% block content %} <div id='app'></div> {% endblock %} second html page: arabic_home.html {% extends 'base.html' %} {% block content %} <div id='app_arabic'></div> {% endblock %} The App.js: ReactDOM.render(<App />, document.getElementById('app')); {/* it only executes the first line */} ReactDOM.render(<App_arabic />, document.getElementById('app_arabic')); -
Permissions to edit certain fields in Django
I have two different groups who are allowed to access Django-Admin. They are allowed to view all Fields in a Model, but shall not edit all Field. For example G1 is allowed to edit "price" and "ean" whilst G2 is allowed to edit "ean" and "detail". I tried the version given here, but I also want to restrict the editability in the detail view of a model object. -
Nextjs or Gatsby, what is the need for e-commerce single site web application?
I want to make a Single Site Application which is an e-commerce application. For this I want use Django, Django Rest for API endpoints as backend. And for frontend I want to use React, Redux, Axios, React-Router, Antd. So for professionally deploy this app, what is need of Nextjs or Gatsby? I want to scale my application for million users. Please help & Thanks. -
How to filter one filed using multiple values in ListAPIView?
How to filter one filed using multiple values in ListAPIView? URL: /api/items/?status=active&status=pending I need to get results that have both active and pending status. What filter_backends will be good for my case? -
Django Admin - Cancel other select fields when selecting one
I'm writting an app on Django. On a model, let's admit we have this : Class MyModel(models.Model): A=models.ForeignKey(A, null=True, on_delete=models.SET_NULL) B=models.ForeignKey(B, null=True, on_delete=models.SET_NULL) C=models.ForeignKey(C, null=True, on_delete=models.SET_NULL) In the django administration, it will create select fields to choose options. And i'd like that when we select an option in a field, it resets the other ones. So in the end, it would be an OR condition between the select fields.. In javascript/jquery, it would be quite easy to do so, but do you think it can be done from django (inside the model..) ? Thank you very much for your replies and ideas -
updating data from another app in django rest framework
I have two apps named requisition and inventory. Now I want update Inventory according to requisition approval. When requisition will approve for a particular Item, then Inventory will increase for that item. how can I solve this problem? Here is my requisition app's model: class Requisition(models.Model): item_name = models.CharField(max_length = 255 ) ammount = models.IntegerField() status = models.IntegerField() class RequisitionSerializer(serializers.ModelSerializer): class Meta: model = Item_One fields = ['item_name', 'ammount', 'status'] and my Inventory app's model is: class Inventory(models.Model): item_name = models.ForeignKey(Requisition, on_delete=models.CASCADE) balance = models.IntegerField() class InventorySerializer(serializers.ModelSerializer): class Meta: model = Item_One fields = ['item_name', 'balance'] If we set status=1 in Requisition class, then balance in the Inventory class will be increase for this Item. I am using function based view for this project. -
Django Compute the average per Grading Categories
I had created my table inside my views.py, I just want to compute the average Per Grading Categories (please see the image of admin Site), This is my data in admin Site studentsgrade = studentsEnrolledSubjectsGrade.objects.filter( Teacher__in=teacher.values('Subjects')).distinct('Grading_Categories').order_by('Grading_Categories') gradingcategories = gradingCategories.objects.filter( id__in=studentsgrade.values_list('Grading_Categories')).distinct().order_by('id') print("gradingcategories",gradingcategories) gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories') print("gradepercategory",gradepercategory) count_id = studentsEnrolledSubjectsGrade.objects.filter( Grading_Categories__in=cate.values_list('id')).filter( grading_Period__in=period.values_list('id')).order_by( 'id').filter(Students_Enrollment_Records__in = studentenrolledsubject.values_list('id', flat=True)).count() this is the result of print("gradingcategories",gradingcategories) and print("gradepercategory",gradepercategory) gradingcategories <QuerySet [<gradingCategories: Quiz>, <gradingCategories: Homework>]> gradepercategory <QuerySet [<studentsEnrolledSubjectsGrade: Mary M Burabod>, <studentsEnrolledSubjectsGrade: Mary M Burabod>]> when i tried this to my gradepercategory gradepercategory = studentsEnrolledSubjectsGrade.objects.filter(Grading_Categories__in = gradingcategories.values_list('id', flat=True)).filter( grading_Period__in=period.values_list('id', flat=True)).distinct('Grading_Categories').aggregate(Sum('Grade'))['Grade__sum'] i get this error error This is how i create my table students = studentsEnrolledSubjectsGrade.objects.filter(Teacher=m.id).filter( grading_Period__in=period.values_list('id')).filter( Subjects__in=student_subject.values_list('id')).filter( Grading_Categories__in=cate.values_list('id')).filter( GradeLevel__in=student_gradelevel.values_list('id')).order_by( 'Students_Enrollment_Records', 'Grading_Categories' ).values('Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname','Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname', 'Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Middle_Initial','Grading_Categories', 'Grade').distinct() teacherStudents = StudentsEnrolledSubject.objects.filter( id__in=students.values_list('Students_Enrollment_Records')) Categories = list(cate.values_list('id', flat=True).order_by('id')) table = [] student_name = None table_row = None columns = len(Categories) + 1 table_header = ['Student Names'] table_header.extend(list(cate.values_list('CategoryName', flat=True))) table.append(table_header) for student in students: if not student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] == student_name: if not table_row is None: table.append(table_row) table_row = [None for d in range(columns)] student_name = student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname'] + ' ' + student['Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname'] table_row[0] = student_name table_row[Categories.index(student['Grading_Categories']) + 1] = """Result of average per grading perion""" table.append(table_row) … -
Filter in Django having multiple categories
All I want do is filter Product on the basis of list shown in photo. In woman category there should be 12 main category as mentioned down in photo. Now every sub category also have sub category. I have no clue about how to do it. Please suggest how I can do it for my project. If possible explain in details.enter image description here -
Celery Task Worker Refresh
I've got a pretty basic task configuration. The problem I have, however, is I have a variable that is being updated every hour. This variable is an auth_token for an API. If the auth_token is expired the task errors because it can't connect to the API. If I attempt to process records just after the auth_token has been refreshed, the task errors out stating that my auth_token is expired. But then if I restart the worker, the task works as designed using the new auth_token. I've been scouring Celery documentation looking for some configuration I can add to my task that would force it to clear it's cache after it processes refresh_access_token task, but can't find anything. Any help would be much appreciated! serializer.py # List Create View class LedgerAPIView(generics.ListCreateAPIView): queryset = Ledger.objects.all() serializer_class = LedgerSerializer permission_classes = [IsAdminUser] authentication_classes = [TokenAuthentication, SessionAuthentication] pagination_class = PageNumberPagination def perform_create(self, serializer): """ Posting to the API requires that a user have an auth_token and be classified as an active_user. """ serializer.save() # Create ProcessRecord Object ledger_object = Ledger.objects.get(id=serializer.instance.id) record = ProcessedRecords(payment_allocation_name=ledger_object) try: record.save() except Exception as exc: formatted = "Cannot update ProcessedRecords Table! ERROR --> {}".format( repr(exc)) raise Exception(formatted) # Start Celery … -
Saving ManyToMany data in Django 3
I'm trying to save data in django with ManyToMany fields via django-bootstrap-modal-forms package for modal forms with no success. I tried overriding the save method but kwargs['instance'] always return an empty dict of the ManyToMany field ('suppliers'): {'name': 'product_1', 'all_suppliers': <QuerySet []>, 'suppliers': <QuerySet []>} What I'm trying to achieve is updating the suppliers for a product and/or updating products from a supplier Totally new to Django so please excuse the bad programming style Could you please help me. Thanks! Here is my code: models.py # models.py class Product(models.Model): name = models.CharField(unique=True, max_length=100) active = models.BooleanField(default=True) def __str__(self): return self.name class Supplier(models.Model): name = models.CharField(unique=True, max_length=100) supplier_products = models.ManyToManyField(Product) def __str__(self): return self.name views.py # views.py class ProductUpdateView(BSModalUpdateView): model = Product template_name = 'product/product_update.html' form_class = ProductForm success_url = reverse_lazy('product_list_view') class SupplierUpdateView(BSModalUpdateView): model = Supplier template_name = 'product/supplier_update.html' form_class = ProductForm success_url = reverse_lazy('supplier_list_view') forms.py # forms.py class ProductForm(BSModalForm): all_suppliers = forms.ModelMultipleChoiceField(queryset=Supplier.objects.all(),required=False) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if kwargs.get('instance'): suppliers = kwargs['instance'].supplier_set.all() print(type(kwargs['instance'])) self.fields['suppliers'] = forms.ModelMultipleChoiceField(required=False, queryset=suppliers) class Meta: model = Product fields = ['name', 'notes'] fields.append('all_suppliers') -
How to use validators in django
from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_subject(value): if value.isalnum(): raise ValidationError(_('%(value)s is not valid. Please use alphanumneric characters as subject names'), params={'value': value},) class Exam(models.Model): #Exam can have many questions subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject]) #make it to reject a string of length 0 def __str__(self): return self.subject I want this code to raise an error when I keyed the following from my_app.models import Exam exam = Exam() exam.subject = "" exam.save() Why Iam not getting an error? -
Django Allauth saving profile information with signup form
I am new in Django, I am using allauth app to create a user registration. There are some extra field I wish to have in my signup form. Not only (username, first_name, last_name) I which to include(info) to registration form. When I submit the registration form only the first_name and the last_name are saved in database, info do not save, I guess it should be saved in Profile Model, but not there. class Profile(models.Model): user = models.OneToOneField(User) info = models.CharField(max_length=128) class CustomSignUpForm(Signup Form): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=30) info = forms.CharField(max_length=50) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() user.profile.info = self.cleaned_data['info'] user.profile.save() ACCOUNT_FORM = 'signup' 'myapp.forms.CustomSignupForm' -
Is SQL or NoSQL a better choice for a beginner Django project?
When it comes to actually deploying a Django project, is SQL software, like PostegreSQL, or NoSQL, like MongoDB, a better option? To evaluate which might be a better choice, you can consider: requires less changes to the actual code of the already existing project - for example having to re-do the models structure, has correct integration with the backend, i.e.: some years ago MongoDB wouldn't integrate with the Django backend, is more beginner friendly. -
Extend Django base.html in multiple separate sections?
My base.html divides the page into two equal columns. <body> <div class="column-left"> <\div> <div class="column-right"> <\div> </body> On homepage.html, I would like to extend these columns separately and add some html content to each column e.g. an image. *Extended base.html column-left* <img src=image_left /> *Extended base.html column-right* <img src=image_right /> Is it possible to extend base.html's columns separately on the homepage.html? -
Django : Compress image from form, then upload it to S3 (creates multiple images...)
I spent the day at trying to make image compression and upload to S3 to work. I feel disappointed, and I hope that you can help me. Ok, I'm creating an ecommerce platform where users can sell things. They need to upload images. I created a modelForm based on my Thing model. I was saving files on the disk before but I need to use S3 for better performances. I have this for the moment : class Thing(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True, null=True, blank=True) seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content = models.TextField(max_length=240, null=True) state = models.ForeignKey('State', related_name='state', on_delete=models.CASCADE) shipping_carrier = models.ForeignKey('Carrier', related_name='carrier', on_delete=models.CASCADE) shipping_weight = models.FloatField() # Price Auto-Calculation upvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='thing_upvotes') downvotes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='thing_downvotes') image1 = models.ImageField(upload_to='things', blank=False, default='image1.jpg') image2 = models.ImageField(upload_to='things', blank=True) image3 = models.ImageField(upload_to='things', blank=True) # max res 1020,573 created_date = models.DateTimeField(default=timezone.now, verbose_name="Publication date") category = models.ForeignKey('Category', related_name='category', on_delete=models.CASCADE) class Meta: verbose_name = "thing" ordering = ['created_date'] # Self method, gives a fast title string of the thing def __str__(self): return self.title # Gives the thing url after creating it for example def get_absolute_url(self): return reverse('detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): super().save(*args, **kwargs) im = Image.open(self.image1) in_mem_file = io.BytesIO() im.save(in_mem_file, quality=30, … -
Why is my BeautifulSoup text search with special characters failing to retrieve my element?
I'm using Python 3.7, Django 2 and Beautiful Soup 4. I have this snippet of HTML ... <p class="tagline ">submitted&#32; on 2/20/2019</p> I would like to retrieve this element and so I have created the below code ... bs = BeautifulSoup(html, features="lxml") ... pattern = re.compile(r'^submitted\&\#32\;') submitted_elt = bs.find(text=pattern) Unfortunately, the submitted_elt is always None. What else do I need to do to tweak my regular expression to search for this element? I don't want to have the word "submitted" all by itself, because that will return too many elements. -
How can I get id="demo" value of html range slider in my django app?
I'm creating my first django app. I want to interactively show some plots. here is the link for my app(hosted on pythonanywhere): https://physics.pythonanywhere.com I have created a slider in my home.html <!DOCTYPE html> <html> <head> <h1><p><font style="font-family:verdana;">Unit Intensity Plots</font></h1> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .slidecontainer { width: 35%; } .slider { -webkit-appearance: none; width: 100%; height: 15px; border-radius: 5px; background: #d3d3d3; outline: none; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s; } .slider:hover { opacity: 1; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 25px; height: 25px; border-radius: 50%; background: #4CAF50; cursor: pointer; } .slider::-moz-range-thumb { width: 25px; height: 25px; border-radius: 50%; background: #4CAF50; cursor: pointer; } </style> </head> <body> {% autoescape off %} {{ plot_div }} {% endautoescape %} <p><font style="font-family:verdana;size=5">&emsp;&emsp;&emsp;&emsp;&emsp;Angle Range Slider</font></p> <div class="slidecontainer"> <input type="range" min="0" max="360" value="0" class="slider" id="myRange"> <p><font style="font-family:verdana;"> Value: <span id="demo"></span>&#176;</p> </div> <script> var slider = document.getElementById("myRange"); var output = document.getElementById("demo"); output.innerHTML = slider.value; slider.oninput = function() { output.innerHTML = this.value; } </script> </body> </html> Now i want to use this slider to change the x axis range as the slider is moved. For this I need to get the value of slider in my django-views.py as … -
This field is required. Error with ImageField django
I'm getting 'This field is required' error while uploading image. I don't understand why I get this error, my model is very basic, but I don't know why and where i'm getting error. Some help would be apreciate. my models is class Post(models.Model): title= models.CharField(max_length=100) img = models.ImageField(upload_to='pics') content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author= models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('User-Posts-Details', kwargs={'pk': self.pk}) 'my views is' class PostCreateViews(CreateView): model = Post fields = ['title','img','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and html code <div class="blog_list"> <form method="POST"> {% csrf_token %} <h2 class="blog_heading">New Post</h2> <fieldset class="form-group" id="new"> {{ form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Post</button> </div> </form> can anyone plz help me with this?????