我是Django的新手,我正在一个网站上,用户可以提交帖子。当我在模型中有很多字段时,Django Form不会保存在数据库中。我不知道我是否可以在Django中实现此目的,我想在帖子中附加其他用户名,以便在我提交表单时在admin中检查帖子时自动选择用户名。为了清楚起见,我将附上屏幕截图。
下面的图像是我的表单,您可以看到“我的帖子”是image_caption,而“安迪”是另一个用户名,我希望在提交表单时在许多区域自动选择“安迪”。
这是提交表格时我想要的,然后我签入管理员。提交表单时,在许多区域中选择了另一个用户名(andy)。我是手动完成的
型号:
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
profile_pic = models.ImageField(upload_to='ProfilePicture/', default="ProfilePicture/user-img.png", blank=True)
class Post(models.Model):
poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True)
image_caption = models.TextField(blank=True, null=True)
tag_someone = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='tagged_users', blank=True)
表格:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = (
'image_caption',
'tag_someone',
)
观看次数:
def upload_view(request):
ImageFormset = modelformset_factory(File, fields=('files',), extra=20)
if request.method == "POST":
form = PostForm(request.POST)
formset = ImageFormset(request.POST, request.FILES)
if form.is_valid() and formset.is_valid():
post = form.save(commit=False)
post.poster_profile = request.user
post.save()
form.save_m2m()
for f in formset:
try:
photo = File(post=post, files=f.cleaned_data['files'])
photo.save()
except Exception as e:
break
return redirect('/')
else:
form = PostForm()
formset = ImageFormset(queryset=File.objects.none())
#User Name Auto-complete In Tag Form
all_users = User.objects.values_list('username', flat=True)
context = {
'form': form,
'formset': formset,
'all_users': all_users,
}
return render(request, 'upload.html', context)
Upload.html:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
{{ formset }}
<button type="submit" class="btn btn-primary btn-sm btn-block w-25">Post</button>
</form>
答案 0 :(得分:1)
我可以通过将小部件更改为:
widget = {
forms.Select(),
}
答案 1 :(得分:0)
您可以在此处更改小部件。小部件是负责将输入输出到HTML的东西。所以您只需要:
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = (
'image_caption',
'tag_someone',
)
widgets = {'tag_someone': forms.TextInput}