【发布时间】: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