I am trying to display the watchlisted items of the logged in user. I am able to display a list but the item details such as title, price etc. don't show up.
models.py:
class Watchlist(models.Model):
user = models.ForeignKey(User, on_delete = models.CASCADE, name = "user")
item = models.ForeignKey(AuctionItem, on_delete = models.CASCADE, name = "item")
def __str__(self):
return f"Username: {self.user} / {self.item} "
views.py:
#login_required
def watchlist(request,user):
user = request.user
item_list = Watchlist.objects.filter(user_id=user)
return render(request, "auctions/watchlist.html",{
"item_list" : item_list
})
watchlist.html:
{% extends "auctions/layout.html" %}
{% block body %}
{% for item in item_list %}
<div class = "frame">
{% if item.image %}
<img src="{{item.image}}" style= "width: 30vw;">
{% endif %}
<h4>{{item.title}}</h4>
<div id="text"><strong>Price:</strong> ${{item.price}}</div>
<div id="text"><strong>Description:</strong> {{item.description}}</div>
<div id="text"><strong>Category:</strong> {{item.category}}</div><br>
<div id="date">Created {{item.date}}</div>
</div>
{% endfor %}
{% endblock %}
urls.py:
urlpatterns = [
path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("create", views.create_listing, name="create"),
path("listing/<int:listing_id>", views.listing, name = "listing"),
path("<str:user>/watchlist", views.watchlist, name= "watchlist")
]
and here is what I'm getting as a result:
In view:
item_list = AuctionItem.objects.filter(watchlist__user=user)
The template stays untouched.
Or only in template in forloop it should be {{item.item.price}} because item alone is Watchlist object.
Related
I'm trying to create an auction system with django.
But when I create a new item for the auction, the image is not saved, but the rest of the item does. But the media folder isn't created.
SETTINGS.PY
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
URLS.PY
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("core.urls")),
path("users/", include("users.urls")),
path("users/", include("django.contrib.auth.urls")),
path("auction/", include("auction.urls")),
]
if settings.DEBUG:
"""
With that Django's development server is capable of serving media files.
"""
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MODELS.PY
class Auction(models.Model):
object = models.CharField(max_length=50)
description = models.CharField(max_length=256, default="")
image = models.ImageField(upload_to="media/", null=True, blank=True)
open_date = models.DateTimeField(auto_now_add=True)
close_date = models.DateTimeField()
total_bet = models.IntegerField(default=0)
open_price = models.FloatField(
default=0,
)
close_price = models.FloatField(default=0)
winner = models.CharField(max_length=256, default="")
active = models.BooleanField(default=True)
json_details_file = models.TextField(default="")
tx = models.CharField(max_length=256, default="")
def __str__(self):
return self.object
FORMS.PY
class ItemForm(forms.ModelForm):
class Meta:
model = Auction
fields = ["object", "description", "image", "close_date", "open_price"]
widgets = {
"close_date": DateTimeInput(attrs={"placeholder": "YYYY-MM-DD HH:MM"})
}
VIEW.PY
#login_required(login_url="login")
def new_item(request):
"""
A function that will create a new item for te auction
"""
if request.method == "POST":
form = ItemForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, "Item create")
return redirect("homepage")
else:
form = ItemForm()
return render(request, "auction/new_item.html", {"form": form})
new_item.html
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
{% if user.is_superuser %}
<div class="row justify-content-center mt-4">
<div class="col-6 text-center">
<h2>Creazione Item!</h2>
<form class="" method="POST" novalidate>
{% csrf_token %}
{{ form|crispy }}
<input type="submit" class="btn btn-info mt-4" value="Crea Item">
</form>
</div>
</div>
{% else %}
<p>You arent' allowed</p>
{% endif %}
{% endblock content %}
I'd looked at every line of code and tried numerous times to upload the image but still not working.
Try adding enctype="multipart/form-data" to your html form tag like so:
<form method="post" enctype="multipart/form-data">
In your tag use this enctype="multipart/form-data"
I am having this error below:
Reverse for 'post_detail' with no arguments not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/$'].
I am working on a blog app. When you click on view more article on your dashboard on index page, the post_detail.html should show the full article and allow users to post comments. I keep getting the error posted above once i click on view article.
Here is the post_detail.html code
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-8 card mb-4 mt-3 left top">
<div class="card-body">
<h1>{% block title %} {{ post.title }} {% endblock title %}</h1>
<p class=" text-muted">{{ post.author }} | {{ post.created_on }}</p>
<p class="card-text ">{{ post.content | safe }}</p>
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
<!-- comments -->
{% with comments.count as total_comments %}
<h2>{{ total_comments }} comments</h2>
<p>
{% endwith %} {% for comment in comments %}
</p>
<div class="comments" style="padding: 10px;">
<p class="font-weight-bold">
{{ comment.name }}
<span class=" text-muted font-weight-normal">
{{ comment.created_on }}
</span>
</p>
{{ comment.body | linebreaks }}
</div>
{% endfor %}
</div>
</div>
<div class="col-md-8 card mb-4 mt-3 ">
<div class="card-body">
{% if new_comment %}
<div class="alert alert-success" role="alert">
Your comment is awaiting moderation
</div>
{% else %}
<h3>Leave a comment</h3>
<form method="POST" action="{% url 'post_detail' %}" style="margin-top: 1.3em;">
{{ comment_form | crispy }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock content %}
My models
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank= True, null=True)
updated_on = models.DateTimeField(auto_now= True)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
status = models.IntegerField(choices=STATUS, default=0)
class Meta:
ordering = ['-published_date']
def publish(self):
self.published_date=timezone.now()
self.save()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.name)
View for the post_detail
def post_detail(request, slug):
template_name = 'post_detail.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)
new_comment = None
# Comment posted
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
context = {'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form}
return render(request, 'blog/post_detail.html', context)
url
urlpatterns = [
path('', views.index, name='index'),
#path('', views.PostList.as_view(), name='index'),
path('login', views.login, name= 'login'),
path('logout', views.logout, name= 'logout'),
path('register', views.register, name = 'register'),
path('dashboard', views.dashboard, name = 'dashboard'),
path('posts', views.posts, name = 'posts'),
path('articles', views.articles, name='articles'),
path('prayers', views.prayers,name='prayers' ),
path('prayer_request', views.prayers, name='prayer_request'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='registration/password_change_done.html'),
name='password_change_done'),
path('password_change/', auth_views.PasswordChangeView.as_view(template_name='registration/password_change.html'),
name='password_change'),
path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_done.html'),
name='password_reset_done'),
path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'),
path('password_reset/', auth_views.PasswordResetView.as_view(), name='password_reset'),
path('reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'),
name='password_reset_complete'),
]
Kindly help with this error.
Following your urls.py you should a pass a slug along your post_detail url.
So in your form, you can not call your url without a slug like this <form method="POST" action="{% url 'post_detail' %}">
Because you can not easily know the id of your new post, maybe should create a different url for creating a new post, like post_create
I want to search by two fields (q1 and q2):
home.html
<form action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search...">
<select name="q2" class="form-control" id="exampleFormControlSelect1">
<option>All locations</option>
<option>RU</option>
<option>Ukraine</option>
<option>USA</option>
</select>
<button> Search </button>
</form>
When I click "search" I go to http://127.0.0.1:8001/search/?q=mos&q2=RU (it's OK)
Then I click "next". I go to
http://127.0.0.1:8001/search/?city=2&q=mos&q2=%20RU (ERROR: "Page not found)
but I want
http://127.0.0.1:8001/search/?city=2&q=mos&q2=RU
How can I fix it? Why do I have "%20" ???
search results.html
<h1>Search Results</h1>
<ul>
{% for city in object_list %}
<li>
{{ city.name }}, {{ city.state }}
</li>
{% endfor %}
</ul>
<div class="pagination">
<span class="page-links">
{% if page_obj.has_previous %}
previous
{% endif %}
<span class="page-current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
next
{% endif %}
</span>
</div>
models.py
from django.db import models
class City(models.Model):
name = models.CharField(max_length=255)
state = models.CharField(max_length=255)
COUNTRY = (
('RU', 'Russia'),
('UKR', 'Ukraine'),
('US', 'USA'),
)
category = models.CharField(max_length=100, choices=COUNTRY, default='RU')
class Meta:
verbose_name_plural = "cities"
def __str__(self):
return self.name
urls.py
urlpatterns = [
path('search/', SearchResultsView.as_view(), name='search_results'),
path('', HomePageView.as_view(), name='home'),
path('city/<int:pk>/', views.city_detail, name='city_detail'),
]
views.py
class HomePageView(ListView):
model = City
template_name = 'cities/home.html'
paginate_by = 3
page_kwarg = 'city'
def city_detail(request, pk):
city = get_object_or_404(City, pk=pk)
return render(request, 'cities/city_detail.html', {'city': city})
class SearchResultsView(ListView):
model = City
template_name = 'cities/search_results.html'
paginate_by = 3
page_kwarg = 'city'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['query'] = self.request.GET.get('q')
# added param
context['query2'] = self.request.GET.get('q2')
#print("BBBBBBBBBBBBBBBBb {}".format(context['query2']))
return context
def get_queryset(self): # new
query = self.request.GET.get('q')
query2 = self.request.GET.get('q2')
#print("AAAAAAAAAAAAAAAAAAAAA", query2, type(query2))
object_list = City.objects.filter(
(Q(name__icontains=query) | Q(state__icontains=query)) & Q(category=query2)
)
return object_list
%20 is the url code for a space. You need to remove the extra spaces in :
previous
# ^
and
next
# ^
I am trying to make category name visible in every page. so for that I passed category model to every view. But here it is visible only in category_view.html page only.
I want to make it visible everywhere as I am listing out category name in navbar.
so far I did this
templates/navbar.html
<nav class="nav d-flex justify-content-between">
{%for name in category_name %}
{% for lst in post %}
<a class="p-2 text-muted" href="{% url 'posts:categoryview' slug=name.slug %}">{{name}}</a>
{% endfor %}
{% endfor %}
</nav>
views.py
from django.shortcuts import render, get_object_or_404,render_to_response
from .models import Post, Category
# Create your views here.
def posts_list(request):
query_list = Post.objects.all()
category_name = Category.objects.all()
context = {
"title" : "Latest Post",
"query_list": query_list,
"category_name": category_name
}
return render(request, "post_list.html", context)
def view_category(request, slug):
category = get_object_or_404(Category, slug=slug)
category_name = Category.objects.all()
return render_to_response('category_view.html', {
'category': category,
'post': Post.objects.filter(category=category).values(),
'category_name': category_name
})
urls.py
urlpatterns = [
path("", posts_list, name="list"),
path("<slug>", view_category, name="categoryview"),
]
This is my first time here.
I'm stuck with a little problem in Django. I'm writing a webpage for a kennel and I have a model for dogs. These dogs appear on the front page after they have been created in admin page. I need it so that after clicking any dog picture on the front page, you could get to their profile(with the dog's name in the URL) that should use one template for each of them.
Here is my code in models, views and urls:
models.py
class dog(models.Model):
name = models.CharField(max_length=30, blank=False, null=True)
main_image = models.ImageField(upload_to='dogs', blank=False, null=True)
MALE = 'ML'
FEMALE = 'FM'
gender_list = (
(MALE, 'male'),
(FEMALE, 'female'),
)
gender = models.CharField(max_length=2, choices=gender_list, default='gender')
description = models.TextField(max_length=500, blank=False, null=True)
birthday = models.DateField(default=datetime.today, blank=True)
slug = AutoSlugField(populate_from='name')
views.py
def home(request):
dog_list = list(dog.objects.all())
template = 'home.html'
return render(request, template, {'dogs' : dog_list})
def dog_view(request, slug):
dog_view = get_object_or_404(dog, slug=slug)
return render(request, 'profile.html', {'dog_view' : dog_view})
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^dogs/(?P<slug>[-\w]+)/$', views.dog_view, name='profile'),
url(r'^mating/', views.mating_list, name='mating'),
url(r'^admin/', admin.site.urls),
]
home.html
{% for dog in dogs %}
<a href="{% url 'profile' %}{{ dog.name }}">
<div class="col-sm-4">
<img class="img-circle img-responsive img-center" src="{{ dog.main_image.url }}" alt="">
<h2 align=center>{{ dog.name }}
<p>{{ dog.description }}</p>
</div>
{% endfor %}
I feel that it should be something very easy, although I searched over the internet and couldn't find how it is possible to have pages be automatically created along with the dog-objects.
Thank you very much in advance.
Try this:
views.py
def home(request):
dog_list = dog.objects.all()
template = 'home.html'
return render(request, template, {'dogs' : dog_list})
def dog_view(request, slug):
dog_view = get_object_or_404(dog, slug=slug)
return render(request, 'profile.html', {'dog_view' : dog_view})
home.html
{% for dog in dogs %}
{{ dog.name }}
<div class="col-sm-4">
<img class="img-circle img-responsive img-center" src="{{ dog.main_image.url }}" alt="">
<h2 align=center>{{ dog.name }}
<p>{{ dog.description }}</p>
</div>
{% endfor %}
urls.py
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^dogs/(?P<slug>[-\w]+)/$', views.dog_view, name='profile'),
url(r'^mating/', views.mating_list, name='mating'),
url(r'^admin/', admin.site.urls),
]