Related
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>
In a view I have 3 forms:
forms.py
class PostForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(PostForm, self).__init__(*args, **kwargs)
class Meta:
model = Post
fields = ['subtitle', 'latitude', 'longitude', 'tags', 'body']
widgets = {
'body': forms.Textarea(attrs={'class': 'log-body editable'}),
'tags': forms.TextInput(attrs={'id': 'tags-field', 'class': 'log-form-field'}),
'latitude': forms.TextInput(attrs={'id': 'latitude-field', 'class': 'log-form-field'}),
'longitude': forms.TextInput(attrs={'id': 'longitude-field', 'class': 'log-form-field'}),
'subtitle': forms.TextInput(attrs={'id': 'subtitle-field', 'class': 'log-form-field'}),
}
labels = {
'subtitle': 'Subtitle:',
'tags': 'Tags:',
'latitude': 'Latitude',
'longitude': 'Longitude',
'body': ''
}
class ImageForm(forms.ModelForm):
images = forms.ImageField(label='Images', widget=forms.ClearableFileInput(
attrs={
'multiple': True,
'class': 'file-upload',
'id': 'file-upload-button-image',
'name': 'images'}
)
)
class Meta:
model = PostImage
fields = ('images',)
class VideoForm(forms.ModelForm):
videos = forms.FileField(label='Videos', widget=forms.ClearableFileInput(
attrs={
'multiple': True,
'class': 'file-upload',
'id': 'file-upload-button-video',
'name': 'images'
}
)
)
class Meta:
model = PostVideo
fields = ('videos',)
And I have a template that creates a post and stores the videos and pictures and that works great. Where I'm having a hard time is updating a 'Post'.
class PostEditView(TemplateView):
template_name = 'Logging/edit view.html'
post_form_class = PostForm
image_form_class = ImageForm
video_form_class = VideoForm
def get_context_data(self, **kwargs):
context = super(PostEditView, self).get_context_data(**kwargs)
context['post_pk'] = self.kwargs['pk']
context['post_form'] = PostForm(instance=Post.objects.get(pk=self.kwargs['pk']))
context['image_form'] = ImageForm(empty_permitted=True, use_required_attribute=False)
context['video_form'] = VideoForm(empty_permitted=True, use_required_attribute=False)
context['images'] = PostImage.objects.filter(post_id=self.kwargs['pk'])
context['videos'] = PostVideo.objects.filter(post_id=self.kwargs['pk'])
return context
def post(self, request, *args, **kwargs):
context = self.get_context_data()
post_data = request.POST or None
if post_data.get('Delete'):
if len(post_data.getlist('img-index[]')) > 0:
for i in post_data.getlist('img-index[]'):
PostImage.objects.filter(id=i).delete()
if len(post_data.getlist('vid-index[]')) > 0:
for i in post_data.getlist('vid-index[]'):
PostVideo.objects.filter(id=i).delete()
print(post_data)
post_form = PostForm(data=post_data, instance=Post.objects.get(pk=self.kwargs['pk']), prefix='post')
print(post_form.is_bound)
post_form.is_valid()
print(post_form.errors)
images = request.FILES.getlist('image-images')
videos = request.FILES.getlist('video-videos')
if post_form.is_valid():
print('valid form')
for i in images:
instance = PostImage(image=i, post=context['post_pk'])
instance.save()
for v in videos:
instance = PostVideo(video=v, post=context['post_pk'])
instance.save()
return super(PostEditView, self).render_to_response(context)
def form_save(self, form, request):
obj = form.save(commit=False)
obj.user = request.user
obj.author = request.user.first_name + ' ' + request.user.last_name
obj.event_type = 'Log Entry'
obj.save()
messages.success(self.request, "{} posted successfully".format(obj))
return obj
When I call is_valid() on post_form it always says false, although it does say its bound. My post object does contain the data from the form in my template, including a csrf token, but for some reason the form is never valid and says that all the fields are empty.
from print(post_data):
<QueryDict: {'csrfmiddlewaretoken': ['h5uxuACKsvBcO4lrPB7yKbYgr0BsASEklT3GTp6R3t8na13TadAfjbihl2VyGvdC'], 'subtitle': ['Test with photos'], 'latitude': ['48.000'], 'longitude': ['112.000'], 'tags': ['[]'], 'images': [''], 'videos': [''], 'body': ['<p>body test 2 saa</p>']}>
from print(post_form.is_bound):
True
from print(post_form.errors):
<ul class="errorlist">
<li>subtitle<ul class="errorlist"><li>This field is required.</li></ul></li><li>latitude
<ul class="errorlist"><li>This field is required.</li></ul></li><li>longitude
<ul class="errorlist"><li>This field is required.</li></ul></li><li>tags
<ul class="errorlist"><li>This field is required.</li
></ul></li><li>body
<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
Models.py
class Post(models.Model):
class Status(models.TextChoices):
active = 'Active'
inactive = 'Inactive'
user = models.ForeignKey(Account, on_delete=models.CASCADE)
author = models.CharField(max_length=255)
title = models.CharField(max_length=80, default='Log Entry: ' + datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))
subtitle = models.CharField(max_length=255)
latitude = models.DecimalField(decimal_places=3, max_digits=6)
longitude = models.DecimalField(decimal_places=3, max_digits=6)
post_time = models.DateTimeField(auto_now_add=True)
tags = TaggableManager()
body = models.TextField()
history = HistoricalRecords()
event_type = models.CharField(max_length=50, choices=EventType.choices, default='Log Entry', editable=False)
status = models.CharField(max_length=10, choices=Status.choices, default='Active')
def __str__(self):
return 'Post by: ' + str(self.user) + " on: " + self.post_time.strftime("%m/%d/%Y at %H:%M:%S")
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_media/%s/%s" % (slug, filename)
class PostImage(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.PROTECT)
image = models.ImageField(upload_to=get_image_filename, verbose_name='Image')
def filename(self):
return self.image.name.split('/')[-1]
class PostVideo(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.PROTECT)
video = models.FileField(upload_to=get_image_filename, verbose_name='Video')
def filename(self):
return self.video.name.split('/')[-1]
template:
{% extends 'layout/base.html' %}
{% load static %}
{% block titleblock %}New Log{% endblock %}
{% block header %}
<script src="{% static 'Logging/js/medium-editor.min.js' %}"></script>
<link rel="stylesheet" href="{% static 'Logging/css/medium-editor.min.css' %}">
<link rel="stylesheet" href="{% static 'Logging/css/new_post.css' %}">
{% endblock %}
{% block bodyblock %}
<form class="post-form" id="post-form" enctype="multipart/form-data" method="POST" action=".">
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="Modal-title" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Confirm</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete these items?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger" name="Delete" value="1" form="post-form">Delete</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-10 col-sm-12">
{% csrf_token %}
{% for field in post_form %}
{% ifnotequal field.label '' %}
<div class="input">
{{ field.label_tag }}
{{ field }}
</div>
<br>
{% endifnotequal %}
{% endfor %}
</div>
<div class="col-lg-2 col-sm-12 button-col">
<label for="file-upload-button-image" class="custom-file-upload">
<div class="upload-button-wrapper">
{{ image_form.images }}
<p id="image-num"></p>
<img src="{% static 'layout/img/image.svg' %}" alt="svg" id="img-svg">
<img src="{% static 'layout/img/plus-circle.svg' %}" alt="svg+" id="plus-svg">
</div></label>
<label for="file-upload-button-video" class="custom-file-upload">
<div class="upload-button-wrapper">
{{ video_form.videos }}
<p id="video-num"></p>
<img src="{% static 'layout/img/film.svg' %}" alt="svg" id="img-svg">
<img src="{% static 'layout/img/plus-circle.svg' %}" alt="svg+" id="plus-svg">
</div></label>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-md-6 col-sm-12 edit-col">
<div class="images_existing">
{% for image in images %}
<div class="stacker">
<div class="image-selector-wrapper">
<input type="checkbox" id="" name="img-index[]" class="invisible img-checkboxes" value="{{ image.pk }}">
<img class="thumbnail" src="{{ image.image.url }}" alt="{{ image.filename }}">
<h6>{{ image.filename }}</h6>
{% if forloop.first %}
<div class="num-indicator" id="image-number"></div>
{% endif %}
</div>
</div>
{% endfor %}
<div class="button-box">
<button type="submit" name="download" value="1" class="btn-primary">Download</button>
<button type="button" class="btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>
</div>
</div><div class="edit" id="edit-images">Edit</div>
</div>
<div class="col-lg-4 col-md-6 col-sm-12 edit-col">
<div class="videos_existing">
{% for video in videos %}
<div class="stacker">
<div class="video-selector-wrapper">
<input type="checkbox" id="" name="vid-index[]" value="{{ video.pk }}" class="invisible video-cb">
<img class="thumbnail-video" src="{% static 'layout/img/film.svg' %}" alt="{{ video.filename }}">
<h6>{{ video.filename }}</h6>
{% if forloop.first %}
<div class="num-indicator" id="video-number"></div>
{% endif %}
</div></div>
{% endfor %}
</div><div class="edit" id="edit-video">Edit</div>
</div></div>
<div class="row">
<div class="col">
{{ post_form.body }}
<button type="submit" class="custom-submit-button"><img src="{% static 'layout/img/upload.svg' %}" alt="submit"> <span>Submit</span></button>
</div>
</div>
{% if post_form.errors %}
{% for field in post_form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in post_form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
</form>
<script>var editor = new MediumEditor('.editable');</script>
<script src="{% static 'Logging/js/new_post.js' %}"></script>
{% endblock %}
I can not for the life of my figure this out. Any help would be appreciated!
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'
I want to assign a task to one of the users who commented on the post. But when I try to go on post_detail.html an error occurs, and i.e.
OperationalError at /home/
no such column: home_post.assign_to_id
PS: I have done python manage.py makemigrations and python manage.py migrate
So, here is the code snippet. I can give more information if needed. Thanks in advance!
views.py
def SaveAssigned(request):
if request.method == "POST":
if request.POST.get('assigned'):
savevalue = Post()
savevalue.assign_to = request.POST.get('assigned')
savevalue.save()
return render(request, 'post_detail.html')
else:
return render(request, 'post_detail.html')
class PostDetailView(DetailView):
model = Post
# template_name = 'home/post_detail.html'
def get_context_data(self, *args, **kwargs):
post_available = get_object_or_404(Post, id=self.kwargs['pk'])
cat_menu = Category.objects.all()
context = super(PostDetailView, self).get_context_data()
context["cat_menu"] = cat_menu
return context
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('post/<int:pk>/comment/', AddCommentView.as_view(), name='add-comment'),
path('add_category/', AddCategoryView.as_view(), name='add-category'),
path('category/<str:cats>/', CategoryView, name='category'),
path('category-list/', CategoryListView, name='category-list'),
]
models.py
class Post(models.Model):
title = models.CharField(max_length = 100)
snippet = models.CharField(max_length= 200)
content = RichTextField(blank=True, null=True)
date_posted = models.DateTimeField(default = timezone.now)
author = models.ForeignKey(User, on_delete= models.CASCADE)
category = models.CharField(max_length=255, default='Coding')
assign_to = models.ForeignKey(User,related_name='assign_to', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('home')
post_detail.html
{% extends 'users/base.html' %}
{% block body %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="#">{{ object.author }}</a>
<small class="text-muted">{{ object.category }}</small>
<small class="text-muted" style="float: right;">{{ object.date_posted|date:"F d, Y" }}</small>
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content|safe }}</p>
</div>
</article>
{% if object.author == user %}
<div>
<a class="btn btn-outline-secondary bt-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-outline-danger bt-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
<a class="btn btn-outline-primary bt-sm mt-1 mb-1" style="float: right;" href="">Done</a>
</div>
<form method="POST">
{% csrf_token %}
<select name="assigned">
<option selected disabled="true"> Select User</option>
{% if not post.comments.all %}
<option>NA</option>
{% else %}
{% for comment in post.comments.all %}
<option>{{ comment.author }}</option>
{% endfor %}
{% endif %}
</select>
<input type="submit" value="Assign" name="">
</form>
{% endif %}
<br>
<hr>
<h2>Comment Section</h2>
<br>
{% if not post.comments.all %}
No Comments yet
<br>
Be the first Ont to Comment!
{% else %}
Add a comment
<br>
{% for comment in post.comments.all %}
<strong>
{{ comment.author }} - {{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
<br><br>
{% endfor %}
<hr>
{% endif %}
<br><br>
{% endblock %}
This error occurs when your model does not contain the specific column and you are trying to add the value in that model with a specific column name.
You can solve this by following steps -
Step - 1. python manage.py makemigration
Step - 2. python manage.py migrate
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()