【问题标题】:How can I prepopulate a form in class based views with url variable <str:>如何使用 url 变量 <str:> 在基于类的视图中预填充表单
【发布时间】:2020-08-19 16:45:19
【问题描述】:

正如问题所说,我正在尝试使用 url 变量预填充表单,我的意思是表单填充了 url 中的变量。我试图使用 get initial 函数,但它不起作用,所以我将分享我的代码,以便您了解发生了什么以及我在做什么错误

views.py

class AddPostView(CreateView):
    model = Post
    form_class = PostForm
    template_name = 'app1/createpost.html'

    def get_initial(self, **kwargs):
        
        #Returns the initial data to use for forms on this view.
        initial = super().get_initial()

        initial['stock'] = self.kwargs.get('sym')

        return initial

        def form_valid(self, form, sym):
            form.instance.author = self.request.user
            return super().form_valid(form)

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,))

forms.py

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title','category', 'body', 'snippet', 'header_image', 'stock')

        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Title', 'length':'100px'}),
            #'author': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id':'elder','type': 'hidden'}),
            #'author': forms.Select(attrs={'class': 'form-control'}),
            'category': forms.Select(choices = choice_list,attrs={'class': 'form-control', 'placeholder': 'Choices'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
            'snippet': forms.Textarea(attrs={'class': 'form-control'}),
            'stock': forms.Select(choices = choice_list,attrs={'class': 'form-control', 'placeholder': 'Choices'})
            
            
        }

urls.py


app_name = 'app1'

urlpatterns = [
    path('add_post/<str:sym>',AddPostView.as_view(), name='addpost'),

]

【问题讨论】:

    标签: python django forms populate web-frameworks


    【解决方案1】:

    您可以尝试在 views.py (Captured URL parameters in form) 中使用 get_form_kwargs :

    您可以覆盖 get_form_kwargs 并将 stock 传递给 kwargs 字典。然后在您的 __init__() 方法中,在表单上设置您的字段。

    views.py:

    class AddPostView(CreateView):
        model = Post
        form_class = PostForm
        template_name = 'app1/createpost.html'
        stock = None
        
        def get_form_kwargs(self):
            kwargs = super(AddPostView, self).get_form_kwargs()
            stock = self.kwargs.get('sym')
            kwargs.update({'stock': stock})
            return kwargs
    

    forms.py:

    class PostForm(forms.ModelForm):
        
        def __init__(self, *args, **kwargs):
            stock= kwargs.pop('stock')
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields['stock'] = stock
    

    【讨论】:

    猜你喜欢
    • 2020-12-07
    • 2018-03-25
    • 2013-03-08
    • 1970-01-01
    • 2015-06-24
    • 2015-11-08
    • 2019-06-21
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多