Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does nulls_last=False not put the nulls first in Django?
I'm finding that while nulls_last=True works, nulls_last=False doesn't. Example below is in a Django shell. In [10]: [x.date for x in Model.objects.all().order_by(F('date').asc(nulls_last=True))] Out[10]: [datetime.datetime(2020, 3, 10, 16, 58, 7, 768401, tzinfo=<UTC>), datetime.datetime(2020, 3, 10, 17, 4, 51, 601980, tzinfo=<UTC>), None, ] [ins] In [11]: [x.last_run_created_at for x in Model.objects.all().order_by(F('date').asc(nulls_last=False))] Out[11]: [datetime.datetime(2020, 3, 10, 16, 58, 7, 768401, tzinfo=<UTC>), datetime.datetime(2020, 3, 10, 17, 4, 51, 601980, tzinfo=<UTC>), None, ] In [12]: I've tried this with both desc() and asc(). -
How to send the value of two dependent dropdowns via an AJAX post request to a Django view?
I'm currently trying to send the values of two dropdowns to a django view. My code would have worked properly had the dropdowns been independent. The problem is that it isn't the case. The first one updates the second one, so I need to make my AJAX post request once the second dropdown has been updated. Here is my current html/Javascript code: <select name="d1" class="toChange"> {% for item in items1 %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <select name="d2"> {% for item in items2 %} <option val="{{ item }}"> {{ item }} </option> {% endfor %} </select> <script type="text/javascript"> function dropdownChange () { var value_d1 = $(".toChange option:selected").val(); var value_d2 = $("select[name=d2] option:selected").val(); $.ajax({ url: '/myApp/templates/', type: 'POST', data: {'d1': value_d1, 'd2': value_d2}, success: function(data) { var str = ''; data.forEach(function(opt){ str += '<option value="' + opt + '">' + opt + '</option>'; }); document.getElementById("d2").innerHTML = str; } }); $(".toChange").change(dropdownChange); So here the change in d1 updates d2 but the AJAX call is made before d2 gets updated and therefore sends the wrong value to my view. How can I overcome this issue? -
How to use pytest's live_server fixture in docker
I am trying to test my app with selenium and pytest. I want to use the live_server fixture for this because I need my tests to be self contained. Pytests offers this fixture and I do this: def test_user_can_visit_website_with_chrome(live_server): """Visit website with chrome browser. """ browser = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME ) browser.get(live_server.url) assert 'mywebsite' in live_server.title I can see in my VNC that it connects and visits the site localhost:42345 . If I run it again it uses a different port. I can see in my VNC that it says: ++ localhost: refused to connect. ERR_CONNECTION_REFUSED if I don't use the liveserver but a normal url I get: selenium.common.exceptions.SessionNotCreatedException: Message: session not created E from disconnected: Unable to receive message from renderer I can get it to work using djangos inbuilt LiveServerTestCase but I don't want to use it since I get problems with my fixtures and my whole setup. I set the ALLOWED_HOSTS everywhere to ['*']. I don't know how to solve this. Anyone any ideas? Thanks so much for any help!! Appreciated a bunch! My dockerfile looks like this: services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: mywebsite depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - … -
Django loggin in AWS
I was just wondering what is the current best way to perform logging within Django and AWS. I was looking at this article, which suggested writing to the following location, but I have found that this doesn't work: /opt/python/log Then use commands such as command: chmod g+s /opt/python/log command: chown root:wsgi /opt/python/log I have also seen articles that suggest using watchtower, but I don't like the idea of adding my secret access keys into the code: https://medium.com/@zoejoyuliao/plug-your-django-application-logging-directly-into-aws-cloudwatch-d2ec67898c0b What is the current and best way to do this ? Thanks -
for python 3.7.6 which myql-client version is supported
for python 3.7.4 the myqli client library is supported which is given below mysqlclient-1.4.4-cp37-cp37m-win32.whl but i have python 3.7.6 which mysql-client wheel is supported Any Help would be appreciated -
Adding IntegerField along with multiselectField?
I've been using MultiSelectField to select multiple list items, but after selecting I want to add their quantity too? Like a solution to add IntegerField alongside with the multiselectfield?? -
Django App: Timezone issues when running my Heroku app?
I'm creating a scheduling app on Django. As per most recommendations on the topic, the appointments (in my Appointments model) are stored in UTC. So my settings.py are set to TIME_ZONE = 'UTC'.The app was working perfectly on my local environment, but when I deployed to Heroku I started having issues. To give you an example (in production): >>> heroku run bash >>> python manage.py shell >>> from datetime import datetime >>> datetime.now() datetime.datetime(2020, 3, 10, 17, 10, 10, 453536) Yet, on local, I get: datetime.datetime(2020, 3, 10, 13, 10, 10, 196794) I tried to solve the issue (ie, 4-hour difference) by changing the TZ config value of the app to my local time, like so: heroku config:add TZ='America/Toronto' No luck. Anyone understands why this is happening? Any suggestions on how to solve this? -
How to validate empty label of M2M field in ModelForm?
I have a ModelForm overridden to have an extra option "None for now". When submitting the form it returns the form (invalid form) with the validation error: "" is not a valid value. ModelForm: class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) self.fields['quiz'].choices = [('', 'None for now')] + \ [(quiz.pk, quiz.title) for quiz in self.fields['quiz'].queryset] How do I allow the empty label through the form validation? -
Django ModelChoiceField get choice of coneceted user
I created a forms.Modelchoicefield that contains items on my database. but it show all users data, I only want to show data of the connected user! THanks for helping models.py class List(models.Model): item = models.CharField(max_length=100) content = models.TextField() site = models.CharField(max_length=11, choices=THE_SITE) content_list = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.item forms.py class ListDataForm(forms.Form): message = forms.CharField(widget=forms.Textarea) listdata = forms.ModelChoiceField(queryset=List.objects.all()) Instead of forms.ModelChoiceField(queryset=List.objects.all()) I writed forms.ModelChoiceField(queryset=List.objects.filter(author=request.user)) but it doesn't work -
Count in django using foreign key
I have two models, User and JobGroup, User Model has a foreign key from Job Group. class User(AbstractUser): jobgroup = models.ForeignKey(JobGroup, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.username class JobGroup(models.Model): group_name = models.CharField(max_length=50, unique=True, blank=True, null=True) def __str__(self): return self.group_name I want to count the number of times a job group is assigned to a user E.G user1 - Jobgroup A, user2 - Jobgroup B, user3-Jobgroup A, user4-Jobgroup C The output I am looking for Jobgroup A-2 Jobgroup B-1 Jobgroup C-1 I tried this jobcount=User.objects.all().values('jobgoup__group_name').annotate(total=Count('jobgroup__group_name')) but it did't work.. It returns None -
What do "Stars" mean about a django package in djangopackages.org grids?
In djangopackages.org grids, it shows many aspects of different django packages. One of them is "Stars". Can't find any explanation on what that "Stars" mean or indicate. If it's a rating system, where does it come from & who makes that decision? Anyone has any idea? -
===== docker migrate release ===== [FATAL tini (8)] exec /app/migrate.sh failed: Permission denied
Successfully tagged app-registry-local.aldryn.net/agrowdevapi-test-37ae123fee35488aa7afaf88779408b0.2403de75863d452293464511e6f01f0d:rel-57c445067a40479da6af0e140792c18a finished docker build ===== docker migrate release ===== [FATAL tini (6)] exec /app/migrate.sh failed: Permission denied -
How to override ModelMultipleChoiceField to pass empty_label
I have a Model and ModelForm: class Question(models.Model): quiz = models.ManyToManyField( Quiz, blank=True) class MCQuestionForm(forms.ModelForm): quiz = forms.ModelMultipleChoiceField( queryset=None, required=False, empty_label="Something", widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') class Meta: model = MCQuestion exclude = () def __init__(self, *args, **kwargs): self.user = (kwargs.pop('user', None)) super(MCQuestionForm, self).__init__(*args, **kwargs) super_role = self.user.role subs_id = self.user.subordinates.values_list('role', flat=True) sub_roles = EmployeeType.objects.filter(pk__in=subs_id) cats = Category.objects.filter(groups=super_role) | Category.objects.filter(groups__in=sub_roles) self.fields['quiz'].queryset = Quiz.objects.filter(category__in=cats) ..where I need to add an empty_label to the ModelMultipleChoiceField. When I pass empty_label="Something" it give the error: TypeError: init() got multiple values for keyword argument 'empty_label' This is in the Django module: class ModelMultipleChoiceField(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label=None, **kwargs) I need to remove the empty_label=None from the super class of ModelMultipleChoiceField so that it is not passing this argument twice. I tried: class MCQuestionMultipleChoiceField(ModelMultipleChoiceField): def __init__(self, queryset, **kwargs): super().__init__(queryset, empty_label="something", **kwargs) class MCQuestionForm(forms.ModelForm): quiz = MCQuestionMultipleChoiceField( queryset=None, required=False, widget=forms.CheckboxSelectMultiple, help_text='Which tests this question applies to.') ..but it still gives me: TypeError: init() got multiple values for keyword argument 'empty_label' So how do I override it? -
Save empty form field as None in Django
I have a trip model, and the form asks for a outbound flight and an inbound flight, that are both ForeignKeys. How can I save the inbound flight as None, if no flight is selected and actually allow this form field to be empty. This is my form: class NewTrip(ModelForm): def __init__(self, *args, **kwargs): super(NewTrip, self).__init__(*args, **kwargs) self.fields['trip_id'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['destination'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['client'].queryset = Clients.objects.all() class Meta: model = Trip fields = ('trip_id', 'destination', 'client', 'out_flight', 'hotel', 'in_flight') And this is my model: class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem") destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") And this is the view: def newtrip(request): if request.method == 'POST': form = NewTrip(request.POST) if form.is_valid(): form.save() return redirect('trips') else: form = NewTrip() return render(request, 'backend/new_trip.html', {'form': form}) -
Deploying my first Django app to Heroku: Error message 'h12' status '503'
I'm working on my first app, and I've avoided having to ask any questions so far, but here we are at deployment. Here is my code: (Note: The majority of the program is in '/starWarsMeals/djangoStarWarsMeals/appStarWarsMeals/utils.py' and not 'models.py'. I didn't feel a database was my best choice for this app, as the 'swapi' API I am pulling data from may change. I figured it would be best to cache the results of the API vs. updating a database periodically.) https://github.com/RyanLegits/starWarsMeals I am trying to deploy my Django app to Heroku, but I get the following 'h12' error code: https://textuploader.com/16beh My suspicion is that the API calls at the beginning of the script in 'utils.py' are taking too long and causing Heroku to time out. However, I'd like a professional opinion before trying to refactor my code. Also, the last thing I changed in the app was setting the environment variables if that is helpful. I tried deploying to Python Anywhere just to see if I could find anymore information. I got the 'Something went wrong' page and related error log: https://textuploader.com/16bez Notes: I did make sure to change 'ALLOWED_HOSTS' in 'settings.py' for each attempted deploy. I tried setting it to … -
Using requests module with Django APITestCase and APIClient?
I'm trying to test my command line client with Django. I want to use the requests module in my client to fetch data from Django, but I'm testing this inside an APITestCase class so I can create factories using Factory_Boy. I get a connection refused error. The file in my front-end to call the view: from . import urls import requests, json HEADERS = {'content-type':'application/json'} BASE_URL = 'http://127.0.0.1:80/' def post(url, **data): query = json.dumps(data) r = requests.post(BASE_URL+url, data=query, headers=HEADERS) return r.json() def get(url, **data): query = json.dumps(data) r = requests.get(BASE_URL+url, data=query, headers=HEADERS) return r.json() The tests file for Django app, inside a APITestCase class: def setUp(self): self.client = APIClient() self.populate_addresses() self.populate_carriers() self.populate_drivers() def test_requests(self): a = query.query_address(err_msg='Stop not found.', conf_msg='Create new stop.') def populate_addresses(self): self.Address__A1 = factories.AddressFactory( name='BANDINI', city='CHATSWORTH', zip_code='92392', state='CA', street='12345 BANDINI BLVD') self.Address__A2 = factories.AddressFactory( name='BALL METAL', city='FAIRFIELD', zip_code='92392', state='CA', street='2400 HUNTINGTON BLVD') -
Cant start new app in django when I split settings.py file
I splited my settings.py like this: # __init__.py from .base import * # noqa try: from .local_settings import * # noqa except ImportError: message = 'ERROR: Unable to import local_settings. Make sure it exists.' raise ImportError(message) # base.py """ Django settings for app project. Generated by 'django-admin startproject' using Django 3.0.4. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/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.dirname(os.path.abspath(__file__)))) # Add the apps folder to python path os.sys.path.append(os.path.join(BASE_DIR, 'apps')) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] try: from .local_settings import * # noqa except ImportError: message = 'ERROR: Unable to import local_settings. Make sure it exist.' raise ImportError(message) and: # local_settings.py import os … -
Django: ORA:01461: can bind a LONG value only for insert into a LONG column
I've made a binary field in my model (flal_file = models.BinaryField()) for inserting binary data in the database. Database column is blob field. I get that error when creating an object (insert). Commenting out flal_file prevents this error. I don't know why I get this error, since this is a binary field. Is that a bug with older versions of Django? Can anyone help me debug this issue? b = DocFileAllocation.objects.using('db_test_').create( flal_file=uploaded_data, #binary data flal_id_no=seq_doc_file, bmeta_id_no=seq_metadata, flal_file_subject=subject, ) b.save(using='db_test_') -
Not redirecting to other webpage after executing Django view
i have a view - user types some data in input (in scraping.html), data is subjected to action and score should be displayed on next webpage (scrapingscore.html). My problem is that after clicking submit button, website 'scraping' is refreshing and nothing happens, only input with textfield disappears. my view: def scraping(request): rootlink = 'https://www.transfermarkt.pl' link = 'https://www.transfermarkt.pl/schnellsuche/ergebnis/schnellsuche?query=' if request.method == 'POST': data = request.POST.get("textfield") if data is None: empty = 'Data is empty' return TemplateResponse(request, 'scrapingscore.html', {'empty':empty}) else: data = data.replace(" ", "+") search = link + data + '&x=0&y=0' req = Request( search, data=None, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' } ) req = urlopen(req).read() soup = BeautifulSoup( req, features="lxml" ) anchor = soup.find("a",{"class":"spielprofil_tooltip"}) link = anchor.get("href") original_link = rootlink + link return TemplateResponse(request, 'scrapingscore.html', {'original_link':original_link}) scraping.html <form action="{% url 'scraping' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input name="text" type="text" /> <input type="submit" value="submit"> </form> my url to scraping, i don't have url to scrapingscore, maybe should i have with this view? path('scraping', views.scraping, name='scraping'), I don't know how to solve this problem - now 'scrapingscore' webpage does not appear. -
ValueError: The 'image' attribute has no file associated with it
is there something wrong with my code? i already run makemigrations and migrate, and i can see the picture i saved on the admin site, but why when i try to call this picture on my html i received this error? this is my html {% for perfume in s %} <img src="{{perfume.image.url}}" width="192px" height="192px" class="class"> {% endfor %} my views.py s = Perfume.objects.all() .... my models.py class Perfume(models.Model): image = models.ImageField(upload_to='image',null=True, blank=True) .... my settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = '/' import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') def get_success_url(self, request, user): return (get_success_url) my urls.py urlpatterns = [ .... ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How do I create a table to keep track of occasional inventory status updates and how do I use in the django environment?
I have a table that has a list of all the devices that I have in my inventory. Occasionally an audit is performed and the database needs to be updated with the status of the devices (e.g. "Lost", "Found", etc.). For this example I'm just naming the audits "Audit 1" & "Audit 2" but there will be many more. In the past I would just add a new field to the device table for each audit, but I'm trying to make it so all can be done completely through the web ui. The following is an example of how I might do it through mysql. But in my new environment, I'm using django and don't have a clue on how to duplicate this. SELECT * FROM inventory_audit; +----+----------------+-----------+-----------+ | id | audit_phase_id | device_id | status_id | +----+----------------+-----------+-----------+ | 1 | 1 | 1 | 2 | | 2 | 1 | 5 | 2 | | 3 | 2 | 2 | 1 | | 4 | 2 | 5 | 1 | +----+----------------+-----------+-----------+ SELECT whole.device_id, l1.a1 AS "Audit 1", l2.a2 AS "Audit 2" FROM (SELECT device_id FROM inventory_audit GROUP BY device_id) AS whole LEFT JOIN (SELECT device_id,status_id AS … -
Display machine learning model's output on a html file i static in django
views.py from django.shortcuts import render from .models import questions from .serializers import approvalSerializers from django.http import JsonResponse from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.decorators import api_view # Create your views here. data = [] def landing_views(request): return render(request, "avasyuapp/landing.html") def ques_views(request): return render(request, "avasyuapp/ques.html") def store_db(request): if request.method == "POST": ans1 = request.POST["answer1"] ans2 = request.POST["answer2"] ans3 = request.POST["answer3"] ans4 = request.POST["answer4"] ans5 = request.POST["answer5"] ans6 = request.POST["answer6"] ans7 = request.POST["answer7"] ans8 = request.POST["answer8"] ans9 = request.POST["answer9"] data.append(ans1) data.append(ans2) data.append(ans3) data.append(ans4) data.append(ans5) data.append(ans6) o1 = questions( ques='Have you motivated yourself to become a good communicator?', ans=ans1) o1.save() o2 = questions( ques='Can you speak in front of group without any nervousness?', ans=ans2) o2.save() o3 = questions( ques='Can you justify you as a good communicator?', ans=ans3) o3.save() o4 = questions( ques='Are you really happy to make communication as your future passion?', ans=ans4) o4.save() o5 = questions( ques='Is your english vocabulary and comprehension strong?', ans=ans5) o5.save() o6 = questions(ques='Are you good at grammar?', ans=ans6) o6.save() o7 = questions( ques='Have you achieved anything till date as a good communicator ?', ans=ans7) o7.save() o8 = questions( ques='Are you a good listener,good reader and are you clear in your … -
Give print option to print database records in django administration
[![I waant to give the print option to print records through a printer from django administration just like the image posted where there is a print icon and when you click it it prints the page somewhat similar to that, I want to have a print option in the rightmost or leftmost top part of the django admin.I've given the search fields but I don't know how are we supposed to get that.Kindly help if Possible.Thanks][1]][1] [1]: https://i.stack.imgur.com/S0Ov1.pngstrong text -
JQuery didn't work as expected with ajax request in django
I am creating a cart( plus, minus and recalculate total) functionality, where I am using ajax and jquery. It works properly only in one button, that is either plus or minus. Sometimes minus button doing reverse that increases the cart number. I don't know where is the bug and which causes that error. Sometimes it updates with the server and suddenly stops and only workes in HTML not updating the backends. I am new with ajax and just following some fiddle for this workes.Here is the jquery and ajax implementation code............ <!-- templates/products/shopping-cart.html --> {% extends 'base.html' %} {% block jquery %} var taxRate = 0.15; var shippingRate = 20.00; var fadeTime = 300; function updateCart(item, qty, del){ var url = "{% url 'create_cart' %}" + '?' + 'item=' + item + '&qty=' + qty; if(del === true){ url += '&delete=y'; } <!-- XHR object or ajax method.Inside this there is a javasctipt object --> return $.ajax({ <!-- This is the URL of the call back function on the server. Remember the view function we created? {% url 'create_cart' %} This code will call that function without reloading the page. --> url: url, <!-- Type key:It takes in the method … -
tinymce has double text box in a blog
I am creating a blog app through django. Above is the post creation form. And Tinymce works fine except the text box inside the text box. This could be removed manually but I want for this not to show up at the first place. I want to remove this but I just cant. What should I do? I have those models, forms and html. models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = HTMLField('Content') date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #featured = models.BooleanField() #categories = models.ManyToManyField(Category) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={ 'id': self.id, 'title': self.title }) @property def get_comments(self): return self.comments.all().order_by('date_updated') @property def comment_count(self): return Comment.objects.filter(blogpost=self).count() @property def view_count(self): return PostView.objects.filter(blogpost=self).count() forms.py class CreateBlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'body'] html {% extends 'base.html' %} {% block content %} <style type="text/css"> .create-form { width: 100%; max-width: 100%; padding: 15px; margin: auto; } .submit-button{ max-width: 200px; } </style> <div class="container"> <div class="row"> <div class="col-lg-7 offset-lg-1"> <form class="create-form" method="post" enctype="multipart/form-data">{% csrf_token %} <!-- title --> <div class="form-group"> <label for="id_title">Title</label> <input class="form-control" type="text" name="title" id="id_title" placeholder="Title" required autofocus> </div> <!-- Body --> <div class="form-group"> <label for="id_body">Content</label> {{form.media}} …