如何使用url变量<str:>在基于类的视图中预填充表单

问题描述

正如问题所述,我正在尝试使用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,'placeholder': 'Choices'})
            
            
        }

urls.py


app_name = 'app1'

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

解决方法

您可以在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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...