我在 url 變量和基于類的視圖方面有問題,但主要是在 html 或模板中,因?yàn)槲也恢廊绾伪硎舅?,我將向您展示代碼以便您理解。urls.pyapp_name = 'app1'urlpatterns = [ path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),]views.pyclass 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 alamodels.pyclass 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,))模板(我在添加帖子(當(dāng)前)時(shí)遇到問題){% 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 %}
1 回答

心有法竹
TA貢獻(xiàn)1866條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試:
<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
添加回答
舉報(bào)
0/150
提交
取消