Display data on a dynamic page - python

Faced with such a problem, the exercise_new page does not display any form and does not display information from the DB.
enter image description here
#------------views.py-----------#
def comment(request, pk):
"""Вывод полной статьи
"""
new = get_object_or_404(Exercise, pk=pk)
comment = Comments.objects.filter(new=pk, moderation=True)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.new = new
form.save()
return redirect(exercise, pk)
else:
form = CommentForm()
return render(request, "ProManager/exercise_new.html",
{"new": new,
"comments": comment,
"form": form})
#---------models.py------------#
class Comments(models.Model):
"""Ксласс комментариев к новостям
"""
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
verbose_name="Пользователь",
on_delete=models.CASCADE)
new = models.ForeignKey(
Exercise,
verbose_name="Новость",
on_delete=models.CASCADE)
text = models.TextField("Комментарий")
created = models.DateTimeField("Дата добавления", auto_now_add=True, null=True)
moderation = models.BooleanField("Модерация", default=False)
class Meta:
verbose_name = "Комментарий"
verbose_name_plural = "Комментарии"
def __str__(self):
return "{}".format(self.user)
#-----------------forms.py-------------#
class CommentForm(ModelForm):
"""Форма комментариев к статьям
"""
class Meta:
model = Comments
fields = ('text', )
#----------------exercise_new.html----------------#
<h4>Комментарии</h4>
{% for comment in comments %}
Пользователь - {{ comment.user }}<br>
{{ comment.text }} <br>
Добавлен - {{ comment.created }}<br><br>
{% endfor %}
{% if user.is_active %}
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Отправить</button>
</form>
{% else %}
<h4>Что бы оставить комментарий авторизуйтесь</h4>
{% endif %}
---------------------urls.py------------------
urlpatterns = [
path('exercise/<int:pk>/', ExerciseDetailView.as_view(), name='exercise-new'),
path('project/<int:pk>/', ProjectDetailView.as_view(), name='project-new'),
path('register',views.register_request, name="register"),
path('login', views.login_request, name="login"),
path('logout', views.logout_request, name= "logout"),
path('project', views.project, name="project"),
path('', views.project, name="project"),
path('exercise', views.exercise, name="exercise"),
path('contact', views.contact, name="contact"),
path('log', views.log, name="log"),
path('create_project',views.create_project, name="create_project"),
path('create_exercise',views.create_exercise, name="create_exercise"),
path('project/<int:pk>/update', views.ProjectUpdateView.as_view(), name='project_update'),
path('project/<int:pk>/delete', views.ProjectDeleteView.as_view(), name='project_delete'),
path('exercise/<int:pk>/update', views.ExerciseUpdateView.as_view(), name='exercise_update'),
path('exercise/<int:pk>/delete', views.ExerciseDeleteView.as_view(), name='exercise_delete'),
]

You need to have:
{% if request.user.is_active %}
Instead of
{% if user.is_active %}
In your template.

Related

My comments are not being displayed in a django blog

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}

nothing is saved after updating form

I have a Candidat models and Experience_Pro models as shown below with fk relation between them .
i can register or login a candidat(user) and a profil page with firstname and lastname of that candidat shown, and a form for Experience_Pro for the user to add if he does have one .
but when i enter all the info in the Experience_Pro form and click update nothing is added to candidat
I don't know what i am missing but the form is showing with no errors and even after i update the profile no errors but nothing is saved to candidat
models.py
class Candidat(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
experience_Pro = models.ForeignKey('Experience_Pro' ,on_delete=models.CASCADE,blank=True,
null=True,default='')
class Experience_Pro(models.Model):
annee_debut = models.IntegerField()
annee_fin = models.IntegerField()
description_exp_pro = models.TextField(null=True,blank=True)
forms.py
class UpdateCandidat(forms.ModelForm):
class Meta:
model=Candidat
fields=['experience_Pro']
class CreateExperience_Pro(forms.ModelForm):
class Meta:
model=Experience_Pro
fields='__all__'
views.py
#login_required
def profil(request):
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
if exp_form.is_valid():
exp = exp_form.save()
candidat = c_form.save(commit=False)
candidat.save(experience_Pro=exp)
return redirect('profil')
context={
'exp_form':exp_form
}
return render(request ,'candidats/profil.html',context)
profil.html
<h1>Profil Candidat</h1>
<p>Prenom: {{ user.first_name }}</p>
<p>Nom: {{ user.last_name }}</p>
<p>Email: {{ user.email }}</p>
<form method="POST" action="">
{% csrf_token %}
{% comment %} {{ c_form }} {% endcomment %}
{{ exp_form }}
<input type="submit" value="Update">
</form>
You need to do some update:
#login_required
def profil(request):
if request.method == 'POST':
exp_form = CreateExperience_Pro(request.POST)
c_form = UpdateCandidat(request.POST)
if exp_form.is_valid() and c_form.is_valid():
exp = exp_form.save()
candidat = c_form.save()
return redirect('profil')
else:
context = {
'exp_form': exp_form,
'c_form': c_form,
}
return render(request, 'candidats/profil.html', context)
else:
exp_form = CreateExperience_Pro()
c_form = UpdateCandidat()
context = {'exp_form': exp_form, 'c_form': c_form}
return render(request, 'candidats/profil.html', context)

why isn't my image being uploaded with the django form I created?

I am using Python 2.7, Django 1.9.
I'm trying to get an image from the user with this model/form pair:
models.py
from PIL import Image
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True, null=True)
location = models.CharField(max_length=200, null=True)
longitude = models.FloatField(null=True)
latitude = models.FloatField(null=True)
credit = models.FloatField(default=0, null=True)
picture = models.ImageField(upload_to='media/images/profile_pictures', blank=True, null=True)
def __unicode__(self):
return self.user.username
forms.py
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = [
"website",
"location",
"picture",
]
widgets = {
'location': forms.TextInput(
attrs={'id': 'location', 'class': 'geo', 'required': True, 'placeholder': 'location'}
),
}
This is saved using the following view:
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(request.POST)
profile_form = UserProfileForm(request.POST, request.FILES)
if user_form.is_valid() and profile_form.is_valid():
print(request.POST['location'])
print(str(request.POST['location']))
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
profile.save()
else:
print user_form.errors, profile_form.errors
else:
profile_form = UserProfileForm()
user_form = UserForm()
return render(request, "register.html", {'user_form' : user_form, 'profile_form' : profil
But upon execution, no pictures are saved to the folders. Here is the root of the image_urls:
project/static/media/images/profile_pictures
Any ideas?
Edit: Here's the html:
{% load static from staticfiles %}
{% block head %}
{% endblock %}
{% block content %}
{% if registered %}
<h1>Thank you for registering.</h2><br>
Start playing!
{% else %}
<form id="user_form" method="post" action="/register/" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="submit" value="register" />
</form>
{% endif %}
{% endblock %}
I upgraded to the latest version of Pillow and it works now.

uploading files from form

I have a ModelForm that I'm using to upload files with and it doesn't want to work. I had it working yesterday but I'm not sure what was done to make it stop all of a sudden.
Here's my ModelForm:
class UserForm(forms.ModelForm):
description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'cols': 80, 'rows': 5}))
class Meta:
model = UserProfile
exclude = {'user', 'description'}
Here's the Model:
def get_image_path(instance, filename):
return os.path.join('images', str(instance.id), filename)
def get_video_path(instance, filename):
return os.path.join('videos', str(instance.id), filename)
def get_randfile_path(instance, filename):
return os.path.join('randfile', str(instance.id), filename)
class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.CharField(max_length=500, blank=True, null=True)
photo = models.FileField(upload_to=get_image_path, blank=True, null=True)
video = models.FileField(upload_to=get_video_path, blank=True, null=True)
rand_file = models.FileField(upload_to=get_randfile_path, blank=True, null=True)
def photo_name(self):
return os.path.basename(self.photo.name)
def video_name(self):
return os.path.basename(self.video.name)
Here's the View:
def detail(request, user_id):
user = get_object_or_404(User, pk=user_id)
userprofile = get_object_or_404(UserProfile, user=user)
year = datetime.now().year
userform = UserForm()
delvid = Del_Video()
if request.method == 'POST':
userform = UserForm(request.POST, request.FILES, instance=user)
delvid = Del_Video(request.POST)
if userform.is_valid():
userprofile.description = request.POST.get('description', userprofile.description)
userprofile.photo = request.FILES.get('photo', userprofile.photo)
userprofile.video = request.FILES.get('video', userprofile.video)
userprofile.rand_file = request.FILES.get('rand_file', userprofile.rand_file)
userprofile.save()
else:
messages.add_message(request, messages.INFO, 'Invalid Form')
userform = UserForm()
if delvid.is_valid():
if request.POST['Delete']:
userprofile.video.delete()
else:
delvid = Del_Video()
context = {'user': user, 'year': year, 'userform': userform, 'userprofile': userprofile, 'delvid': delvid}
return render(request, 'users/detail.html', context)
And here is the form in the template:
<div class="row">
<div class="col-md-4">
<h4>Update User:</h4>
{% if userform.errors %}
<h6>{{ userform.errors }}</h6>
{% endif %}
{% if messages %}
{% for message in messages %}
<h5>{{ message }}</h5>
{% endfor %}
{% endif %}
<form action="{% url 'users:detail' user.id %}" method="post" enctype="multipart/form-data" data-ajax="false">
{% csrf_token %}
{{ userform.as_p }}
<input type="submit" value="Update">
</form>
</div>
</div>

Form posting Django

I can't get my django app to post to the db. I'm trying to pass my foreign key so I can post it correctly.
Sorry if it's something basic I'm missing I'm just starting. I think it never gets to form = ResultForm(request.POST). And just gives me the form = ResultForm.
Here is my code:
Model:
class Result(models.Model):
category = models.ForeignKey(Category)
category_result = models.CharField(max_length=200)
rating = models.DecimalField('', '', 8, 3)
votes = models.IntegerField(default=0)
created_by = models.IntegerField(default=0, null=True, blank=True)
created_on = models.DateTimeField('created on')
def __unicode__(self):
return self.category_result
Form:
class ResultForm(forms.ModelForm):
category_result = forms.CharField(max_length=200,help_text="Your best line")
rating = forms.DecimalField(widget=forms.HiddenInput(), initial=0)
votes = forms.IntegerField(widget=forms.HiddenInput(), initial=0)
created_by = forms.IntegerField(widget=forms.HiddenInput(), initial=1)
category = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = Result
fields = ('category_result', 'rating', 'votes')
view:
def help_out(request, category_id):
if request.method == 'POST':
form = ResultForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.category = category_id
form.save()
return index(request)
else:
print form.errors
else:
form = ResultForm
context = {'form': form, 'category_id': category_id}
return render(request,'pocketwingman/help_out.html', context)
template:
<!DOCTYPE html>
<html>
<head>
<title>Pocketwingman</title>
</head>
<body>
<h1>Add a Result</h1>
<form id="result_form" method="post" action="/pocketwingman/help_out/{{category_id}}/">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text}}
{{ field }}
{% endfor %}
<input type="submit" name="submit" value="Create Line" />
</form>
</body>
</html>
url config:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<category_id>\d+)/$', views.help_me, name='help_me'),
url(r'^help_out/(?P<category_id>\d+)/$', views.help_out, name='help_out'),
)
You should initiate your form if it's not a POST:
else:
form = ResultForm()
append () to form class.

Categories