我在 url 变量和基于类的视图方面有问题,但主要是在 html 或模板中,因为我不知道如何表示它,我将向您展示代码以便您理解。
urls.py
app_name = 'app1'
urlpatterns = [
path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),
]
views.py
class AddPostView(CreateView):
model = Post
form_class = PostForm
template_name = 'app1/createpost.html'
def get_queryset(self):
ala = Post.objects.filter(stock__symbol=self.kwargs['sym'])
return ala
models.py
class StockNames(models.Model):
name = models.CharField(max_length=255)
symbol = models.CharField(max_length=255)
def __str__(self):
return self.symbol
class Post(models.Model):
title = models.CharField(max_length= 255)
header_image = models.ImageField(null = True, blank = True, upload_to = 'images/')
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = RichTextField(blank = True, null = True)
#body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default='coding')
snippet = models.CharField(max_length=255)
likes = models.ManyToManyField(User, related_name = 'blog_posts')
stock = models.ForeignKey(StockNames, null=True, on_delete = models.CASCADE)
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('app1:article-detail', args=(self.id,))
模板(我在添加帖子(当前)时遇到问题)
{% extends "app1/base.html" %}
{% block body_block %}
{% if stock_sym %}
<h1> {{sym}} </h1>
<a href ="{% url 'app1:addpost' StockNames.symbol %}">Add Post<span class="sr-only">(current)</span></a>
{% if stocks %}
心有法竹
相关分类