如何在基于类的视图中使用 url 变量

我在 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 %}

富国沪深
浏览 99回答 1
1回答

心有法竹

尝试:<a href ="{% url 'app1:addpost' sym=sym %}">Add Post<span class="sr-only">(current)</span></a>Views.py - 尝试切换 get_context_data 的方法:class AddPostView(CreateView):     model = Post     form_class = PostForm     template_name = 'app1/createpost.html'     def get_context_data(self, *args, **kwargs):         context = super().get_context_data(**kwargs)         context.update(             sym=get_object_or_404(StockNames, StockNames.symbol)         )                 return context
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python