I get a ValueError at /new_animal/7/ here is the error message:invalid literal for int() with base 10: b'11 02:07:39.299546'
It sends me to my base.html file saying there's an error at "line 0".
My base.html file contains the bootstrap.
Here is my new_animal.html file:
{% extends "zoo_animal_feeders/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>{{ animal_type }}</h2>
<h2>Add new animal:</h2>
{% endblock header %}
{% block content %}
<form action="{% url 'zoo_animal_feeders:new_animal' animal_type.id %}" method='post' class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name='submit'>add animal</button>
{% endbuttons %}
</form>
{% endblock content %}
Let me know if I need to show you more of my project.
Update
Here is my views code:
#login_required
def new_animal(request, animal_type_id):
"""Add a new animal to an animal type"""
animal_type = AnimalType.objects.get(id=animal_type_id)
if request.method != 'POST':
#create a blank form
form = AnimalForm()
else:
#POST data submitted
form = AnimalForm(data=request.POST)
if form.is_valid():
new_animal = form.save(commit=False)
new_animal.animal_type = animal_type
new_animal.save()
return HttpResponseRedirect(reverse('zoo_animal_feeders:animal_type', args=[animal_type_id]))
context = {'animal_type':animal_type, 'form':form}
return render(request, 'zoo_animal_feeders/new_animal.html', context)
Here is my models code:
class AnimalType(models.Model):
"""Type of animal that can classify the animal"""
owner = models.ForeignKey(User, on_delete=models.CASCADE)
a_type = models.CharField(max_length=50, default='')
date_added = models.DateField(auto_now_add=True)
def __str__(self):
return self.a_type
The solution was that in my models field I had date_added = models.DateField(auto_now_add=True) and I changed it to date_added = models.DateTimeField(auto_now_add=True) and it then worked.
It was because somewhere on the page I had it formatted as a DateTimeField and not a DateField.
Related
I have to do wishlist, I have done wishlist page, model and html.bBut when I click on the button bellow my post, I'm redirected to wishlist page and post didnt saved in my wishlist.So thats my code:
models.py
class Wishlist(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
wished_item = models.ForeignKey(Posts, on_delete=models.CASCADE)
def __str__(self):
return self.wished_item.title
class Posts(models.Model):
TYPE = Choices(
('private', _('private')),
('business', _('business')),
)
STATUS = Choices(
('active', _('active')),
('deactivated', _('deactivated'))
)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='posts',
on_delete=models.CASCADE, verbose_name='owner')
phone_number = PhoneNumberField(verbose_name=_('Phone_number'), null=False, blank=False, unique=True)
title = models.CharField(verbose_name=_('Title'), max_length=100)
text = RichTextField(verbose_name=_('Text'))
image = models.ImageField(upload_to='images/%Y/%m/%d/', null=True, blank=True, validators=[file_size])
price = models.DecimalField(verbose_name=_('Price'), decimal_places=2, max_digits=9)
status = models.CharField(choices=STATUS, max_length=50)
created = models.DateTimeField(auto_now=True)
type = models.CharField(choices=TYPE, max_length=50)
def __str__(self):
return self.title
views.py
class WishListView(generic.View):
def get(self, *args, **kwargs):
wish_items = Wishlist.objects.filter(user=self.request.user)
context = {
'wish_items': wish_items
}
return render(self.request, 'wishlist/wishlist.html', context=context)
def addToWishList(request):
if request.method == 'POST':
post_var_id = request.POST.get('object-id')
post_var = Posts.objects.get(id=post_var_id)
print(post_var)
try:
wish_item = Wishlist.objects.get(user=request.user, post=post_var)
if wish_item:
wish_item.save()
except:
Wishlist.objects.create(user=request.user, post=post_var)
finally:
return HttpResponseRedirect(reverse('wishlist'))
wishlist.html
{% extends 'posts/base.html' %}
{% load thumbnail %}
{% block content %}
<div>
{% for item in wish_items %}
{% if item.wished_item.image1 %}
<img src="{{item.wished_item.image.url}}" alt="">
{% endif %}
</div>
<div>
<li>{{item.wished_item.title}}</li>
<li>{{item.wished_item.text}}</li>
<li>{{item.wished_item.price}}</li>
<li>{{item.wished_item.phone_number}}</li>
{% if item.wished_item.image %}
<img src="{% thumbnail item.wished_item.image 200x200 crop %}" alt="" />
<p></p>
{% endif %}
</div>
{% endfor %}
{% endblock %}
urls.py
urlpatterns = [
path("wishlist/", WishListView.as_view(), name='wishlist'),
path("add-to-wishlist", addToWishList, name='add-to-wishlist'),
]
and all posts template with add to wishlist button.
<ul>
{% for object in object_list %}
<li>Owner: {{ object.owner }}</li>
<li>Phone: {{ object.phone_number }}</li>
<li>Title: {{ object.title }}</li>
<li>Text: {{ object.text }}</li>
<li>Type: {{ object.type }}</li>
<li>Price: {{ object.price }}</li>
<li>Date: {{ object.created }}</li>
<p>
{% if object.image %}
<img src="{% thumbnail object.image 200x200 crop %}" alt="" />
{% endif %}
</p>
<form action="{% url 'add-to-wishlist' %}" method="POST">
{%csrf_token%}
<input type="hidden" name="object-id" value="{{object.id}}">
<input type="submit" value="Add to Wishlist">
</form>
<hr/>
Probably problem with posts Id, but I'm not sure in that.
You can use get_or_create instead of the if else statement for if exist or not. And use get_object_or_404 to make code more clear.
from django.shortcuts import get_object_or_404
def addToWishList(request):
if request.method == 'POST':
post_obj = get_object_or_404(Post, pk=request.POST.get('object-id'))
Wishlist.objects.get_or_create(user=request.user, post=post_obj)
return HttpResponseRedirect(reverse('wishlist'))
In your views.py try to replace these lines:
try:
wish_item = Wishlist.objects.get(user=request.user, post=post_var)
if wish_item:
wish_item.save()
except:
Wishlist.objects.create(user=request.user, post=post_var)
with
wish_item, was_created = Wishlist.objects.get_or_create(user=request.user, post=post_var)
# for debugging
if was_created:
print(f"{wish_item} was created")
else:
print(f"{wish_item} already exists")
what is the output?
The code looks OK for me. You might add a trailing / in your urls.py after the path("add-to-wishlist/" ... but I can't spot anything wrong in the first place.
I have made a comment system under my books where only the authenticated user can comment. When I use the form to add a comment, it doesn't work! why ?
here is my models
models.py
class Books(models.Model):
author = models.ManyToManyField(Authors)
title = models.CharField(max_length=250)
number_of_pages = models.PositiveIntegerField(validators=[MaxValueValidator(99999999999)])
date_added = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now=True)
publication_date = models.PositiveIntegerField(default=current_year(), validators=[MinValueValidator(300),
max_value_current_year])
cover = models.ImageField(upload_to='pics/covers/', default='pics/default-cover.jpg')
pdf_file = models.FileField(upload_to='pdfs/books/', default='pdfs/default-pdf.pdf')
category = models.ForeignKey(Categories, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Comments(models.Model):
book = models.ForeignKey(Books, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '{} - {}'.format(self.livre.title, self.user)
here is my forms
forms.py
class BookForm(ModelForm):
class Meta:
model = Books
fields = '__all__'
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = ['body']
here is my views
views.py
#login_required(login_url='login')
def book_detail_view(request, book_id):
books = get_object_or_404(Books, pk=book_id)
context = {'books': books,}
return render(request, 'book_detail.html', context)
#login_required(login_url='login')
def add_comment(request, comment_id):
form = CommentForm()
books = get_object_or_404(Books, pk=comment_id)
user = request.user
if request.method == "POST":
form = CommentForm(request.POST, instance=books)
if form.is_valid():
comment = form.save(commit=False)
comment.user = user
comment.books = books
comment.save()
return redirect('book_detail', books.id)
context = {'form': form}
return render(request, 'comment_form.html', context)
here is my book detail page
book_detail.html
{% extends 'base.html' %}
{% block title %} {{ books.title }} {% endblock %}
{% block content %}
<div class="row">
<div class="col-lg-4">
<p><img src="{{ books.cover.url }}"></p>
</div>
<div class="col-lg-8">
<h2>{{ books.title }}</h2>
<b>Author : </b>
{% for author in books.author.all %}
{{ author.name }}
{% if not forloop.last %},{% endif %}
{% endfor %}<br/>
<b>Catégory : </b>{{ books.category }}<br/>
<b>Pages : </b>{{ books.number_of_pages }}<br/>
<b>Publication : </b>{{ books.publication_date }}<br/>
<b>Date added : </b>{{ books.date_added }}<br/>
<b>Updated : </b>{{ books.updated }}<br/>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<p><button class="btn btn-outline-dark btn-sm"><i class="far fa-eye"></i> Read</button></p>
</div>
</div>
<hr/>
<div class="container-fluid">
<h2>Comments</h2>
</div>
<div class="container-fluid">
{% if not books.comments.all %}
<p>No comments yet ! <a class="text-primary" href="{% url 'add_comment' books.id %}">Add comment...</a></p>
{% else %}
<a class="text-primary" href="{% url 'add_comment' books.id %}">Add comment !</a><br/><br/>
{% for comment in books.comments.all%}
<b>{{ comment.user }}</b> - <span class="text-muted" style="font-size: 13px;">{{ comment.date }}</span>
<p>{{ comment.body }}</p>
{% endfor %}
{% endif %}
</div>
{% endblock %}
here is my form for comment model
comment_form.html
{% extends 'base.html' %}
{% block title %} Add a comment {% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add this comment</button>
</form>
{% endblock %}
here is my urls
urls.py
urlpatterns = [
# BOOKS
path('book/<int:book_id>/', views.book_detail_view, name='book_detail'),
# COMMENTS
path('book/<int:comment_id>/comment/', views.add_comment, name='add_comment'),
]
Your form is currently set to edit the book, not the comment, you should remove the instance=books:
if request.method == "POST":
# no instance=books ↓
form = CommentForm(request.POST)
If you use instance=books, the form will set attributes to the Books object, and then the comment = form.save(commit=False) will result in the fact that comment is a Books object that is already saved and thus updated in the database.
You also made a typo when setting the book of a Comments object: it is book, not books:
if form.is_valid():
comment = form.save(commit=False)
comment.user = user
comment.book = books # ← .book, not .books
comment.save()
Note: normally a Django model is given a singular name, so Book instead of Books.
how can I retrieve the lesson modules by its parent lesson strictly? e.g if I change to the next lesson where at the same contains a lessonmodule /lesson1/task1 this one shouldn't display since it doesn't belong to lesson2? how can I fix this by only retrieve slugs, content by the lesson attach to?
views
class LessonDetailView(LoginRequiredMixin, View):
login_url = "/account/login/"
def get(self, request, course_slug, lesson_slug, *args, **kwargs):
lesson = get_object_or_404(Lesson.objects.select_related('course'), slug=lesson_slug, course__slug=course_slug)
lessonmodule = get_object_or_404(LessonModule.objects.select_related('lesson'), slug='hello_world')
context = {
'object': lessonmodule,
'previous_lesson': lesson.get_previous_by_created_at,
'next_lesson': lesson.get_next_by_created_at,
}
return render(request, "courses/lesson_detail.html", context)
models
class Lesson(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(max_length=25,unique=True)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('lesson-detail',
kwargs={
'course_slug': self.course.slug,
'lesson_slug': self.slug
})
class LessonModule(models.Model):
slug = models.SlugField(unique=True, blank=True, null=True)
content = models.TextField()
lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
allowed_memberships = models.ManyToManyField(Membership)
created_at = models.DateTimeField(auto_now_add=True, blank=True)
updated_at = models.DateTimeField(auto_now=True, blank=True)
def __str__(self):
return self.slug
template
{% block content %}
<div class='container'>
<h1>Lesson Detail View</h1>
<div class='row'>
<div class='col-sm-6 col-md-6'>
{% if object is not None %}
<h3>{{ object.title }}</h3>
<p>{{ object.course.description }}</p>
{{object}}
{% if previous_lesson %}
Back
{% endif %}
{% if next_lesson %}
Next
{% endif %}
{% else %}
<h3>Upgrade membership</h3>
<p>To view this course you'll need to upgrade your membership</p>
<br>
<hr>
{% endif %}
</div>
</div>
</div>
{% endblock content %}
As I can see here, you can have multiple LessonModule for a single Lesson due to one-to-many relation between Lesson and LessonModule(ForeignKey relation basically). You can fetch all the LessonModules like this(using reverse query):
# view
def get(self, request, course_slug, lesson_slug, *args, **kwargs):
lesson = get_object_or_404(Lesson.objects.select_related('course').prefetch_related('lessonmodule_set'), slug=lesson_slug, course__slug=course_slug)
context = {
'object': lesson,
'previous_lesson': lesson.get_previous_by_created_at,
'next_lesson': lesson.get_next_by_created_at,
}
return render(request, "courses/lesson_detail.html", context)
# template
{% for lesson_module in object.lessonmodule_set.all %}
{{ lesson_module.slug }}
{% endfor %}
I am just sending the Lesson object to template, and using reverse query in template to get LessonModule objects.
First of all I want to apologize for my English. It's hard for me to write this question in English, but I didn't find any ideas for my problem on russian sites. So, I want to create a timetable on school-site. In my models.py :
class Classes(models.Model):
class Meta:
db_table = 'classes'
verbose_name_plural = "School_classes"
verbose_name = "School_class"
name = models.CharField(max_length=50, unique=True, verbose_name = 'School_classes')
def __str__(self):
return self.name
class Lessons(models.Model):
class Meta():
db_table = "lessons"
verbose_name_plural = "Lessons"
verbose_name = "Lessons"
lessons_class = models.ForeignKey(Classes)
lessons_creationdate = models.DateField()
lessons_weekcontent = RichTextField()
Then, in forms.py I have:
class LessonsForm(forms.ModelForm):
classname = forms.ModelChoiceField(queryset = Classes.objects.all(),empty_label="Choose a class",widget=forms.Select(attrs={'class':'dropdown'}),label="School_classes")
class Meta:
model = Lessons
fields = ('lessons_class',)
And in my views.py:
def ShowTimetable(request):
LForm = LessonsForm(request.POST or None)
args = {}
args['classes'] = Classes.objects.all()
args['lessons'] = Lessons.objects.all()
args['showlessons'] = LForm
args.update(csrf(request))
if request.method == 'POST' and LForm.is_valid():
CurrentClass = LForm.cleaned_data('currentclass', None)
args['class_name'] = CurrentClass
args['lessons'] = Lessons.objects.filter(lessons_class = CurrentClass)
if args['lessons']:
return render_to_response('Weekcontentpage.html',args )
else:
return render_to_response('Weekcontentpage_null.html',args )
else:
return render_to_response('myview.html',args )
Finally, in myviews.html
{% extends 'base.html' %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ showlessons }}
<input type="submit" value="Show timetable">
</form>
{% endblock %}
In Weekcontentpage.html:
{% extends "base.html" %}
{% block content %}
<h4>On request "{{ class_name }}:</h4>
{% for lesson in lessons %}
<h6>Date:{{ lesson.lessons_creationdate }}</h6>
<h4>{{ lesson.lessons_weekcontent }}</h4>
{% endfor %}
{% endblock content %}
and in Weekcontentpage_null.html:
{% extends "base.html" %}
{% block content %}
<h4> On "{{class_name}}" is nothing found :( (</h4>
{% endblock content %}
Now, after I make a choice in the drop down menu and push 'Show timetable' button, I've just see "None" and nothing is found :(. I understand that the problem in views.py, so i cant get a value from drop down, but I don't know how can i fix it. So i would appreciate any help. Thanks and sorry for my English:)
The same way as with any other field.
The problem is that you have defined a form class, but you are not using it in any way at all. Instead of ignoring the form and getting data from request.POST, you should be instantiating the form with the POST data, calling is_valid() on it, then getting the result from form.cleaned_data.
I have some problem
This is my code:
views.py:
def cv_detail(request, pk):
cv = get_object_or_404(Cv, pk=pk)
return render(request, 'cv_detail.html', {'cv': cv})
cv_detail.html:
{% block profile %}
<a class="btn-lg btn-default" href="{% url "edit_cv" pk=cv.pk %}"><span class="glyphicon glyphicon-pencil"> Edit</span></a>
<p></p><br>
<div class="jumbotron">
{% if not cv.specialization.is_empty %}
<p>Specialization: {{cv.specialization}}</p>
{% endif %}
</div>
{% endblock %}
forms.py:
class CvForm(forms.ModelForm):
class Meta:
model = Cv
fields = ('name', 'specialization',)
models.py:
class Cv(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=25, null = True)
specialization = models.CharField(max_length=30, blank=True, null=True)
def zapisz(self):
self.save()
def __str__(self):
return self.surname
And the question is: how can i check is any field of cv model is empty?
I have nothing in "Specialization" - is not complemented by me, so shouldn't be displayed, but it is, like: "Specialization: ".
Any ideas how to check? Becouse that what i have is not working :/
Thanks!
You can check for an empty specialization field in your template with:
{% if cv.specialization and cv.specialization.strip %}
<p>Specialization: {{cv.specialization}}</p>
{% endif %}
The .strip check will ensure that you do not attempt to display a string that only contains whitespaces.