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),
]
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 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.
I want to add a slider to my homepage. What is best way to do it? Should I create a new app for slider? Or can I create a class for slider in home(app)/models.py?
I tried to create Slider class in home/models.py. But I couldn't list on homepage.
home/views.py
def slider_index(request):
slides = Slider.objects.all()
return render(request, 'home.html', {'slides': slides})
def slider_detail(request, id):
slide = get_object_or_404(Slider, id=id)
context = {
'slide': slide,
}
return render(request, 'home.html', context)
home/models.py
class Slider(models.Model):
title = models.CharField(max_length=120, verbose_name='Başlık')
content = models.TextField(verbose_name='Açıklama')
publishing_date = models.DateTimeField(verbose_name='Yayınlanma Tarihi', auto_now_add=True)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('slide:detail', kwargs={'id': self.id})
# return "/slider/{}".format(self.id)
class Meta:
ordering = ['-publishing_date', '-id']
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view),
path('slider/', slider_index, name='index'),
path('slider/<int:id>/', slider_detail, name='detail'),
path('post/', include('post.urls')),
]
and home.html:
{% for slide in slides %}
<!-- Slide #1 image -->
{% if slide.image %}
<img src="{{ slide.image.url }}" alt="{{ slide.content }}" title="{{ slide.title }}" />
{% endif %}
{% endfor %}
Nothing appears about slider. I'm newbie in django. I want to learn how to list slides in homepage.
Thanks in advance.
I have a problem (I think) with urls and views. So that, I have 3 categories, and each of them has 3 subcategories. I want to open subcategories when clicked on each category.
urls.py:
urlpatterns = [
path('', views.index),
url(r'^category/(?P<pk>\d+)$', views.category, name='category'),
]
views.py:
def category(request):
categories = Category.objects.all()
subcategories = SubCategory.objects.all()
return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories}
base.html:
{% for category in categories%}
<a class="dropdown-item" href="{% url 'category' pk=category.pk %}">{{ category.name }}</a>
{% endfor %}
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
class SubCategory(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
image_url = models.CharField(default=0, max_length=2000)
price = models.IntegerField(default=0)
urls.py
urlpatterns = [
path('', views.index),
url(r'^get_subcategory/(?P<pk>\d+)$', views.get_subcategory, name='get_subcategory'),
]
models.py(should like this)
class Category():
name=models.CharField()
class SubCategory():
name=models.CharField()
category = models.ForeignKey(Category)
views.py
def get_subcategory(request, pk):
category = Category.objects.get(id=pk)
subcategories = SubCategory.objects.filter(category=category)
return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories}
html
{% for category in categories%}
<a class="dropdown-item" href="{% url 'YourAppName:get_subcategory' pk=category.id %}">{{ category.name }}</a>
{% endfor %}
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"),
]