如何让Django表单字段在我的自定义html创建后模型表单中工作



以下是我对创建帖子的看法。。我真的很感激关于如何在我的Html代码中适应表单字段的解决方案

def create_post(request):
context = {}
user = request.user
if request.method == "POST":
form = NewPostForm(request.POST, request.FILES)
if form.is_valid():
data = form.save(commit=False)
data.user_name = user
data.save()
messages.success(request, f'Posted Successfully')
return redirect('feed')
else:
form = NewPostForm()
context['NewPostForm'] = form
return render(request, 'feed/feed.html', context)

这是我的表单模型,我如何访问下面html代码中的表单字段,而不必使用这样的表单变量{{form.as_p}}

class NewPostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('description', 'pic', 'tags',)
class NewCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('comment',)

这是我为这篇文章编写的HTML代码。

<div id="create-post-modal" class="create-post" uk-modal>
<div class="uk-modal-dialog uk-modal-body uk-margin-auto-vertical rounded-lg p-0 lg:w-5/12 relative shadow-2xl uk-animation-slide-bottom-small">
<div class="text-center py-4 border-b">
<h3 class="text-lg font-semibold"> Create Post </h3>
<button class="uk-modal-close-default bg-gray-100 rounded-full p-2.5 m-1 right-2"  uk-close uk-tooltip="title: Close ; pos: bottom ;offset:7"></button>
</div>
<div class="flex flex-1 items-start space-x-4 p-5">
<img src="{{ user.profile_pic.url }}" class="bg-gray-200 border border-white rounded-full w-11 h-11">
<div class="flex-1 pt-2">
<form method="POST" id="post_form">{% csrf_token %}
<fieldset>
<textarea name="description" id="id_description" class="uk-textare text-black shadow-none focus:shadow-none text-xl font-medium resize-none" rows="5" placeholder="What's Your Mind ? {{ user.first_name }}"></textarea>
</fieldset>
</form>
</div>
</div>
<div class="bsolute bottom-0 p-4 space-x-4 w-full">
<div class="flex bg-gray-50 border border-purple-100 rounded-2xl p-3 shadow-sm items-center">
<div class="lg:block hidden"> Add to your post </div>
<div class="flex flex-1 items-center lg:justify-end justify-center space-x-2">

在HTML模板中,您可能需要

对于馈送文本,

{{ NewPostForm.description }}

对于图像,

{{ NewPostForm.pic }}

最新更新