所以我有一个定义如下的模型Post。
class Post(models.Model):
post_body = models.TextField()
user = models.ForeignKey(
to=User,
on_delete=models.CASCADE
)
published = models.BooleanField(
default=False
)
schedule = models.DateTimeField(
default=timezone.now
)
我在HTML模板中创建了一个表单,允许用户选择他想发送到另一个网站或社交媒体账户的帖子。像这样。
<form>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Select</th>
<th scope="col">Post Body</th>
<th scope="col">Published?</th>
<th scope="col">Schedule (Editable)</th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<td>
<div class="form-group">
<input type="checkbox" value="{{ post.id }}">
</div>
</td>
<td>{{ post.post_body }}</td>
<td>{{ post.published }}</td>
<td>
<div class="form-group">
<input type="datetime-local" class="form-control" name="schedule" value="{{ post.schedule|date:"Y-m-d\TH:i" }}">
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<button class="btn btn-primary" type="submit">Post</button>
</form>
我想在forms.py中创建一个表单,以便处理这些信息(即知道哪些帖子被选中),然后执行进一步的操作(调用其他API,以便将这些帖子发布到其他网站),此外,由于字段时间表是可编辑的,我希望能够保存这些信息。
解决这个问题的一个方法是使用 模型多选字段
这是我在类似情况下使用的结构。
class SelectPostsForm(forms.Form):
posts = forms.ModelMultipleChoiceField(
queryset=Post.objects.none(), widget=forms.CheckboxSelectMultiple)
def __init__(self, filtered_post_queryset, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['posts'].queryset = filtered_post_queryset
def get_posts(self):
return self.cleaned_data.get('posts')
# Example usage
form = SelectPostsForm(Post.objects.all(), data=request.data)
if form.is_valid():
selected_posts = form.get_posts()
# Process posts...
如果你在输入中加入name="posts",它可能会直接和你展示的html代码一起工作。
如果你需要在过滤限制的queryset上做这件事,你可以通过视图提供的 "filtered_post_queryset"。然后,数据将通过 form.is_valid()
对照过滤后的查询集。
如果你想通过表单处理多个相同类型的对象,那么你应该尝试使用 formsets
- https:/docs.djangoproject.comen3.0topicsformsformsets。
还有很多其他的选择,但我认为这个表格集可以满足你的需求。
EDIT:请只把它作为一个指导。
# forms.py
class PostForm(forms.ModelForm):
is_selected = forms.BooleanField(default=False)
class Meta:
model = Post
fields = ("is_selected", "other", "model" "fields")
PostFormSet = modelformset_factory(Post, form=PostForm)
# views.py
class PostView(generic.View):
def get(self, request, *args, **kwargs):
posts = Post.objects.all() # get your Post queryset
formset = PostFormSet(queryset=posts)
# ...
return response
def post(self, request, *args, **kwargs):
formset = PostFormSet(request.POST)
for form in formset.forms:
if form.is_valid() and form.cleaned_data.get("is_selected"):
# here you can save your instance and/or write logic
# to process gathered information
# ...
return response
你想让你所有的 "帖子 "通过 "一个表单() "来呈现,然后对选定的帖子进行操作。表格集 都是在django中使用的,虽然有很多类型,但任何一个简单的表单集都可以完成你的工作。虽然有很多类型,但任何一个简单的表单集都可以完成你的工作。
请访问django文档来实现。https:/docs.djangoproject.comen3.0topicsformsformsets。
为了方便快捷的了解,请访问这个。https:/www.geeksforgeeks.orgdjango-formsets