Query data using filter Django/python - python
I'm pretty new to the Django backend framework. I have been able to easily query data, but now I'm trying to filter that data. When I run the application it will load the landing page and other pages, but when I try to naviagate to the FRReports page I get
"Error during template rendering
In template C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html, error at line 16
'webdart' is not a registered namespace"
Any ideas or guidance?
urls.py
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.DocRepositoryListView.as_view(), name='webdart-documents_FRReports'),
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'),
#path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
.
.
.
views.py
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
class DocRepositoryListView(ListView):
model = DocRepository
template_name = 'webdart/FRReports.html'
def get_context_data (self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset())
return context
class documents_FRReports(DetailView):
model = DocRepository
template_name = 'webdart/FRReports.html'
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', {'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
def data_mcv(request):
return render(request, 'webdart/mcvHTML.html');
def data_viewer(request):
return render(request, 'webdart/viewerHTML.html');
def data_multiSiteReport(request):
return render(request, 'webdart/multiSiteReport.html');
def documents_antennaBias(request):
pdfPath = DocRepository.objects.all()
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "RTS Range Bias":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
test = "reversed"
return render(request, 'webdart/antennaBias.html', {'pdfPath': pdfPath,'test': test, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#def documents_FRReports(request):
# return render(request, 'webdart/FRReports.html')
.
.
.
filters.py
import django_filters
from webdart.models import DocRepository
class DocRepositoryFilter(django_filters.FilterSet):
class Meta:
model = DocRepository
fields = ('file_location',)
models.py
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
def __str__(self):
return self.file_location
class Meta:
managed = False
db_table = 'doc_repository'
base.html
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/main.css' %}" />
<meta charset="utf-8">
<title>{% block title %}WeB DARt{% endblock %}</title>
<link rel="icon" href="{% static 'media/wd.png' %}" type="image/x-icon">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"></script>
<div class="CUI_banner_top">CUI</div>
</head>
<body class="test_margin" {% block data_status %}{% endblock %}>
<nav class="navbar navbar-expand-md bg_home ">
<div class="container-fluid ">
<div class="">
<div class="row aaa">
<img src="{% static 'media/logo.png' %}">
<!-- WeB DARt
<p class="nav_logo ">Web Based Data Analysis and Repository</p>
</div>
-->
</div>
</div>
<button class="navbar-toggler bg-light btn-sm py-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="text-dark bg-light h6">Menu</span>
</button>
<div class="collapse navbar-collapse px-4 nav_center" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="">
<a class="nav-link bg_home px-4 dropdown_hover" aria-current="page" href="{% url 'webdart-home' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link bg_home px-4 dropdown_hover" href="{% url 'webdart-data' %}">Data</a>
</li>
<div class="collapse navbar-collapse px-4 dropdown show ">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_documents()">Documents</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-documents_antennaBias' %}">Antenna Bias</a>
<a class="dropdown-item" href="{% url 'list' %}">F&R Reports</a>
<a class="dropdown-item" href="{% url 'webdart-documents_IERSBulletinA' %}">IERS Bulletin A</a>
<a class="dropdown-item" href="{% url 'webdart-documents_IERSBulletinB' %}">IERS Bulletin C</a>
<a class="dropdown-item" href="{% url 'webdart-documents_NRF' %}">NRF</a>
<a class="dropdown-item" href="{% url 'webdart-documents_OCNBandwidth' %}">OCN Bandwidth Limits</a>
<a class="dropdown-item" href="{% url 'webdart-documents_ONDLC' %}">ONDLC</a>
<a class="dropdown-item" href="{% url 'webdart-documents_ORL' %}">ORL</a>
<a class="dropdown-item" href="{% url 'webdart-documents_RAPID' %}">RAPID</a>
<a class="dropdown-item" href="{% url 'webdart-documents_SystemAvail' %}">System Availability</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_schedule()">Schedule</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-schedule_launch' %}">Launch Schedule</a>
<a class="dropdown-item" href="{% url 'webdart-schedule_maintenance' %}">Maintenance Schedule</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show test">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_support()">Support</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'webdart-support_help' %}">Help</a>
<a class="dropdown-item" href="{% url 'webdart-support_contact' %}">Contact</a>
<a class="dropdown-item"href="{% url 'webdart-support_networkRequest' %}">Network Request</a>
</div>
</div>
</ul>
</div>
Documents
Antenna Bias
F&R Reports
IERS Bulletin A
IERS Bulletin C
NRF
OCN Bandwidth Limits
ONDLC
ORL
RAPID
System Availability
FRReports.html
{% extends 'webdart/base.html' %}
{% load static %}
{% block title %} WeB DARt - Home {% endblock %}
{% block content %}
<div class="container " >
<div class="row" >
<div class="col-md-6 offset-md-4 my-5 ">
<h1 class="text-decoration-underline">
F&R Report Documents
<h1>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
</tr>
</table>
</div>
{{ filter.form }}
<ul>
{% for element in filter.qs %}
<li>
a{{ element.file_location }}
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I think that your error is in your template tag {% url 'webdart:detail' element.id %}. I believe that when you use the {% url %}, the first argument you give to it is the name of a path in your urlpatterns. If your link is trying to go to your path:
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports')
Then your template tag should be something like:
{% url 'webdart-documents_FRReports' element.id %}
Sadly, I wasn't able to get it working with the code originally used. I was able to do filtering within views.py:
"""
Views for webdart.
"""
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
def docRepo(request):
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
if request.method == "GET" and len(request.get_full_path().split("?")) > 1 and "page" not in request.get_full_path().split("?")[1]:
if "choice=date_newToOld" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
elif "choice=date_oldtoNew" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('date_on_doc')
elif "choice=date_range" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("&"))
greaterThanDate = request.get_full_path().split("&")[1].split("=")[1]
lessThanDate = request.get_full_path().split("&")[2].split("=")[1]
print("----------------" + greaterThanDate + lessThanDate)
pdfPath = DocRepository.objects.all().filter(date_on_doc__lte=lessThanDate)
pdfPath = pdfPath.filter(date_on_doc__gte=greaterThanDate)
pdfPath = pdfPath.order_by("-date_on_doc")
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "F and R Reports":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
return render(request, 'webdart/FRReports.html', {'pdfPath': pdfPath, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', {'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository"})
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
And then I was able to manipulate that view within the template (I created a template below called document_static.html so I can just include it in the other document pages:
{% load static %}
<div class="container no_margin" >
<div class="row" >
<div class="pagination d-flex flex-row-reverse">
<span class="step-links ">
{% if contacts.has_previous %}
<a class="page_button" href="?page=1"><<</a>
<a class="page_button" href="?page={{ contacts.previous_page_number }}"><</a>
{% endif %}
<span class="current">
Page {{ contacts.number }} of {{ contacts.paginator.num_pages }}
</span>
{% if contacts.has_next %}
<a class="page_button" href="?page={{ contacts.next_page_number }}">></a>
<a class="page_button" href="?page={{ contacts.paginator.num_pages }}">>></a>
{% endif %}
<div class="show filter_div dropup">
<a class="filter_button" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">⩸</a>
<div class="dropdown-menu navDrop filter_drop" aria-labelledby="navbarDropdown">
<p>Sort by:</p>
<form method="GET">
<input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>
<label class="" for="date_newToOld">Date - New to old</label>
<br />
<input type="radio" id="date_oldtoNew" name="choice" value="date_oldtoNew" />
<label for="date_oldtoNew">Date - Old to new</label>
<br />
<input type="radio" id="date_range" name="choice" value="date_range" />
<label class="" for="date_range">Date range</label>
<div class="date_range">
<label class="" for="date_range">Start date</label>
<input type="date" id="start" name="date" value="{% now "Y-m-d" %}" min="2000-01-01" max="{% now "Y-m-d" %}">
<label class="" for="date_range">End date</label>
<input type="date" id="start" name="date" value="{% now "Y-m-d" %}" min="2000-01-01" max="{% now "Y-m-d" %}">
</div>
</select>
<div class="filter_button_submit_center">
<input class="filter_button_submit" type="submit" value="Filter">
</div>
</form>
</div>
</div>
</span>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
<th>Comments</th>
</tr>
<tr>
{% for o in contacts %}
{% if 0 < forloop.counter and forloop.counter < viewsPerPage %}
<td><a id="open" class="p-0 m-0 fw-bold doc_link">{{ o.title }} </a></td>
<td>{{ o.date_on_doc }}</td>
<td>
<button type="button" class="doc_comments_btn" data-toggle="modal" data-target="#antennaCommentBoxTest{{ forloop.counter0 }} ">Comments</button>
<div class="modal fade document_comment_modal" id="antennaCommentBoxTest{{ forloop.counter0 }}">
<div class="modal-dialog">
<div class="modal-content">
<div style="justify-content: center; display: block;" class="modal-header">
<button type="button" class="doc_comment_close_btn" data-dismiss="modal">×</button>
<h3 id="antennaCommentBoxTest{{ forloop.counter0 }}"><b style="font-size: 75%;">{{ o.title }} - Comments</b></h3>
</div>
<div class="modal-body">
<p class="doc_comment_feed" id="commentFeed">This document has no comments yet.</p>
<form>
<textarea id="newCommentBlock" rows="5" class="doc_comment_textarea" placeholder="Add a Comment" required></textarea>
<br><button type="button" class="doc_comment_submit_btn" onclick="postComment()">Post</button><br>
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
{% endif %}
{% endfor %}
</table>
</div>
</div>
Here is a document page (IERSBulletinA.html):
{% extends 'webdart/base.html' %}
{% load static %}
{% block title %} WeB DARt - Home {% endblock %}
{% block content %}
<div class="container " >
<div class="row " >
<div class="col-md-6 offset-md-4 my-5">
<h1 class="text-decoration-underline">IERS Bulletin A Documents<h1>
</div>
</div>
</div>
{% include "webdart/document_static.html" %}
{% endblock %}
And here is urls.py for anybody interested:
"""
Definition of urls for webdart.
"""
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
from django.views.generic import ListView, DetailView
from django.views import View
from .models import DocRepository
from django.http import HttpResponse
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.docRepo, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
path('IERSBulletinB/', views.documents_IERSBulletinB, name='webdart-documents_IERSBulletinB'),
path('NRF/', views.documents_NRF, name='webdart-documents_NRF'),
path('OCNBandwidth/', views.documents_OCNBandwidth, name='webdart-documents_OCNBandwidth'),
path('ONDLC/', views.documents_ONDLC, name='webdart-documents_ONDLC'),
path('ORL/', views.documents_ORL, name='webdart-documents_ORL'),
path('RAPID/', views.documents_RAPID, name='webdart-documents_RAPID'),
path('SystemAvail/', views.documents_SystemAvail, name='webdart-documents_SystemAvail'),
path('launch/', views.schedule_launch, name='webdart-schedule_launch'),
path('maintenance/', views.schedule_maintenance, name='webdart-schedule_maintenance'),
path('help/', views.support_help, name='webdart-support_help'),
path('contact/', views.support_contact, name='webdart-support_contact'),
path('networkRequest/', views.support_networkRequest, name='webdart-support_networkRequest'),
path('accountDetails/', views.user_accountDetails, name='webdart-user_accountDetails'),
path('signOut/', views.user_signOut, name='webdart-user_signOut'),
path('timeOut/', views.user_timeOut, name='webdart-user_timeOut'),
path('accountRequest/', views.user_accountRequest, name='webdart-user_accountRequest'),
path('', AboutView.as_view(template_name="data-stationData")),
]
And an excerpt from models.py too, because why not:
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
class Meta:
managed = False
db_table = 'doc_repository'
Related
How to combine multiple models into one view template in django
I have two models class Post(models.Model): title = models.CharField(max_length=100) body = RichTextField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank = True) image = ResizedImageField(size=[250, 200], upload_to='img') and class Politics(models.Model): title = models.CharField(max_length=100) body = RichTextField(max_length=1000000) created_at = models.DateTimeField(default=datetime.now, blank = True) image = ResizedImageField(size=[250, 200], upload_to='img',blank = True) I want to combine them both into one template view and render them on the index.html Here is my view function def index(request): politics = Politics.objects.all() return render(request, 'index.html', {'politics':politics, 'posts': Post.objects.all()}) index.html (posts part) <section id="posts" class="posts"> <div class="container" data-aos="fade-up"> <div class="row g-5"> {% for post in posts reversed %} {% if forloop.counter < 5 %} <div class="post-entry-1 col-lg-2 box mx-1"> <img src="{{post.image.url}}" class="post_img"> <div> <div class="post-meta"><span class="date">{{post.category}}</span> <span class="mx-1">•</span> <span>{{post.created_at}}</span></div> <h2>{{post.title}}</h2> </div> <p class="mb-4 d-block">{{post.body|truncatewords:75}}</p> <div class="d-flex align-items-center author"> <div class="photo"><img src="{% static 'assets/img/person-1.jpg' %}" alt="" class="img-fluid"></div> <div class="name"> <h3 class="m-0 p-0">OlePundit</h3> </div> </div> </div> (politics part) <div class="row"> {% for politic in politics%} {% if forloop.counter < 11 %} <div class="post-entry-1 col-2 mx-1"> <img src="{{politic.image.url}}" alt="" class="post_img"> <div class="post-meta"> <span class="date">{{politic.category}}</span> <span class="mx-1">•</span> <span>{{politic.created_at}}</span> </div> <h2 class="mb-2">{{politic.title}}</h2> <span class="author mb-3 d-block">Ole Pundit</span> <p class="mb-4 d-block">{{politic.body| safe | truncatewords:20}}</p> </div> {% endif %} {% endfor %} </div> However, only the 'politics' object is being rendered. What could be wrong?
try this or the problem will be in template file def index(request): politics = Politics.objects.all() posts = Post.objects.all() return render(request, 'index.html', {'politics':politics, 'posts': posts})
The modal appears but the profile edit form don't appear on it, any idea why?
On my social app that I'm working on, there's still one issue. On my ProfileDetailView, to click on "Edit Profile" the modal form appear but there's no form. It was working before but when I fixed the close button and I don't know what happened.. I copied the modal html from bootstrap so i probably deleted/changed something and forgot to re-do it.. Form: from django import forms from .models import Profile, Post, Comment class ProfileModelForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'last_name', 'bio', 'avatar') class PostModelForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={'rows':2, 'cols': 30})) class Meta: model = Post fields = ('content', 'picture') class CommentModelForm(forms.ModelForm): body = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Add a comment...', 'class':'comment'})) class Meta: model = Comment fields = ('body',) Views: from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from django.shortcuts import render, redirect, resolve_url, get_object_or_404 from django.urls import reverse, reverse_lazy from django.core import serializers from django.core.paginator import Paginator from django.contrib import messages from django.contrib.auth.models import User from django.db.models import Q from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from itertools import chain from .models import Relationship, Post, Profile, Like from django.views.generic import TemplateView, View, UpdateView, DeleteView, ListView, DetailView from .forms import ProfileModelForm, PostModelForm, CommentModelForm def search_view(request): if request.method == "POST": searched = request.POST['searched'] profiles = Profile.objects.filter(slug__contains=searched) return render(request, 'network/search.html', {'searched':searched, 'profiles':profiles}) else: return render(request, 'network/search.html', {}) class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'network/profile.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = User.objects.get(username__iexact=self.request.user) profile = Profile.objects.get(user=user) rel_r = Relationship.objects.filter(sender=profile) rel_s = Relationship.objects.filter(receiver=profile) rel_receiver = [] rel_sender = [] for item in rel_r: rel_receiver.append(item.receiver.user) for item in rel_s: rel_sender.append(item.sender.user) context["rel_receiver"] = rel_receiver context["rel_sender"] = rel_sender context["posts"] = self.get_object().get_all_authors_posts() context["len_posts"] = True if len(self.get_object().get_all_authors_posts()) > 0 else False return context #login_required def profile_view(request): profile = Profile.objects.get(user=request.user) form = ProfileModelForm(request.POST or None, request.FILES or None, instance=profile) confirm = False if request.method == 'POST': if form.is_valid(): form.save() confirm = True context = { 'profile': profile, 'form': form, 'confirm': confirm, } return render(request, 'network/profile.html', context) profile.html: {% extends "network/layout.html" %} {% load static %} {% load crispy_forms_tags %} {% block title %} My Profile {% endblock title %} {% block body %} <!--Modal--> <div class="modal fade" id="profileModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Update Your Profile</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <img width="100px" src="{{object.avatar.url}}"> <form action="", method="POST", enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} {{ form }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update</button> </form> </div> </div> </div> </div> <div> {% if confirm %} <div class="alert alert-info" role="alert">Your profile has been updated!</div> {% endif %} </div> <div class="row py-5 px-4"> <div class="col-md-5 mx-auto"> <!-- Profile widget --> <div class="bg-white shadow rounded overflow-hidden"> <div class="px-4 pt-0 pb-4 cover"> <div class="media align-items-end profile-head"> <div class="profile mr-3"><img src="{{object.avatar.url}}" width="130" class="rounded mb-2 img-thumbnail"></div> <div class="media-body mb-5 text-white"> <h4 class="mt-0 mb-3">{{profile.first_name}} {{profile.last_name}}</h4> <p style="color: black;" class="small mb-4"> <i class="fas fa-map-marker-alt mr-2"></i>{{profile.country}}</p> </div> </div> </div> <div class="bg-light p-5 d-flex justify-content-end text-center"> <ul class="list-inline mb-0"> <li class="list-inline-item"> <h5 class="font-weight-bold mb-0 d-block">{{object.get_posts_num}}</h5><small class="text-muted"> <i class="fas fa-image mr-1"></i>Posts</small> </li> <li class="list-inline-item"> <h5 class="font-weight-bold mb-0 d-block">{{object.get_followers_num}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Followers</small> </li> <li class="list-inline-item"> <h5 class="font-weight-bold mb-0 d-block">340</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Following</small> </li> <li class="list-inline-item"> <h5 class="font-weight-bold mb-0 d-block">{{object.like_count}}</h5><small class="text-muted"> <i class="fas fa-user mr-1"></i>Likes</small> </li> </ul> </div> <div class="ml-2"> {% if object.user not in rel_receiver and object.user not in rel_sender %} <form action="{% url 'send-invite' %}" method="POST"> {% csrf_token %} <input type="hidden" name="profile_pk" value={{object.pk}}> <button type="submit" class=" btn btn-sm btn-success w-btn"><i class="bi-plus-lg"></i> Follow</button> </form> {% endif %} {% if object.user in rel_receiver and request.user not in object.following.all %} <button class="btn btn-sm disabled "><i class="bi-three-dots"></i> Waiting aprroval</button> {% endif %} {% if request.user in object.following.all %} <form action="{% url 'remove-friend' %}" method="POST"> {% csrf_token %} <input type="hidden" name="profile_pk" value={{object.pk}}> <button type="submit" class=" btn btn-sm btn-dark w-btn"><i class="bi-dash-lg"></i> Unfollow</button> </form> {% endif %} </div> <div class="px-4 py-3"> <h5 class="mb-0">About</h5> <button class="btn btn-sm btn-secondary float-right" id="modal-btn" data-toggle="modal" data-target="#profileModal">Edit Profile</button> <div class="p-4 rounded shadow-sm bg-light"> <p class="font-italic mb-0">{{profile.bio}}</p> </div> </div> <div class="py-4 px-4"> <div class="d-flex align-items-center justify-content-between mb-3"> <h5 class="mb-0">Recent posts</h5>Show all </div> {% if len_posts %} <div class="row"> {% for post in posts %} <div class="col-lg-6 mb-2 pr-lg-1 fluid"> {% if post.picture %} <img class="card-img-profile" src="{{post.picture.url}}"> {% endif %} {{post.content}} </div> {% endfor %} {% else %} <h1>This user didn't post anything yet..</h1> {% endif %} </div> </div> </div> </div> </div> </div> {% endblock %} Model: class Profile(models.Model): first_name = models.CharField(max_length=64, blank=True) last_name = models.CharField(max_length=64, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=64, blank=True) avatar = models.ImageField(upload_to='avatars', default='avatar.png') background = models.ImageField(upload_to='backgrounds', default='background.png') following = models.ManyToManyField(User, related_name='following', blank=True) bio = models.TextField(default="No Bio..") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, blank=True) objects = ProfileManager() def __str__(self): return f"{self.user.username}" def get_absolute_url(self): return reverse("profile-view", kwargs={"slug": self.slug}) __initial_first_name = None __initial_last_name = None def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__initial_first_name = self.first_name self.__initial_last_name = self.last_name def save(self, *args, **kwargs): ex = False to_slug = self.slug if self.first_name != self.__initial_first_name or self.last_name != self.__initial_last_name or self.slug=="": if self.first_name and self.last_name: to_slug = slugify(str(self.first_name) + " " + str(self.last_name)) ex = Profile.objects.filter(slug=to_slug).exists() while ex: to_slug = slugify(to_slug + " " + str(get_random_code())) ex = Profile.objects.filter(slug=to_slug).exists() else: to_slug = str(self.user) self.slug = to_slug super().save(*args, **kwargs) def get_followers(self): return self.following.all() def get_followers_num(self): return self.following.all().count() def get_my_posts(self): return self.post_set.all() def get_country(self): return self.post_set.all() def get_following_users(self): following_list = [p for p in self.get_following()] return following_list def get_all_posts(self): users = [user for user in self.get_following()] posts = [] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.post_set.all() posts.append(p_posts) my_posts = self.post_set.all() posts.append(my_posts) if len(posts) > 0: qs = sorted(chain(*posts), reverse=True, key=lambda obj: obj.created) return qs def get_posts_num(self): return self.post_set.all().count() def get_all_authors_posts(self): return self.post_set.all() def get_likes_given_num(self): likes = self.like_set.all() total_liked = 0 for item in likes: if item.value == 'Like': total_liked += 1 return total_liked def get_likes_received_num(self): posts = self.post_set.all() total_liked = 0 for item in posts: total_liked += item.all().count() return total_liked def get_proposals_for_following(self): profiles = Profile.objects.all().exclude(user=self.user) followers_list = [p for p in self.get_following()] available = [p.user for p in profiles if p.user not in followers_list] random.shuffle(available) return available[:3] STATUS_CHOICES = ( ('send', 'send'), ('accepted', 'accepted') ) Update posts html: {% extends "network/layout.html" %} {% block title %} Update Post {% endblock title %} {% block body %} <div class="card center" style="width: 30rem;"> <h3>Update post</h3> <form action="" method="POST" enctype="multipart/form-data" class="form-group"> {% csrf_token %} {{form}} <button type='submit' class="btn float-right btn-sm btn-primary mt-5">Update</button> </form> </div> {% endblock body %} URLs: from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import ( posts_of_following_profiles, like_unlike_post, invites_received_view, invite_profiles_list_view, send_invitation, remove_friends, accept_invitation, reject_invitation, search_view, post_comment_create_view, login_view, logout_view, register, ProfileDetailView, PostDeleteView, PostUpdateView, ProfileListView, ) urlpatterns = [ path("", ProfileListView.as_view(), name="all-profiles-view"), path("posts/", views.post_comment_create_view, name="posts"), path("posts-follow/", posts_of_following_profiles, name="posts-follow"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("liked/", like_unlike_post, name="like-post-view"), path("<pk>/delete", PostDeleteView.as_view(), name="post-delete"), path("<pk>/update", PostUpdateView.as_view(), name="post-update"), path("invites/", invites_received_view, name="invites-view"), path("send-invite/", send_invitation, name="send-invite"), path("remove-friend/", remove_friends, name="remove-friend"), path("invites/accept/", accept_invitation, name="accept-invite"), path("invites/reject/", reject_invitation, name="reject-invite"), path("to-invite/", invite_profiles_list_view, name='invite-profiles-view'), path("search/", views.search_view, name='search-view'), path("<slug>", ProfileDetailView.as_view(), name="profile-view"), ] screenchot Code snippet: <div class="modal-header"> <h5 class="modal-title">Update Your Profile</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <img src="/media/avatars/11892013_911718608883264_3848632245418610369_n.jpg" width="100px"> <form action="" ,="" method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="P2vu2WI916PGSbMOrXD14c9EFmfMVEk3T1vkf9rqsZC7hXD94Dq2Cjo4MVCIiEEp"> </form></div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update</button> </div>
Please how can get the number of listings in a category, i have tried
I have a django app and I need to count the number of listings in a category (as defined by the models below): here is my complete model class Category(models.Model): name = models.CharField(max_length=500) icon = models.ImageField(upload_to='photos/icons/%Y/%m/%d/') def __str__ (self): return self.name class Listing(models.Model): name = models.CharField(max_length=300) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=False, null=True) email = models.EmailField(max_length=300) description = RichTextField(blank=False, null=False) photo_main = models.ImageField(upload_to = 'photos/%Y/%m/%d/') photo_1 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_2 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_3 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) photo_4 = models.ImageField(upload_to = 'photos/%Y/%m/%d/', blank=True, default=True) location = models.CharField(max_length=500, null=True) phone_number = models.CharField(max_length=11, default = "#") website = models.CharField(max_length=150, blank=True, default="#") facebook = models.CharField(max_length=150, blank=True, default="#") instagram = models.CharField(max_length=150, blank=True, default="#") opening_time = models.CharField(max_length=7) closing_time = models.CharField(max_length=7) is_published = models.BooleanField(default=False) posted_date = models.DateTimeField(auto_now_add=True) user_id = models.IntegerField(blank=True) def __str__ (self): return self.name here are my views from django.shortcuts import render from listings.models import Listing from listings.models import Category from testimonies.models import Testimony from our_team.models import Team_Mate from testimonies.models import Testimony from django.db.models import Count def index(request): this part is working perfectly. listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] category = request.GET.get('category') categories = Category.objects.all()[:7] counting listings in a category count_cate = Category.objects.all() cate_count = count_cate.count() if category == None: listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] else: listings = Listing.objects.filter(Category__name=category) here is my context context ={ 'listings': listings, 'categories': categories, 'cate_count': cate_count, } return render(request, 'pages/index.html', context) Here is my html where I want the number of listings in category to show {% extends 'base.html' %} {% load static %} {% block content %} <!-- ======= Intro Section ======= --> <div class="header"> <div class="header-content display-table"> <div class="table-cell"> <div class="container"> <h1 class="header-title text-light text-uppercase pb-3">Explore Bonny Island</h1> <h3 class="text-light">Find. Connect. Share</h3> <div class="search mt-3 px-0 py-1 mx-0"> <form action="{% url 'search' %}" method="GET"> {% csrf_token %} <div class="row d-flex justify-content-center container p-0 m-0 px-1"> <input type="text" name="keywords" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Keyword"> <input type="text" name="location" class="form-control col-lg-3 col-md-12 mx-2 py-4 col-sm-12 my-2 border border-5" placeholder=" Location"> <input type="text" name="category" value="{{ query }}" list="category" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)"> <datalist id="category"> {% for categories in categories %} <option>{{ categories.name }}</option> {% endfor %} </datalist> <button type="submit" class="btn search-bt col-lg-2 col-md-12 mx-2 col-sm-12 py-2 px-2 font-weight-bold my- 2">Search</button> </div> </form> </div> </div> </div> </div> </div><!-- End Intro Section --> <!-- ======== most popular categories ========= --> <section class="main"> <div class="discover pb-1 m-0"> <h2>Explore Categories</h2> <div class="container"> <div class="row justify-content-around m-0 p-0 pt-3"> {% for category in categories %} {% if category %} <div class="col-lg-3 col-md-6 py-2"> <a href="{% url 'listings' %}?category={{ category.name }}" class="card category"> <div class="d-flex justify-content-between align-items-start px-3 m-0 py-2"> <div class="category-name-icon p-0 m-0"> <span class="text-dark font-weight-bold"><img class="category-icon" src="{{ category.icon.url }}"> {{category.name}}</span> </div> <div class="category-list-number text-muted font-weight-bold">{{cate_count}}</div> </div> </a> </div> {% endif %} {% endfor %} <div class="col-lg-3 col-md-6 py-2"> <a href="{% url 'category' %}" class="card category" data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample"> <div class="d-flex justify-content-between = px-3 m-0 py-2"> <i class="font-weight-bold py-1 text-secondary">More Categories...</i> </div> </a> </div> </div> </div> </section> <!-- ======== most popular categories end ======== --> <!-- STRUCTURING THE POPULAR LISTINGS CONTENT--> <section id="popularListings" class="container mb-5 py-5"> <!-- Popular listenings head title--> <div class="sectionTitle d-flex justify-content-between align-items-baseline"> <div class="mainTitleContents"> <h2 class="titleText h2 text-blue">Popular Listings</h2> <p class="subTitleText mb-2">Explore businesses on the island.</p> </div> <div class="filterOption"> All Listings </div> </div> <!-- MAIN POPULAR LISTINGS ROW CONTENT--> <div class="popularListingsRows row py-2"> {% if listings %} {% for listing in listings %} <div class="customCard p-1 m-0 col-lg-3 col-md-4 col-sm-6 mt-sm-3"> <div class="card"> <div class="card-header p-0"> <div class="blank rounded" style="background-image: url('{{ listing.photo_main.url }}'); background-repeat: no-repeat; background-size:cover; width:100%; height: 15em; background- position:center-top" ;></div> </div> <div class="card-body"> <div class="content-details"> <h3 class="m-0 mt-1 mb-2 cardTitle">{{ listing.name }}</h3> <p class="cardSubTitle"> {%autoescape off%} {{ listing.description|striptags|truncatechars:100 }} {%endautoescape%} </p> <a href="{% url 'listing' listing.id %}" class="btn btn-sm bg-blue text- light rounded-none">Read More</a> </div> </div> </div> </div> {% endfor %} {% else %} <div class="col-md-12"> <p class="text-dark">No listings Available</p> </div> {% endif %} </div> </section> {% endblock %} How can I make this code work as intended?
You should call the count method on the list of objects like... if category == None: listings = Listing.objects.order_by('-posted_date').filter(is_published=True)[:6] else: listings = Listing.objects.filter(category__name=category).count() Please ensure where you have Category__name=category you must allow this to match your model field category. In your html: <!-- ======= Intro Section ======= --> <form action="{% url 'search' %}" method="GET"> {% csrf_token %} <div class="row d-flex justify-content-center container p-0 m-0 px-1"> ... <!--<input type="text" name="category" value="{{ query }}" list="category" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)">--> <!-- Remove value="{{ query }}" --> <input type="text" name="category" list="categories" class="form-control col-lg-3 col-md-12 col-sm-12 mx-2 py-4 my-2 border border-5" placeholder=" Category (All)"> <!-- Should be category in categories instead of categories in categories --> <datalist id="categories"> {% for category in categories %} <option value="{{ category.name }}"> <!-- Setting the value here... --> {% endfor %} </datalist> ... </div> </form>
I solved the it by calling the name of the category i want to count but am still to look for a way to count it without specifying the category name. cate_count = Listing.objects.filter(category__name="Catering services").count()
Add User Functionality at custom admin side - Django
I am working on a project in Python Djnago 3.1.2, and developing a custom admin side, where admin can perform different functionalities. At the admin site I want to add functionality to add user and I have created a function but there is some error but I could not get it. Here is My models. models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') def __str__(self): return "{}".format(self.user_id) This is the function I have created and I think error is in my views. views.py def addUser(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/admin1/addUser') else: addUser_show = User.objects.all() # start paginator logic paginator = Paginator(addUser_show, 3) page = request.GET.get('page') try: addUser_show = paginator.page(page) except PageNotAnInteger: addUser_show = paginator.page(1) except EmptyPage: addUser_show = paginator.page(paginator.num_pages) # end paginator logic return render(request, 'admin1/addUser.html', {'addUser_show': addUser_show, "form":form}) urls.py path('addUser/', views.addUser, name="admin-add-user"), Form I am using to get the create user form. forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'first_name', 'last_name', 'avatar', 'email', 'password1', 'password2', 'gender', 'role'] addUser.html {% extends 'admin1/layout/master.html' %} {% block title %}Add User{% endblock %} {% block main %} <div class="container"> <div class="row"> <div class="col-lg-2"></div> <div class="col-lg-10"> <button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add User </button> <div class="modal fade" id="modal-primary"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Add User</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button> </div> <div class="modal-body mt-2"> <form action="{% url 'admin-add-user'%}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <table border="1" class="table table-bordered border border-info"> {{form.as_p}} <div class="modal-footer justify-content-right"> <input type="Submit" name="Submit" value="Submit" class="btn btn-outline-success"> <button type="button" class="btn btn-outline-danger" data-dismiss="modal">Close </button> </div> </table> </form> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.modal --> <br> <div class="container-fluid "> <div class="row"> <div class="card mt-2 border border-secondary"> <div class="card-header"> <h3 class="card-title ">Product Table</h3> </div> <!-- /.card-header --> <div class="card-body"> <table class="table table-bordered border border-info"> <thead> <tr> <th>User Id</th> <th>User Name</th> <th>User First Name</th> <th>User Last Name</th> <th>User Email</th> <th>User Gender</th> <th>User Avatar</th> <th>Role</th> <th>Action</th> </tr> </thead> <tbody class="justify-content-center"> {% for x in addUser_show %} <tr> <td>{{x.user_id}}</td> <td>{{x.username}}</td> <td>{{x.first_name}}</td> <td>{{x.last_name}}</td> <td>{{x.email}}</td> <td>{{x.gender}}</td> <td><img src="{{x.avatar.url}}" alt="{{x.avatar}}" height="100" width="100"> </td> <td>{{x.role}}</td> <td><a href="#" class="btn btn-outline-primary mt-2"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></a> <a href="#" class="btn btn-outline-danger mt-2"><i class="fa fa-trash" aria-hidden="true"></i></a> <a href="#" class="btn btn-outline-warning mt-2"><i class="fa fa-eye" aria-hidden="true"></i></a> </td> </tr> {% endfor %} </tbody> </table> </div> <!-- /.card-body --> <div class="card-footer clearfix "> <ul class="pagination pagination-sm m-0 justify-content-center"> {% if addUser_show.has_previous %} <li class="page-item"><a class="page-link" href="?page={{product_show.previous_page_number}}"> Previous </a> </li> {% endif%} {% for x in addUser_show.paginator.page_range %} {% if addUser_show.number == x %} <li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li> {% else%} <li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li> {% endif %} {% endfor %} {% if addUser_show.has_next %} <li class="page-item"><a class="page-link" href="?page={{addUser_show.next_page_number}}"> Next </a> </li> {% endif %} </ul> </div> </div> <!-- /.card --> </div> </div> </div> </div> </div> {% endblock %} Here I want to make admin able to create new user. but I am getting error shown below while submission of form. My form works proper till it display the form , but when I fill up details and submit the form it shows the following error. If possible please write the answer.
I have tried something and its working for me but I don't know that it is right way to do it or not. view.py def addUser(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('/admin1/addUser') addUser_show = User.objects.all() # start paginator logic paginator = Paginator(addUser_show, 3) page = request.GET.get('page') try: addUser_show = paginator.page(page) except PageNotAnInteger: addUser_show = paginator.page(1) except EmptyPage: addUser_show = paginator.page(paginator.num_pages) # end paginator logic return render(request, 'admin1/addUser.html', {'addUser_show': addUser_show,"form":form})
Comment is not displaying in django after submission
I have tried to submit a comment from app rather than django admin. Comment is not displaying when submitted from my created app. But it is displaying when I add a comment from django admin app. May be I am doing something wrong in views.py file. Can anyone help me on this? Thank you. views.py: #login_required def book_review(request,id): book = get_object_or_404(Bookslist, id=id) comment=Comment.objects.all().filter(post_id=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user_id = request.user post.message= comment post.save() return redirect('book_review', id=id) else: form=CommentForm() return render(request, "books/book_review.html", {'book':book, 'comment':comment, 'form': form}) models.py: class Comment(models.Model): message= models.TextField('Message',null=True) date_comment=models.DateTimeField(default=now, null=True) user_id= models.ForeignKey(User, on_delete=models.CASCADE,null=True) post_id=models.ForeignKey(Bookslist,on_delete=models.CASCADE,null=True) forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['message', ] book_review.html: {% extends 'books/base.html' %} {% load static %} {% block stylesheet %} <link rel="stylesheet" href="{% static 'accounts/accounts.css' %}"> {% endblock %} {% block content %} <div class = "container"> <ul class = "nav nav-tabs" id = "myTab" role = "tablist"> <li class = "nav-item"> <a class = "nav-link active" id = "summary-tab" data-toggle = "tab" href = "#summary" role = "tab" aria-controls = "summary" aria-selected = "true">Summary</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "characters-tab" data-toggle = "tab" href = "#characters" role = "tab" aria-controls = "characters" aria-selected = "false">Characters</a> </li> <li class = "nav-item"> <a class = "nav-link" id = "relatedbooks-tab" data-toggle = "tab" href = "#relatedbooks" role = "tab" aria-controls = "relatedbooks" aria-selected = "false">Related Books</a> </li> </ul> <div class = "tab-content" id = "myTabContent"> <div class = "tab-pane fade show active" id = "summary" role = "tabpanel" aria-labelledby = "summary-tab"><br><br> {{book.summary}} </div> <div class = "tab-pane fade" id = "characters" role = "tabpanel" aria-labelledby = "characters-tab"><br><br> {{book.c1}}<br><br>{{book.c2}}<br><br>{{book.c3}}<br><br>{{book.c4}}<br><br>{{book.c5}}<br><br> {{book.c6}}<br><br>{{book.c7}}<br><br>{{book.c8}}<br><br>{{book.c9}}<br><br> {{book.c10}} </div> <div class = "tab-pane fade" id = "relatedbooks" role = "tabpanel" aria-labelledby = "relatedbooks-tab">Content for related books tab</div> </div> <br> <br> <div class="container"> <form method="post" class="mb-4"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlTextarea1">Leave your comment:</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <button type="submit" class="btn btn-success">Post</button> </form> {% for com in comment %} <div class="card mb-2"> <div class="card-body p-3"> <div class="row"> <div class="col-2"> <img src="{% static 'images/icon2.webp' %}" alt="{{ com.user_id }}" class="w-100"> <small>Posts: {{ com.count }}</small></div> <div class="col-10"> <div class="row mb-3"> <div class="col-6"> <strong class="text-muted">{{ com.user_id }}</strong> </div> <div class="col-6 text-right"> <small class="text-muted">{{ com.date_comment }}</small> </div> </div> {{ com.message }}<br><br> {% if com.user_id == user %} <button type="button" class="btn btn-primary">Reply</button> {% endif %} </div> </div></div></div></div> {% endfor %} </div> </div> </div> <!-- jQuery library --> <script src = "https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity = "sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin = "anonymous"> </script> <!-- Popper --> <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity = "sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin = "anonymous"> </script> <!-- Latest compiled and minified Bootstrap JavaScript --> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity = "sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> {% endblock %}
You need to add the post_id to the newly created comment. Like so: post.post_id = id Also make sure you are using the correct naming for your variables i believe post should be comment in this scenario based on the form being of CommentForm: model = Comment This replacement would make for sense for the code: if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user_id = request.user comment.message= comment comment.post_id = id comment.save()