Как создать ссылку для деталей в каждом сообщении
Я делаю проект, в котором я отображаю список всех крупных дилерских центров в вашем регионе, но также позволяю пользователю самостоятельно продать свой автомобиль. Я работаю над частью, связанной с самостоятельной продажей, и застрял на одном моменте. На данный момент пользователь может создать сообщение, и оно будет отображено на сайте, рядом с сообщением есть кнопка "Просмотр", которая показывает детали автомобиля, такие как пробег, контакт, дата публикации и т.д. Проблема в том, что я не знаю, как сделать так, чтобы каждый пост имел свою собственную страницу просмотра. Как мне сделать так, чтобы у каждого сообщения была своя страница с деталями?
Вот мой код на данный момент:
views.py
from django.shortcuts import render
from .models import *
from django.http import HttpResponse
def home(request):
context = {}
return render(request, 'store/home.html', context)
def store(request):
context = {}
return render(request, 'store/store.html', context)
def cart(request):
context = {}
return render(request, 'store/cart.html', context)
def checkout(request):
context = {}
return render(request, 'store/checkout.html', context)
def posts(request):
cars = Userpost.objects.all()
context = {'cars':cars}
return render(request, 'store/userposts.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = "home"),
path('posts/', views.posts, name = "posts"),
path('store/', views.store, name = "store"),
]
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null= True)
def __str__(self):
return self.name
class Userpost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
Year = models.CharField(max_length = 4)
Mileage = models.CharField(max_length = 8)
Make = models.CharField(max_length = 50)
Model = models.CharField(max_length = 50)
Price = models.DecimalField(max_digits=15, decimal_places=2)
email = models.EmailField()
date_published = models.DateField(default = timezone.now)
image = models.ImageField(null = True, blank = True)
def __str__(self):
return self.Year + " " + self.Make + " " + self.Model
@property
def imageURL(self):
try:
url = self.image.url
except:
url = ''
return url
Шаблон
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{% for car in cars %}
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<button class="btn btn-outline-secondary add-btn">Add to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
Я только изучаю Django, поэтому часто застреваю и теряюсь. Буду благодарен за любую помощь.
добавьте это в ваш views.py
from django.shortcuts import render,get_object_or_404,redirect
def post_detail(request,post_id):
cars = get_object_or_404(Userpost,pk=post_id)
context = {'car':car}
return render(request, 'store/userpost_detail.html', context)
userpost_detail.html
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-lg-4">
<img class="thumbnail" src="{{car.imageURL}}">
<div class="box-element product">
<h6><strong>{{car.Year}} {{car.Make}} {{car.Model}}</strong></h6>
<hr>
<button class="btn btn-outline-secondary add-btn">Add to Cart</button>
<h4 style="display: inline-block; float: right"><strong>${{car.Price|floatformat:2}}</strong></h4>
</div>
</div>
</div>
{% endblock content %}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name = "home"),
path('posts/', views.posts, name = "posts"),
path('store/', views.store, name = "store"),
path('post/<int:post_id>/', views.post_detail, name = "post_detail"),#new
]
теперь внутри вашего userposts.html, если вы хотите получить деталь страницы, вы можете сделать что-то вроде этого
<a class="btn btn-outline-success" href="{% url 'post_detail' car.pk %}">View</a>