I'm new to Django and I'm utilizing class-based views for the first time. I want to use the generic ListView to show a list of "tables" owned by a user. And so far I've gotten it to display ALL the tables in the database. But I only want it to show tables for the logged in user.
this is what my view looks like:
from django.shortcuts import render
from django.http import HttpResponse
from django.views import generic
from vtables.models import Vtable
class TableListView(generic.ListView):
model = Vtable
context_object_name = 'table_list'
def get_context_data(self, **kwargs):
context = super(TableListView, self).get_context_data(**kwargs)
return context
And this is what my model looks like:
from django.db import models
from django.contrib.auth.models import User
class Vtable(models.Model):
user = models.ForeignKey(User)
table_name = models.CharField(max_length=200)
added_date = models.DateTimeField('date added')
class Vdata(models.Model):
table_id = models.ForeignKey(Vtable)
table_pk = models.IntegerField()
column_1 = models.CharField(max_length=200)
column_2 = models.CharField(max_length=200)
added_date = models.DateTimeField('date added')
I'll admit, I'm not sure what this line is doing:
context = super(TableListView, self).get_context_data(**kwargs)
But I suspect this is what I need to change? Or do I have to go into my template and do an if statement there? Maybe something like: {% if request.user == vtable.user %}?
EDIT: here is my template:
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
{% if request.user.is_authenticated %}
<img src="{{ request.user.profile.profile_image_url }}"/>
Logout
{% if request.user.first_name or request.user.last_name %}
{{ request.user.first_name }} {{ request.user.last_name }}
{% else %}
{{ request.user.username }}
{% endif %}
{% if request.user.profile.account_verified %}
(verified)
{% else %}
(unverified)
{% endif %}
<h1>Tables</h1>
<ul>
{% for vtable in table_list %}
<li>{{ vtable.user }}, {{ vtable.table_name }}</li>
{% endfor %}
</ul>
{% else %}
Login
{% endif %}
{% endblock %}
perhaps, overriding get_queryset():
def get_queryset(self):
return self.model.objects.filter(user=self.request.user)
Related
I am building a simple forum application and I keep getting the error OperationalError at /forums/
no such table: forums_simple_post when I go on my forum page. Does anyone know how to fix this I would much appreciate the help?
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from django.views import generic
from . import forms
from forums_simple.models import Post
# Create your views here.
class ForumForm(generic.CreateView):
template_name = 'forums_simple/forum.html'
form_class = forms.ForumForm
success_url = '/'
def form_vaild(self, form):
self.object = form.save(commit=False)
self.object.save()
return super().form_vaild(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['object_list'] = Post.objects.all()
return context
urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'forums'
urlpatterns = [
path('', views.ForumForm.as_view(), name='forum')
]
models.py
from django.db import models
# Create your models here.
class Post(models.Model):
message = models.TextField(blank=True, null=False)
created_at = models.DateTimeField(auto_now=True)
forms.py
from django import forms
from . import models
class ForumForm(forms.ModelForm):
class Meta:
model = models.Post
fields = ('message',)
forum.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
{% for message in object_list %}
{{ post.message }}
{% endfor %}
</div>
<div class="container">
<form class="forum_class" action="index.html" method="post">
{% csrf_token %}
{% crispy form %}
<button type="submit" name="big-button"></button>
</form>
</div>
{% endblock %}
Have you run migration commands?
python manage.py makemigrations
python manage.py migrate
Also, I think that fixing this loop might help at some point:
# Bad
{% for message in object_list %}
{{ post.message }}
{% endfor %}
# Good
{% for post in object_list %}
{{ post.message }}
{% endfor %}
Data from database to html is not rendering. The static data is rendering but unfortunately the database data is not rendering no error occurs, and page is also rendering but data is not rendering from database to the page.
Html doc
{% extends "base.html" %}
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<h1>All Tractors</h1>
<h1>{{posts.implementation}} hi</h1>
<br>
<ul>
{% for posts in post %}
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
Vews.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
return render(request,"tractor/index.html")
def posts(request):
qs = Post.objects.all()
context = {"posts":qs}
return render(request,"tractor/all-post.html",context)
This is the Models.py file:
from django.db import models
from django.core.validators import MinLengthValidator
from django.db.models.signals import pre_save
# Create your models here.
from .utils import unique_slug_generator
class Farmer(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
phone =models.CharField(max_length=10)
address = models.TextField(max_length=200)
email_address = models.EmailField()
def full_name(self):
return f"{self.first_name} {self.last_name}"
def __str__(self):
return self.full_name()
class Post(models.Model):
tractor_price = models.IntegerField(max_length=150)
implementation = models.CharField(max_length=50)
purchase_date = models.DateField(auto_now=False)
slug = models.SlugField(unique=True, db_index=True, null=True,blank=True)
tractor_company = models.CharField(max_length=50)
tractor_model = models.CharField(max_length=50)
description = models.TextField(validators=[MinLengthValidator(10)])
date = models.DateField(auto_now=False)
farmer = models.ForeignKey(
Farmer, on_delete=models.SET_NULL, null=True, related_name="posts")
def __str__(self):
return self.implementation
Try this:
{% load static %}
{% block title %}
All Tractors
{% endblock %}
{% block content%}
<section id="all_events">
<h1>All Tractors</h1>
<ul>
{% for post in posts %}
<h1>{{post.implementation}} hi</h1>
<br>
{% include "tractor/includes/singlePost.html" %}
{% endfor %}
</ul>
</section>
{% endblock %}
It should be {% for post in posts %}
Added the ability to add comments, made it so that only authorized users can add comments, but for some reason this does not work, please fix it.
I also added tag strong, but for some reason it does not work either
post_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<link href="{% static 'css/post_detail.css' %}" rel="stylesheet">
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body|urlize }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
{% if post.header_image %}
<p><img src="{{post.header_image.url}}"></p>
{% else %}
<p></p>
{% endif %}
{% for comm in post.commentpost_set.all%}
{{ comm.user }} <br>
{{ comm.text }} <br><br>
{% endfor %}
<br>
<hr>
<h2>Comments...</h2>
{% if not post.comments.all %}
No Comments Yet...<a href="{% url 'post_comment' post.pk %}">
Add Comment</a>
{% else %}
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
Add Comment<br><br>
{% else %}
Add Comment<br><br disabled>
{% endif %}
</form>
{% for comment in post.comments.all %}
<strong>
{{ comment.name }} -
{{ comment.date_added }}
</strong>
<br>
{{ comment.body }}
<br><br>
{% endfor %}
{% endif %}
{% endblock content %}
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy, reverse
from .models import Post, Comment
from .forms import CommentForm
from django.http import HttpResponseRedirect
class BlogListView(ListView):
model = Post
template_name = 'home.html'
context_object_name = 'posts'
paginate_by = 2
queryset = Post.objects.all()
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'post_comment.html'
def form_valid(self, form):
form.instance.post_id = self.kwargs['pk']
return super().form_valid(form)
success_url = reverse_lazy('home')
#fields = '__all__'
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
if self.image:
return getattr(self.photo, 'url', None)
return None
Write what files still need to be shown, I will show
Thanks everyone!
<form method="post">
{% csrf_token %}
{{ comment_form.as_p }}
{% if request.user.is_authenticated %}
Add Comment<br><br>
{% else %}
Add Comment<br><br>
{% endif %}
</form>
The 'Thumbnail' attribute has no file associated with it.
I have tried Django {% if %} {% else %} {% endif %} in my HTML list and it works on the page, but when I do the same for a detailview HTML it doesn't work and returns "The 'Thumbnail' attribute has no file associated with it."
** Models.py **
class Article(models.Model):
Title = models.CharField(max_length=150)
Thumbnail = models.ImageField(blank=True, null=True)
Author = models.ForeignKey(Author, on_delete=models.CASCADE)
Content = QuillField()
Date = models.DateField(auto_now_add=True)
slug = AutoSlugField(populate_from='Title')
** Views.py**
class ArticlesDetailView(DetailView):
model = Article
template_name = 'articles_app/articles_detail.html'
def get_context_data(self, **kwargs):
latest = Article.objects.order_by('-id')[0:3]
context = super().get_context_data(**kwargs)
context['latest'] = latest
return context
** HTML - List (articles_list.html) ** It works perfectly fine here!!!
<img src=" {% if articles.Thumbnail %}
{{ articles.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
** HTML - Detail (articles_detail.html) ** It doesn't work here.
{% for obj in latest %}
<img src="{% if obj.Thumbnail %}
{{ obj.Thumbnail.url }}
{% else %}
{% static 'img/add-ons/article_thumbnail_default.jpg' %}
{% endif %} " alt="..." class="card-img-top">
{% endfor %}
What am I doing wrong? Please help!
try object.Thumbnail instead of obj.Thumbnail, I think that will solve your problem.
I have a models.py:
class Part(models.Model):
Party_number = models.CharField(max_length=10)
Film = models.CharField(max_length=5)
viesws.py:
from django.shortcuts import render
from django.views.generic import ListView
from description.models import Part
class PartyNumView(ListView):
template_name = 'part_list.html'
model = Part
def partList(self, request):
my_var = Part.objects.all()
return render(request, 'part_list.html', {"my_var": my_var})
And HTML template part_list.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% load static %}
{% block activeButton %}
<li class="active">Описание партий</li>
<li>Ic и QE</li>
{% endblock %}
{% block tableName %}
Список партий
{% endblock %}
{% block content %}
{% for object in my_var %}
{{object.Party_number}}
{% endfor %}
{% endblock content%}
My question is why part of code which consist cycle "for" does not working? i.e. objects of Party_number does not displayed on html page
UPDATE
I change object.Party_number to {{object.Party_number}}, but whatever it does not working
You have defined a custom method, partList, but it is not being called from anywhere. The method is pointless and you should delete it.
If you want to add data to the template context in a class-based view, you need to define get_context_data. However there is no reason to do that here as it would just do what ListView does for you anyway. You should use the variable that the view automatically populates, which is object_list.
{% for object in object_list %}
{{ object.Party_number }}
{% endfor %}