如何使用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'),]

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)