Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In flask if we change our database do we need to change our code also?
I have query about flask over django: As we know in django no matter whatever database we use(mongodb,mysql,postgres) we just need to write Djnago-ORM query to work with database. Just example: we have one django model: class User(models.Model): name = models.CharField(max_length=256) and we can get records using: User.objects.values() And it will give us all the records from User models. if we change our database also we don't need to change any thing in our code. except using these two commands. python manage.py makemigrations python manage.py migrate Then it will take care of everything. So, my queston is if we are using mysql in flask and in future we are changing our database to mongodb do we need to change our codes. Actually i am good at Django and don't have any idea about flask. So any clarification will be helpful for me , Thanks, -
Django-Paypal: How to create a unique django-paypal form for each object in a store model, and then display the Buy Now buttons with template tags?
I have a store model (called StoreItem) with objects in it, with price being one of the model's attributes. These store items are already displayed on a webpage, so that when you click on an item's image then info pops up about that item. I would like to use django-paypal to display a unique purchase button for each of those store items. I would like the button's price attribute to be obtained directly from the corresponding store object's price, as set in the database via the django admin page. I have successfully setup a django-paypal "Buy Now" button following instructions here: https://django-paypal.readthedocs.io/en/stable/standard/ipn.html However, this only creates one button, with the price amount given as a string. I need many different unique buttons, with the number of buttons changing depending on how many StoreItem objects there are, and each with prices obtained directly from those objects. I have scoured the internet and so far have seen no examples as to how to accomplish this. So far the best I can figure is to loop through all of the StoreItem.objects that haven't been sold, to create a paypal form for the "Buy Now" button for that object, and store each paypal form … -
Correct Pattern for a Web App (Python Django), server side script with long duration and Database
I have a Web - App (Phyton Django), which allows the User to enter his name in a form. Then the App is doing some serverside calculation (up to 5 min) and saving the result to the database . After that the user is forwarded to another dynamically created side with the results, which are fetched from the database. My Problem is that when 2 User are searching for the same name, then there are 2 identical threads running. How can I prevent this from happening ? -
Bootstrap button menu responsive doesn't work in Django project
I'm writing a project of Django. I created a static folder in my application accueil. Te button doesn't show the menu when browser resized. It's a free template that i downloaded, when i used it in my project of Django it doesn't work. <!DOCTYPE html> <html lang="fr" dir="ltr" class="no-js"> {% load static %} <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon" href="apple-touch-icon.png"> <title></title> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/Styles_accueil.css' %}" /> <!-- <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/bootstrap.css' %}" /> --> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/normalize.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/main.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/font-awesome.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/bootstrap.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/style.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'accueil/css/responsive.css' %}"> <script src="{% static 'accueil/js/vendor/modernizr-2.8.3.min.js' %}"></script> <header id="home"> <!-- Main Menu Start --> <div class="main-menu"> <div class="navbar-wrapper"> <div class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle Navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <!-- <a href="#" class="navbar-brand"><img src="{% static 'accueil/img/correspondx.png' %}" /></a> --> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li> <a href="/accueil/">Accueil</a></li> <li> <a href="/apropos/">A propos</a></li> <li><a href="/contacternous/">Nous contacter</a></li> </ul> … -
Django: Return serializer ValidationError in Model save() method
I use django-rest-framework to create Rest API within Django framework. And it's possible to return any validationError beside serializer methods. But, I was wondering is it possible to return errors from save() method of django model that be translated to django rest validationError? For example imagine I want to limit creating objects on a specific table. like this: class CustomTable(models.Model): ... # modles fields go here def save(): if CustomTable.objects.count() > 2: # Return a validationError in any serializer that is connected to this model. Note I could use raise ValueError or raise ValidationError, but they all cause 500 error on endpoint. But i want to return a response in my api view that says for example 'limit reached' -
How to get all data out of many to many field?
what i want to do here is to show current user "Signels" from all the users he is following. but can't get data of more then one user out. models.py class Signels(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) coin_name = models.CharField(max_length=300 , null=True, blank=True) symbol = models.CharField(max_length=10 , null=True, blank=True) title = models.CharField(max_length = 100, null=True, blank=True) buy = models.CharField(max_length=200 , null=True, blank=True) sell = models.CharField(max_length=200 , null=True, blank=True) class Follow(models.Model): user = models.ForeignKey(User, related_name='current_user', null=True) Following = models.ManyToManyField(User) views.py def post(request): user1 = request.user user_now = Follow.objects.get(user=user1) for followed in user_now.Following.all(): signel = Signels.objects.filter(author=followed) return render(request, 'posts/all.html', { "signels" : signel } ) all.html {% for i in signels %} <div class="card post_card "> <a type="button" href="/profile/{{i.author.username}}" class="username"><b>{{i.author.username}}</b></a> <p class="category">{{i.title}} </p> <p class="category"><b>{{i.coin_name}}({{i.symbol}})</b></p> <b class="buy">buy</b>:{{ i.buy }} , &nbsp; <b class="sell">sell</b>: {{i.sell}}, &nbsp; {% endfor %} the result i am getting in "all.html" is that it,s showing all the Signals from 1st user he is following in many to many field. but nothing from other users he is following. i want current user to see all the Signels from all the users he is following. -
Django Xampp apache not serving static file in windows
The Apache config file is given below, the STATIC_ROOT file is in the project directory static file. <IfModule wsgi_module> Alias /static/ C:\xampp\htdocs\backend_crowed\static <Directory C:\xampp\htdocs\backend_crowed\static> Require all granted </Directory> WSGIScriptAlias / C:\xampp\htdocs\backend_crowed\backend_crowed\wsgi.py WSGIPythonHome C:\Users\Biruk_Abraham\.virtualenvs\backend_crowed-bbZ215g0 WSGIPythonPath C:\xampp\htdocs\backend_crowed <Directory C:\xampp\htdocs\backend_crowed> <Files wsgi.py> Require all granted </Files> </Directory> </IfModule> The setting.py file for static and media files is STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') The View.py file is from django.shortcuts import render def home(request): return render(request, 'visual/home.html') In the html tag the static file is called as follows {% load static %} <link rel="stylesheet" type="text/css" href={% static "visual/css/style.css" %}> -
How to use Django custom template tags to get an attribute of an object?
I've written a custom tag and it is working. No problem there. However, while the template tag returns the model object that I need, I'm not able to go one step further and get an attribute of that object. As shown below: models.py class ExamScore(models.Model): exam_name = models.CharField(max_length=20) reading = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) uofe = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2, verbose_name='use of English') writing = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) listening = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) speaking = models.DecimalField(blank=True, null=True, max_digits=5, decimal_places=2) student = models.ForeignKey(Student, on_delete=models.CASCADE) custom_tags.py @register.simple_tag def unique_exam(student_id, exam_name, skill): if ExamScore.objects.filter(student_id=student_id, exam_name=exam_name).exists(): e = ExamScore.objects.get(student_id=student_id, exam_name=exam_name).skill return e else: return '' template.html <input type="number" step="0.01" class="score" id="score-re" value="{% unique_exam student.id exam_name 'reading' %}" placeholder="36"> # the trouble is here where it says 'reading' # I have also tried 'reading' with double quotes and no quotes 'reading' is the attribute I want in this case, at other times it is speaking, listening, etc. Which is why I can't hard code it, and have to pass it through the tag as an argument. What I get is this: AttributeError at /teacher/exams/PreCourse/ 'ExamScore' object has no attribute 'skill' The traceback specifically tells me the issue is at: line 17. e = … -
Django limit accessibility to database using firewall
In django website in security section, we have this sentence : It is a good idea to limit the accessibility of your caching system and database using a firewall. I wonder how I can do it? and is there a database firewall in order to do that? -
How to pre-populate fields in django?
I want to pre-fill(editable) fields in django. Something like this: Currently I'm just using multiple input fields and setting a placeholder in that. And that requires multiple try-catch blocks to be written in view. like this: try: //find if there is input catch: pass try: //find if there is input catch: pass Is there some possible "standard" way of doing this ( handling the forms / try-catch blocks in this case )? -
how can i set cookie in javascript? TT (Django Project)
i use django 2.0.9. I am creating a project in which the display is changed by changing the value of the cookie. i want to change my cookie's value in javascript or html. i want to set cookie in 'index.html' in javascript, i can get coockie's value as '{{request.COOKIES.glob }}' and how can i change glob`s value to 1 .. in my View.py) response = render(request, 'index.html') response.set_cookie('glob',0) return response i already search in google, but i can't find any answers ... please help me.. t_t -
Struggling to Install Pip and Django on Windows 10
Hi ultimately I'm trying to install django on my computer, but I'm unable to do this as the when I run pip in the command line I get the following error message: ''pip' is not recognized as an internal or external command, operable program or batch file.' I've added the following locations to my path environment: 'C:\Python37-32;C:\Python37-32\Lib\site-packages;C:\Python37-32\Scripts' I've also tried to reinstall pip using 'py -3.7 -m ensurepip -U --default-pip', but then I get the following error message: 'Requirement already up-to-date: setuptools in c:\users\tom_p\anaconda3\lib\site-packages (40.6.3) Requirement already up-to-date: pip in c:\users\tom_p\anaconda3\lib\site-packages (18.1) spyder 3.3.2 requires pyqt5<5.10; python_version >= "3", which is not installed. xlwings 0.15.1 has requirement pywin32>=224, but you'll have pywin32 223 which is incompatible.' I'm new to this so I'm struggling with the install and I'm confused by the fact pip is in C:\Python37-32\Scripts, but the above error seems to be looking in the anaconda folder. The only reason I installed anaconda was to use the Spyder IDE. I've installed python 3.7 32-bit on my Windows 10, any help would be much appreciated. Thanks -
Error in Django Widget tweaks 'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value":
I'm getting this error 'render_field' tag requires a form field followed by a list of attributes and values in the form attr="value": I'm trying to use Widget Tweaks for Django to render the Form. It gives the error and highlights the line {% render_field field class ="form-control is-valid" %} once the page loads on the browser {% extends 'base.html' %} {% load widget_tweaks %} {% block title %} New Topic: {{board.name}} - {{board.super}} {% endblock %} {% block breadcrumb %} <li class="breadcrumb-item"><a href="{% url 'home' %}">Boards</a></li> <li class="breadcrumb-item"><a href="{% url 'board_topics' board.pk %}">{{board.name}}</a></li> <li class="breadcrumb-item active">New Topic<li> {% endblock %} {% block content %} <form method="post" novalidate > {% csrf_token %} {% for field in form %} <div class = "form-group" > {{field.label_tag}} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{error}} </div> {% endfor %} {% else %} {% render_field field class ="form-control is-valid" %} {% endif %} {% else %} {% render_field field class ="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted" > {{ field.help_text }} </small> {% endif %} </div> {% endfor %} <button type ="submit" class="btn btn-success">Post</button> </form> … -
Django Heroku not serving static files when Debug=False
I'm hosting my Django application on Heroku and using whitenoise to handle serving static files. Following is content of settings.py DEBUG = False ALLOWED_HOSTS += [ 'example.com', ] MIDDLEWARE += [ 'whitenoise.middleware.WhiteNoiseMiddleware', ] STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static_my_project') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'static_root') But static files are not working. Setting Debug=True is serving static files but not when Debug=False. -
'chatterbot' is not a registered namespace
I just clone the chatterbot api and tried to run the django_app from examples as python manage.py runserver. I'm facing this issue. 'chatterbot' is not a registered namespace Can any one help me? app.html: var chatterbotUrl = '{% url "chatterbot:chatterbot" %}'; urls.py: from django.conf.urls import url from django.contrib import admin from chatterbot.ext.django_chatterbot import urls as chatterbot_urls from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', admin.site.urls, name='admin'), url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'), ] Further info: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.2 Exception Type: NoReverseMatch Exception Value: 'chatterbot' is not a registered namespace Python Version: 3.6.7 Note: I have already checked this link but of no use. -
Django Model Management in the shell
I'm having a trouble understanding the process of 'making an instance(or a row in DB table) of the model in the shell', because I think it conflicts the plain python knowledge - class/instance attribute and instantiation. Following is from the example in Django official documents. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name This is the code describing the model 'Blog'. >>> from blog.models import Blog >>> b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') >>> b.save() And the shell prompt follows. In the second line, the right hand side is just the perfect instantiating form from python, writing the class name and then assigning values in arguments inside the parentheses, right? But problem here is, 'name' and 'tagline' is defined as class attributes, not instance variables. If the code makes sense, then it should be like: class Blog(models.Model): def __init__(self): name = models.CharField(max_length=100) tagline = models.TextField() How can the class be instantiated using class variable? P.S One possibility, I guess, is that the manager API which intermediates DB table and the user does all the job, and the obscure code above is the following result. BUT I'm not sure. -
how to restrict unfollow users from accessing the blog content using if-statement in django templates?
Guys i want to create a logic for Django in the template where only the subscribed users can access the blog post. i tried to use only_for subscribers boolean field and user.followers group to allow post only accessible for subscribers. class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True,default=None) created = models.DateField(auto_now_add = True) author = models.ForeignKey(User, related_name='uploaded_by') published = models.BooleanField(default=True) only_for_subscribers = models.BooleanField(default = False) @login_required def ArticleDetailView(request,slug): post = get_object_or_404(Post, slug=slug) return render(request, 'blog/post_detail.html', {'post': post,}) class Contact(models.Model): user_from = models.ForeignKey(User,related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return '{} follows {}'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('self', through=Contact, related_name='followers', symmetrical=False)) {% if request.user not in user.followers.all and post.only_for_ subscribers %} Please subscribe {% else %} <div> {{post.title}} </div> {% endif %} -
Django migration raised TypeError: Unknown option(s) for sync_cassandra command
I trying to use Cassandra database for my Django rest application. When I am using sqlite database the migration working fine. However, when I am changing database to use cassandra I am getting the following error. TypeError: Unknown option(s) for sync_cassandra command: app_label, fake, fake_initial, interactive, migration_name, run_syncdb. Valid options are: database, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version. I am running cassandra service in another shell. Also I have created a Keyspace named project_db using cqlsh. The setting.py file is given below. I am getting same error even I am changing my database to cassandra only i.e. removing the sqlite database. """ Django settings for project project. Generated by 'django-admin startproject' using Django 2.1.4. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'm8m_d3=qx)&fq1j2xlz&b$(!=82#w3kljq(68n9-@%x*1=e70m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = … -
Django Rest Framework create multiple objects
This is what I have so far. My serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('field_1', 'field_2', 'field_3') My ModelViewset class MyViewSet(ModelViewSet): serializer_class = MySerializer model = MyModel queryset = MyModel.objects.all().order_by('date_paid') def create(self, request, *args, **kwargs): many = True if isinstance(request.data, list) else False serializer = MySerializer(data=request.data, many=many) if serializer.is_valid(): serializer.save() else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) My main concern is that when testing the endpoint to create multiple objects using the following payload, on the view the property request.data seem to be empty, as a result it returns errors of fields missing. { 'data': [ { 'type': 'MySerializer', 'attributes': { 'field_1': 1, 'field_2': 0.05, 'field_3': 'abc' } }, { 'type': 'MySerializer', 'attributes': { 'field_1': 1, 'field_2': 0.05, 'field_3': 'abc' } }, { 'type': 'MySerializer', 'attributes': { 'field_1': 1, 'field_2': 0.05, 'field_3': 'abc' } } ] } However when using a single object instance: { 'data': { 'type': 'MySerializer', 'attributes': { 'field_1': 1, 'field_2': 0.05, 'field_3': 'abc' } } } It seeems to work just fine and the object is created. I have tried several ways to accomodate the payload: Placing the list of objects inside the attributes field. Placing the list of instances directly on … -
how to make ajax call to django view?
I am trying to build like button but i can't make ajax call to django view. My code with httpresponse(not with ajax is as folows):- /models.py class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) user_like=models.ManyToManyField(User,related_name="likes",blank=True) def __str__(self): return self.Profile.user.username @property def totallikes(self): return self.user_like.count() class Meta: ordering=['-DatePosted'] @property def like_count(self): return len(likes.objects.filter(post=self)) /urls.py path('like/<int:postid>',views.like_button,name='like_button'), /views.py def like_button(request,postid): postresult=get_object_or_404(post,id=postid) if postresult.user_like.filter(id=request.user.id).exists(): postresult.user_like.remove(request.user) else: postresult.user_like.add(request.user) return redirect('feed') while my template is:- {% for p in result %} <div class="SpriteContainer"> <a href="/like/{{ p.id }}"><img src="{%static "/images/icons/heart.png" %}"/></a> <p style="display: inline-block;">{{ p.totallikes }}</p> </div> {% endfor %} Now i want to do two things:- 1)To make ajax call so that i don't need to reload the page. 2)To check whether the current logged in user has liked the post or not so that i can change icon for like.can i do it directly in template or i have to declare a custom django template tag? -
tasks delay not working when called from cmd
I am running celery worker in one cmd and from shell i am running my task, but when i call my task like TestTaskOne.delay() it's not working, cmd just pause there and i have to terminate with ctrl+c and worker is also not getting any task. Any ideas why this is happening. for celery worker i am using celery -A Project worker -l info -P eventlet tasks.py from __future__ import absolute_import, unicode_literals from celery import task @task def TestTaskOne(): msg = "DEFAULT TASK IS WORKING......" return msg celery.py from __future__ import absolute_import, unicode_literals import os, logging from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'RestUserAPI.settings') app = Celery('UserAPI') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) settings.py CELERY_BROKER_URL = 'mongodb://localhost:27017' CELERY_RESULT_BACKEND = "mongodb" CELERY_IGNORE_RESULT = False CELERY_TRACK_STARTED = True CELERY_MONGODB_SCHEDULER_DB = "celery" CELERY_MONGODB_SCHEDULER_COLLECTION = "schedules" CELERY_MONGODB_SCHEDULER_URL = "mongodb://localhost:27017" CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER … -
Test date value in django views
In order to make sure my database values don't create null value exceptions I created a dummy date of 01-01-0001 in Postgresql. However I want my views to return none if it's the dummy date in the view. I tried the following but it's not working: {% if myDate == "0001-01-01" %} None {% else %} {{ myDate }} {% endif %} -
How can get Ajax array in Django
There are a lot of questions about passing array via Ajax but no one worked for me. I am posting only changed form data in an array from Ajax to Django view and i am able to get data but i am not able to use any loop to get first index of the array because i see data format different in Django view. views.py @csrf_exempt def formdata(request): template_name = 'base_index.html' if request.method == 'GET': form = userForm() posts = User.objects.all() args = {'form': form, 'posts': posts } return render(request, template_name, args) if request.is_ajax(): data = request.POST print(data.dict()) # result of array is in last part. for i in data: print(i[0]) # this printing first letter of array name.But i was expecting value of first index. else: message = " " return HttpResponse(message) js: var getformdata = [] //calling this function when texbox data changed. function change_send(lblname,columnname,id,oldvalue,newvalue){ //some code //... getformdata.push({id:id, fieldname:columnname, fieldvalue:newvalue }) console.log(getformdata) } $(document).ready(function() { $("#userdata").submit(function(event){ $.ajax({ type:"POST", url:"/main/", data: { 'getformdata':getformdata }, success: function(data){ //return success msg } }); return false; }); }); </script> I see javascript array result in console like this : 0: {id: 2, fieldname: "user_name", fieldvalue: "qa"} 1: {id: 3, fieldname: "user_name", … -
How to change site from http://SERVER-IP/APP to http://SERVER-IP in Apache served Django website
I have successfully deployed a Django Website in Google Cloud with the help of Bitnami serving using Apache. The site is served at http://SERVER-IP/APP, how can i configure it to server from http://SERVER-IP? Thanks -
Unable to call Django function for inserting data in postgres db
I am running the below code however when i submit create.html template it goes directly to home.html without inserting any record in postgres db. I believe, the function "create" is not called at all. Kindly assist I tried directing the function * views.py * from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Product def home(request): return render(request, 'products/home.html') @login_required def create(request): if request.method =='POST': product = Product() product.title = request.POST['title'] product.save() return redirect('home') else: return render(request, 'products/create.html') * urls.py * from django.urls import path,include from . import views urlpatterns = [ path('create',views.create,name='create'),] * models.py * from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title * apps.py * from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' * urls.py * from django.urls import path,include from . import views urlpatterns = [ path('create',views.create,name='create'),] * create.html * {%extends 'base.html'%} {%block content%} <form method="POST" action="{% url 'create' %}" enctype = "multipart/form-data"> {% csrf_token %} Title: <br/> <input type="text" name = "title"/> <br/><br/> <input type="submit" class = "btn btn-primary" value = "Add Product"/> </form> {%endblock%} I was expecting the record to be inserted in database (postgres) and I should be able to validate …