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 %}
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 %}
I am trying to include a profile feature in a simple blog site. I have created a profile model using the one to one link for the user field, also created a function view for the profile detail with corresponding template name but i keep getting a 404 error.
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
username = models.CharField(max_length=15, default='Anonymous')
dp = models.ImageField(null=True)
country = models.CharField(max_length=20, null=True)
age = models.IntegerField(null=True)
joined = models.DateTimeField( auto_now_add=True)
class Meta:
ordering = ['joined']
def __str__(self):
return self.username
def get_absolute_url(self):
return reverse('profile_detail', args=[str(self.id)])
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()```
views.py
def profile_detail(request, pk):
user = get_object_or_404(User, pk=pk)
context = {'user': user}
return render(request, 'milk/profile_detail.html', context)
profile_detail.html
{% extends 'milk/base.html' %}
{% block title %}
{% endblock %}
{% block content %}
<h2>{{ user.get_full_name }}</h2>
<ul>
<li>Username: {{ user.username }}</li>
<li>Location: {{ user.profile.country }}</li>
<li>Age: {{ user.profile.age }}</li>
</ul>
{% endblock %}
template referencing
<em>{{user.get_username }}</em>
urls.py
path('profile/<int:pk>/', views.profile_detail, name='profile_detail'),
you can display current user info like this without passing through context
{% extends 'milk/base.html' %}
{% block title %}
{% endblock %}
{% block content %}
<h2>{{ request.user.profile.get_full_name }}</h2>
<ul>
<li>Username: {{ request.user }}</li>
<li>Location: {{ request.user.profile.profile.country }}</li>
<li>Age: {{ request.user.profile.profile.age }}</li>
</ul>
{% endblock %}
or
instead of 'get_object_or_404' try
user = User.objects.get(id=pk)
I am a beginner learning Django through building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews.
I have already created models, views and the template files. Right now, I am facing a problem. While attempting to use slug, I am getting NoReverseMatch Error. It looks like this:
NoReverseMatch at /index
Reverse for 'modellist' with arguments '('',)' not found. 1 pattern(s) tried: ['phonemodel/(?P<slug>[-a-zA-Z0-9_]+)$']
However, I didn't face any problem with while using primary key in urls.py. The problem is occurring when I attempt to use slug in the URLs.
Here are my codes of models.py located inside PhoneReview folder:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.CharField(max_length=100, null=True, blank=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.brand_name
def save(self, *args, **kwargs):
self.slug = slugify(self.brand_name)
super().save(*args, **kwargs)
class PhoneModel(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.model_name
def save(self, *args, **kwargs):
self.slug = slugify(self.model_name)
super().save(*args, **kwargs)
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
link = models.TextField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
Here are my codes of urls.py located inside PhoneReview folder:
from . import views
from django.urls import path
app_name = 'PhoneReview'
urlpatterns = [
path('index', views.BrandListView.as_view(), name='brandlist'),
path('phonemodel/<slug:slug>', views.ModelView.as_view(), name='modellist'),
path('details/<slug:slug>', views.ReviewView.as_view(), name='details'),
]
Here are my codes of views.py located inside PhoneReview folder:
from django.shortcuts import render, get_object_or_404
from django.views import generic
from .models import Brand, PhoneModel, Review
class BrandListView(generic.ListView):
template_name = 'PhoneReview/index.html'
context_object_name = 'all_brands'
def get_queryset(self):
return Brand.objects.all()
class ModelView(generic.ListView):
template_name = 'PhoneReview/phonemodel.html'
context_object_name = 'all_model_name'
def get_queryset(self):
self.brand = get_object_or_404(Brand, slug=self.kwargs['slug'])
return PhoneModel.objects.filter(brand=self.brand)
class ReviewView(generic.DetailView):
model = Review
template_name = 'PhoneReview/details.html'
Here are my codes of apps.py located inside PhoneReview folder:
from django.apps import AppConfig
class PhonereviewConfig(AppConfig):
name = 'PhoneReview'
Here are my codes of index.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Brand List
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Brand List Page</h1>
<h2>Here is the list of the brands</h2>
<ul>
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of phonemodel.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
{% block title%}
Phone Model Page
{% endblock %}
{% block content %}
<!--Page content-->
<h1>This is Phone Model Page</h1>
<h2>Here is the phone model</h2>
<ul>
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
{% endfor %}
</ul>
<img src="{% static "images/brandlist.jpg" %}" alt="Super Mario Odyssey" /> <!-- New line -->
{% endblock %}
Here are my codes of details.html located inside templates folder:
{% extends 'PhoneReview/base.html' %}
{% load static %}
<html>
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">
<html lang="en">
{% block title%}Details{% endblock %}
{% block content %}
<h1>This is the Details Page</h1>
<h2>Review:</h2>
<p>{{ review.review_article }}</p>
<h2>News Link:</h2>
<p>{{ review.link }}</p>
{% endblock %}
</html>
Am I doing anything wrong in index.html and phonemodel.html?
In your index.html instead of phonemodel.slug it should be brand.slug
{% for brand in all_brands %}
<!-- <li>{{ brand.brand_name }}</li>-->
<li>{{ brand.brand_name }}</li>
{% endfor %}
Same with your phonemodel.html
{% for phonemodel in all_model_name %}
<li>{{ phonemodel.model_name }}</li>
% endfor %}
I have a model 'Post' and this has a function 'total_likes' that counts all the likes on a post. How can i access this function inside my template to show the number of likes? Thank you!
Model:
class Post(models.Model):
created_date = models.DateTimeField()
title = models.CharField(max_length=100)
profile_image = models.ImageField(upload_to='poze', blank=True, null=True)
text = models.CharField(max_length=1000, default='Nimic', blank=True)
user = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
likes=models.ManyToManyField(UserProfile,related_name='likes',blank=True )
def total_likes(self):
return self.likes.count()
View:
class ShowPosts(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'mainPage.html'
def get(self, request):
posts = Post.objects.all()
serializer = PostSerializer(posts, many=True)
return Response({'posts': serializer.data})
Template:
{% extends 'base2.html' %}
{% load static %}
{% load rest_framework %}
{% load crispy_forms_tags %}
<form action="{% url 'like_post' %}" method="post">
{% csrf_token %}
<button type="submit" name="post_id" value="{{ post.id}}">Like {{"How can I access the 'total_likes' function ?'}}</button>
</form>
{% endfor %}
{% endblock %}
Just reference the method like any other attribute. Since it didn't take any parameters, Django will call it automatically.
{{ post.total_likes }}
Just like you passed {{post.id}}, call the function before you render the template, and pass the arg to it
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)