Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why annotate dupliquates my queryset objects?
Whenever I use Annotate with Case/When logic to return a boolean, the resulting queryset is twice as long. Model : class Message(models.Model): readers = models.ManyToManyField(Compte, related_name='messages') Message.objects.count() // return 800 Then : qs = Message.objects.annotate(read=Case( When(readers=Compte.objects.first(), then=Value(True), default=Value(False), outputfield=BooleanField())) qs.count() // return 1600 What am I missing here ? Django 2.2.9 / PostgreSQL -
Django forms can I change the default "Username" field in Django forms to "Job Title"
I'm trying to make a form for a service providers booking app as part of a project. I'm just wondering can I change the default "Username" field in Django forms to "Job Title". Here is my current "Forms.py file. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2' ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user -
Django custom middleware request.user always AnonymousUser
I'm using Django 2.2 and DRF In my application, based on the user property, I need to change the request.user to a different user. class CustomMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print(request.user) response = self.get_response(request) return response The print(request.user) always gives AnonymousUser object but it gives the authenticated user in the views. How can I get the user in the middleware? -
dajngo admin date input format issue
I use django2.0 and postgresql9.6, and I have model.py: class model_test(models.Model): start_date = models.DateField('start') stop_date = models.DateField('stop') and I register it in admin.py: admin.site.register(model_test) So I can insert it on admin-site, but my pg database's has start_date like '20200101', and my insert date is default '2020-01-01', I want to change my insert to '20200101', I tried setting.py: USE_L10N = False DATE_FORMAT = 'Y%m%d' it does not work for me. How to do this? And my second question is I don't want to show the textbox, just show the date-piker: How to solve this? Thanks! -
Django template: Display object in template not using view
This almost feels too simple but I'm trying to show an object in my template and I can't use a function/class-based view because this needs to be on the base.html template (for all views). I totally get the problem as I can make it work when I define the object as a variable in a view. My question is really about how to make it work when not using the view.py base.html <!-- works --> {{ user.username }} <!-- doesn't work --> {{ custom_model.field }} I checked out The Django template language and using their story model as an example. -
How can I deploy Django App to 1and1 (ionos)
I created a website with Django and now I need to deploy it and now I have to upload it to 1and1. Do I need a specific tool for this or can I upload it without hesitation like a website that only contains .html and .css files? -
Django admin handling multiple forms
I created a custom model form class ProductGroupCommonForm(forms.ModelForm): items = forms.CharField(widget=ProductPairInputs) place = forms.MultipleChoiceField(choices=[(obj.place, obj.place) for obj in IapPlace.objects.all()]) class Meta: model = Product fields = ( 'name', 'product_order', 'place', 'tag', 'items', 'managed_by_promotion', 'asset', 'user_segment') def __init__(self, *args, **kwargs): super(ProductGroupCommonForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-2' self.helper.field_class = 'col-md-4' I am sending my custom form to overrided admin/change_form.html, like that def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['product_common_form'] = product_common_form return super(ProductGroupModelAdmin, self).changeform_view(request, object_id, form_url, extra_context=extra_context) And i added this html custom change_form html is like {% load crispy_forms_tags %} <div class="form-group product-common"> {% crispy product_common_form %} </div> Now i want to get back that form data from my ModelAdmin class, How can i acces this post data ? -
AttributeError (Django)
I am getting an error 'FeedBackForm' object has no attribute 'FeedBackForm'.I have tried all troubleshooting steps but no luck..It'll be much appreciable if anyone can help. a)form.py file from django import forms class FeedBackForm(forms.Form): name=forms.CharField() Ldap_id=forms.CharField() email=forms.EmailField() company_name=forms.CharField() feedback=forms.CharField(widget=forms.Textarea) b)views.py from django.shortcuts import render from testapp import forms # Create your views here. def feedback_view(request): form = forms.FeedBackForm() # As here we are sending details to register.html and in html file we have not mentioned action wher this file will go # so it will come back here in views.py file only. :) if request.method == 'POST': form1 = form.FeedBackForm(request.POST) if form1.is_valid(): print("Form Validation sucess and printing feedback info") # Now to capture data we will use cleaned_data===>cleaned_data==>{name:value} print('Name of editor:', form1.cleaned_data['name']) print('LDAP of editor:', form1.cleaned_data['Ldap_id']) print('EmailId:', form1.cleaned_data['email']) print('Company:', form1.cleaned_data['company']) print('Feedback provided:', form1.cleaned_data['feedback']) ##Note this above if form.is_valid(): will start working only when we'll submit form otherwise it will not start. my_dict = {'form': form} return render(request, 'testapp/register.html', context=my_dict) c)urls.py file from django.contrib import admin from django.urls import path from testapp import views urlpatterns = [ path('admin/', admin.site.urls), path('register/',views.feedback_view), ] -
Format for Storing Interactive Documents in Database
Which format can I use to store interactive elements inside of a document oriented database, which allows us to easily derive a form out of it? Background: We have the use case of storing a document in a database, with basic structures within like: heading, itemizations, enumerations, paragraphs, etc. but also with interactive elements like a checkbox, etc. From this document we want to create an interactive (HTML) document, where users can check checkboxes, and submit the result back to the server. Normally we would model the (static) document with its components as tables and columns, and e.g. a checkbox as bool field, paragraphs as varchars etc. However, we want to dynamically create and store such documents, and therefore want to use a document oriented database, e.g. MongoDB. But we are unsure about which format we should use for that. Are there any JSON or alike formats we could use and derive a form out of it? Currently we see JSON forms and JSON schema as a possibility, but then we see that we must model all elements we need, for the structural elements of such a document, e.g. paragraphs, itemizations, headings, etc. Maybe pandoc may us help here, too. … -
cannot accès to my Model Data base from views.py
I m learning Django 2.2, I am trying to a model from named sKills base on a parent model named Profile: But I have this error : DoesNotExist at /skills/ Profile matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8080/skills/ Django Version: 2.2 Exception Type: DoesNotExist Exception Value: Profile matching query does not exist. in Skills => models.py: from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) in Skills => Views.py: # Create your views here. def skill_view(request): user_id = request.user.id profile = Profile.objects.get(pk=user_id) #profile = get_object_or_404(Profile, pk=user_id) SkillFormset = inlineformset_factory(Profile, Skill,fields='__all__',extra=1) formset = SkillFormset( instance=profile) context = { 'formset': formset } return render(request,'skills/add.html',context) In Skills => urls.py: app_name = 'skills' urlpatterns = [ path('', skill_view, name='my-skills'), ] In Skills => templates => add.html: {% extends 'base.html' %} {% block title %}my skills{% endblock title %} {% block content %} <form action="" method="POST"> {{formset}} </form> {% endblock content %} I have Profile user in database I do not understand Thanks for your help -
How to Create Model from this Dictionary?
I want to make form Input User from dictionary below but dont know to make it on django my_play = dict( name="may_first_play", hosts='cisco_firewalls', become='yes', become_method='enable', gather_facts='no', tasks=[ dict(action=dict(module='asa_command', commands=['show version','show ip'])), dict(action=dict(module='asa_config', lines=['network-object host 10.1.0.1']) ] ) ihave make model like this but confusing on make on field tasks class Book(models.Model): name = models.CharField(max_length=100) hosts = models.CharField(max_length=100) become = models.CharField(max_length=100) become_method = models.CharField(max_length=100) gather_facts = models.CharField(max_length=100) class task(Book):` Please I will be very grateful if you help me -
Django LOGGING not printing to console and file
I have encountered a strange behavior of Django Loggers. I am developing a front end application using Django. During the login service, I make some requests to certain components and use log.warning() calls to see the flow of the requests. The logs worked perfectly, until I decided to add a LOGGING configuration to print the output of the logs in a file, as I want to deploy the application via Docker and I want to periodically check the log files. When I added the following Django configuration concerning logging: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'detailed': { 'class': 'logging.Formatter', 'format': "[%(asctime)s] - [%(name)s:%(lineno)s] - [%(levelname)s] %(message)s", } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'detailed', }, 'file': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': "{}/am.log".format(BASE_DIR), 'mode': 'w', 'formatter': 'detailed', 'level': 'INFO', 'maxBytes': 2024 * 2024, 'backupCount': 5, }, }, 'loggers': { 'am': { 'level': 'INFO', 'handlers': ['console', 'file'] }, } } The logging stops working. The file specified in the logging configuration, am.log, is indeed created but nothing gets printed to this file. Even the console logging does not take place. I have taken this logging configuration from one of my Django projects for the backend of … -
django has_perm method always return false
im using django 1.11, if i'm calling request.user.has_perm("auth.add_user") in shell, its return true. but if im calling this in a view its return false, all the db permission relations are fine. i tried get_object_or_404 method to get user from db to avoid cache. but its not working # shell >>> user = User.objects.get(pk=497) >>> user.has_perms(["auth.add_user"]) (u'has perm', True) True this is my permission class class DjangoModelPermissionsV2(BasePermission): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } return [perm % kwargs for perm in self.perms_map[method]] def has_permission(self, request, view): if getattr(view, '_ignore_model_permissions', False): return True if request.user and request.user.is_authenticated() or not self.authenticated_users_only: if hasattr(view, 'get_queryset'): queryset = view.get_queryset() else: queryset = getattr(view, 'queryset', None) else: return request.user and request.user.is_authenticated() or not self.authenticated_users_only assert queryset is not None, ( 'Cannot apply DjangoModelPermissions on a view that ' 'does not set `.queryset` or have a `.get_queryset()` method.' ) perms = self.get_required_permissions(request.method, queryset.model) return ( request.user.is_authenticated() and request.user.has_perms(perms) ) # requset.user.has_perms return False settings file REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated … -
how to use custom user model for django-graphql-auth
I am using graphql in my project and want to generate token while registration. Even though django-graphql-auth has all the written mutation, it uses a different user model. But I want to use my custom user model. What should I do? -
How to render multiple matplotlib graph in django templates
in my views.py def Home(request): covid19 = COVID19Py.COVID19() data = covid19.getAll(timelines=True) virusdata = dict(data['latest']) values = list(virusdata.values()) print(values) names = list(virusdata.keys()) print(names) plt.bar(range(len(virusdata)), values , tick_label= names) buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') context = { 'graphic':graphic,'virusdata':virusdata } location = covid19.getLocationByCountryCode("IN") loc_data = location[0] virusdata1 = dict(loc_data['latest']) values1 = list(virusdata1.values()) print(values1) names1 = list(virusdata1.keys()) print(names1) plt.bar(range(len(virusdata1)), values1 , tick_label= names1) buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic1 = base64.b64encode(image_png) graphic1 = graphic1.decode('utf-8') ind = {'virusdata1':virusdata1,'graphic1':graphic1 } context.update(ind) return render(request,"crona/index.html",context) in my templates {% block body %} <div class="jumbotron"> <p class="display-6 ">worldwide <span style="font-size:16px;" class="text-danger"></span></p> <div class="row"> {% for key , value in virusdata.items %} <div class="box"> <h4 class="display-6 text-center">{{ key }}</h4> <h2 class="text-primary text-center">{{ value }}</h2> </div> {% endfor %} <img src="data:image/png;base64,{{ graphic|safe }}"> </div> </div> <p class="display-6 ">India <span style="font-size:16px;" class="text-danger"></span></p> <div class="row"> {% for key , value in virusdata1.items %} <div class="box"> <h4 class="display-6 text-center">{{ key }}</h4> <h2 class="text-primary text-center">{{ value }}</h2> </div> {% endfor %} <img src="data:image/png;base64,{{ graphic1|safe }}"> </div> </div> <hr class="my-4"> <div > </div> {% endblock %} How to render multiple matplotlib graph in django templates How to render multiple matplotlib … -
Django: Cast CharField to Integer if possible
I have the following code to cast a field my_field into integer for sorting. self.object_list = self.object_list.annotate(order_field=Cast('my_field', IntegerField())) \ .order_by('order_field') The problem is that some data fields may be non-numeric, due to which it throws an error. Is there a way to Cast only if possible? I am looking for two cases - Return the full object_list, ordering those which are possible and keeping the others in the front/end. Return only the object_list where my_field can be casted to integer -
I got this error while uploading django project to pythonware
25/03/2020 https://www.pythonanywhere.com/user/rohanhirwe32/files/var/log/rohanhirwe32.pythonanywhere.com.error.log https://www.pythonanywhere.com/user/rohanhirwe32/files/var/log/rohanhirwe32.pythonanywhere.com.error.log 1/1 2020-03-25 08:19:48,249: Error running WSGI application 2020-03-25 08:19:48,263: ModuleNotFoundError: No module named 'bootstrap4' 2020-03-25 08:19:48,263: File "/var/www/rohanhirwe32_pythonanywhere_com_wsgi.py", line 15, in 2020-03-25 08:19:48,264: application = get_wsgi_application() 2020-03-25 08:19:48,264: 2020-03-25 08:19:48,264: File "/usr/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-25 08:19:48,264: django.setup(set_prefix=False) 2020-03-25 08:19:48,264: 2020-03-25 08:19:48,265: File "/usr/lib/python3.6/site-packages/django/init.py", line 24, in setup 2020-03-25 08:19:48,265: apps.populate(settings.INSTALLED_APPS) 2020-03-25 08:19:48,265: 2020-03-25 08:19:48,265: File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2020-03-25 08:19:48,265: app_config = AppConfig.create(entry) 2020-03-25 08:19:48,265: 2020-03-25 08:19:48,266: File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2020-03-25 08:19:48,266: module = import_module(entry) 2020-03-25 08:19:48,266: *************************************************** 2020-03-25 08:19:48,266: If you're seeing an import error and don't know why, 2020-03-25 08:19:48,267: we have a dedicated help page to help you debug: 2020-03-25 08:19:48,267: https://help.pythonanywhere.com/pages/DebuggingImportError/ 2020-03-25 08:19:48,267: *************************************************** 2020-03-25 08:19:50,917: Error running WSGI application 2020-03-25 08:19:50,917: ModuleNotFoundError: No module named 'bootstrap4' 2020-03-25 08:19:50,918: File "/var/www/rohanhirwe32_pythonanywhere_com_wsgi.py", line 15, in 2020-03-25 08:19:50,918: application = get_wsgi_application() 2020-03-25 08:19:50,918: 2020-03-25 08:19:50,918: File "/usr/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-03-25 08:19:50,918: django.setup(set_prefix=False) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,919: File "/usr/lib/python3.6/site-packages/django/init.py", line 24, in setup 2020-03-25 08:19:50,919: apps.populate(settings.INSTALLED_APPS) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,919: File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate 2020-03-25 08:19:50,919: app_config = AppConfig.create(entry) 2020-03-25 08:19:50,919: 2020-03-25 08:19:50,920: File "/usr/lib/python3.6/site-packages/django/apps/config.py", line 90, in create 2020-03-25 08:19:50,920: module = import_module(entry) 2020-03-25 … -
Converting Tokenize2 JSON Searchfunction from PHP into Python
Hey I´m trying to convert a searchfunction code written in PHP from a Jquery Plugin called Tokenizer2 into Python. These are 2 Links to the Plugin: https://dragonofmercy.github.io/Tokenize2/config.html https://www.jqueryscript.net/form/Dynamic-Autocomplete-Tag-Input-Plugin-For-jQuery-Tokenize2.html (there ist the PHP code from) I have tested everything with PHP locally and it is working fine. I need this Plugin to put Userinput into Tokens (obviously) and because im using a Django backend I´m trying to convert the following PHP-Code (which is used to search a JSON for the userinput) into python, but I´m having some problems doing so. So this is the PHP-Code: <?php header('content-type: text/json'); $search = preg_quote(isset($_REQUEST['search']) ? $_REQUEST['search'] : ''); $start = (isset($_REQUEST['start']) ? $_REQUEST['start'] : 1; $obj = json_decode(file_get_contents('tagginglist.json'), true); $ret = array(); foreach($obj as $item) { if(preg_match('/' . ($start ? '^' : '') . $search . '/i', $item['text'])) { $ret[] = array('value' => $item['text'], 'text' => $item['text']); } } echo json_encode($ret); And this is my attempt convert this into python: import re import request import json r = request.head('tagginglist.py') search = re.escape(request['search']) start = request['start'] x = request.get('tagginglist.py') obj = x.json() ret = {} for item in obj: if re.match (re.compile('/' + (start '^' : '')) + search + '\i', item['text'])) ret = {'value' … -
Sending Video Stream from Front-end(angularjs) to Backend(Django)
I want to pass video frame from Front-end(angularjs) to Back-end(Django) for video sreaming. for that I had followed below link. https://github.com/aiortc/aiortc/tree/master/examples/server for Django,I had used Django-celery Tasks for asynchronuos function. I tried to pass RtcPeerConnection object(as arguement) into celery task that time I got below error TypeError: Object of type RTCPeerConnection is not JSON serializable Traceback (most recent call last): File "/home/loksun/.local/lib/python3.6/site-packages/kombu/serialization.py", line 50, in _reraise_errors yield File "/home/loksun/.local/lib/python3.6/site-packages/kombu/serialization.py", line 221, in dumps payload = encoder(data) File "/home/loksun/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 70, in dumps **dict(default_kwargs, **kwargs)) File "/usr/lib/python3/dist-packages/simplejson/init.py", line 399, in dumps **kw).encode(obj) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 291, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 373, in iterencode return _iterencode(o, 0) File "/home/loksun/.local/lib/python3.6/site-packages/kombu/utils/json.py", line 59, in default return super(JSONEncoder, self).default(o) File "/usr/lib/python3/dist-packages/simplejson/encoder.py", line 268, in default o.class.name) TypeError: Object of type RTCPeerConnection is not JSON serializable Any hint will be appreciated. Thank you! -
NoReverseMatch Error for a pattern that exists
I am making a simple login logout app in django. I am getting a NoReverseMatch error claiming a pattern name doesn't exist, but it does. My project directory looks like this: dryrun_root -db.sqlite3 -manage.py -dryrun -asgi.py -init.py -py_cache -settings.py -urls.py -wsgi.py -dryapp -admin -apps.py -init.py -migrations -models.py -py_cache -static -templates -base.html -dryapp -home.html -login.html -tests.py -urls.py -views.py dryapp/views.py from django.views.generic import TemplateView from django.shortcuts import render # Create your views here. class HomePageView(TemplateView): template_name = 'dryapp/home.html' dryapp/urls.py from django.conf.urls import url from .views import HomePageView app_name="dryapp" urlpatterns = [ url('', HomePageView.as_view(), name='_home'), ] dryapp/templates/dryapp/home.html {% extends 'base.html' %} {% block head %} <title>Home Page</title> {% endblock %} {% block body %} <div class="container"> <h1>Home</h1> </div> <div> <small class="text-muted"> <a class="ml-2" href="{% url 'login' %}">Click here to log in</a> </small> </div> {% endblock %} Now, this displays just fine. But the next template does not. dryapp/templates/dryapp/login.html {% block body %} <div class="container"> <h1>Welcome!</h1> <p>You can login here.</p> <h2>Login</h2> <form method="post"> {{ form.as_p }} {% csrf_token %} <button type="submit">Login</button> </form> </div> <div class="border-top pt-3"> <small class="text-muted"> No Account? Let's Change That <a class="ml-2" href="{% url '_home' %}">Sign Up</a> </small> </div> {% endblock %} This template will not load. I keep getting the … -
How to apply background image in sending email using django
I hope the title is enough to understand my problem. i just want to add in my email_html background image. this is my email_html {% load static %} <!DOCTYPE html> <html> <head> <style> body { background-image: url('https://myschoolapp.school.com/static/emailbackground.jpg'); background-repeat: repeat-y no-repeat; margin: 0; padding: 0; } </style> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="20"> <tr> <td> <p>Content on a pretty background image.</p> </td> </tr> </table> </body> </html> -
How to access url path in django view
How can I access the url in a django view. I have a view handling following 5 urls: localhost:8000/standings/ localhost:8000/standings/q1 localhost:8000/standings/q2 localhost:8000/standings/q3 localhost:8000/standings/q4 and my view is class StandingsView(LoginRequiredMixin, TemplateView): template_name = 'standings.html' Based on q1, q2, q3, q4 or None in the url path, I have to query data from the db and render to the given template. Please suggest on how such scenarios can be handled. -
how to implement mouse over feature in django app?
hope you all are safe from corona virus! I'm creating a Django app in which i want to implement the following functionality: "When person mouses over a target word, a pop-up window shows up with a short definition of the word" Can anyone help me in this or share any tutorial or reference link? -
Dango : Andministration page do not diplay user new well
I am learning Django 2.2, I am trying to display the user name of my model named 'Profile' but instead I have : Profile objet(3), Profile Object(4) Here is the code in Profile Apps=> models.py : from django.db import models from profiles.models import Profile from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. class Skill(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE) name = models.CharField(max_length=220) score = models.PositiveIntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) def __str__(self): return "{}-{}-{}".format(self.user, self.name, self.score) Here is the code in Profile Apps=> admin.py : from django.contrib import admin from .models import Profile # Register your models here. admin.site.register(Profile) Here is the code in Profile Apps=> init.py : default_app_config = "profiles.apps.ProfilesConfig" I have this, instead of user name: -
Django DateTimeField and User Input fields not added
I am beginner to python Django. I'm working on practice project. I got stuck while adding a product. Its adds all the fields except two fields i. DateTimeField ii. User (who add the product) The error which i'm facing is: django.db.utils.IntegrityError: null value in column "pub_date" violates not-null constraint DETAIL: Failing row contains (3, Piano, Ball Pens(set of 3), 15, 30, 10, images/ballpens_QdhwoOa.jpg, null, null). models.py class Product(models.Model): companyName = models.CharField(max_length=255) pro_name = models.CharField(max_length=255) Purchase_Price = models.IntegerField() Sale_Price = models.IntegerField() Quantity = models.IntegerField() Picture = models.ImageField(upload_to='images/') saler = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() def pub_date_pretty(self): return self.pub_date.strftime('%b %e %Y') def __str__(self): return self.pro_name views.py class AddProduct(TemplateView): template_name = 'stock/addproduct.html' def get(self, request): form = AddProductForm() args = {'form':form} return render(request, self.template_name, args) def post(self, request): form = AddProductForm(request.POST, request.FILES) if form.is_valid(): productadded = form.save() productadded.saler = request.user productadded.pub_date = timezone.datetime.now() productadded.save() return redirect('stock') else: args = {'form': form} return render(request, self.template_name, args) In views.py, I am saving a user and date and time as you see in above forms.py class AddProductForm(forms.ModelForm): class Meta: model = Product fields = ('companyName', 'pro_name', 'Purchase_Price', 'Sale_Price', 'Quantity', 'Picture' ) def __init__(self, *args, **kwargs): super(AddProductForm, self).__init__(*args, **kwargs) self.fields['companyName'].label = 'Company Name' self.fields['pro_name'].label = 'Product Name' …