如何创建帖子?

时间:2020-03-18 13:53:47

标签: python html django

我在正确使用表格时遇到一些问题。 我搜索了如何创建帖子,但遇到了问题; 我不知道为什么发帖不起作用。

我要保存POST和图像文件。

views.py

@login_required()
def postFind(request):
if request == "POST":
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        post = form.save(commit = False)
        post.menu = True
        post.pub_date = timezone.datetime.now()
        post.up_date = timezone.datetime.now()
        post.user = request.user
        post.save()
        return HttpResponseRedirect(reverse('website:postCheck', args=(post.id)))
else:
    form = PostForm()
    return render(request, 'postFind.html', {'form' : form})

postFind.html

{% if user.is_authenticated %}
<div class="form">
    <form class="post-form" method="post" enctype="multipart/form-data" action="{% url 'website:postFind' %}">
        {% csrf_token %}
        <div class="wrapper">
            <div class="box">
                <div class="js--image-preview"></div>
                <div class="upload-options">
                    <label>
                        {{ form.image }}
                    </label>
                </div>
            </div>

            <p id="info">Species</p>
            {{ form.species }}
            <p id="info">Location</p>
            {{ form.location }}
            <p id="info">Date</p>
            {{ form.date }}
            <p id="info">Feature</p>
            {{ form.feature }}

            <button type="submit" class="btn btn-default">Submit</button>

            <a class="btn btn-default" href="{% url 'website:homePost' %}" role="button" id="button">Cancel</a>
        </form>
</div>
{% endif %}

form.py

class PostForm(ModelForm):
class Meta:
    model = Post
    fields = ['image', 'species', 'location', 'date', 'feature']

2 个答案:

答案 0 :(得分:1)

在您的views.py中,我认为您应该使用

if request.method == "POST":

代替

if request == "POST":

答案 1 :(得分:0)

一切都很好,但是保存后,您应该像这样重定向

from django.shortcuts import redirect

......
if form.is_valid():
    post = form.save(commit = False)
    post.menu = True
    post.pub_date = timezone.datetime.now()
    post.up_date = timezone.datetime.now()
    post.user = request.user
    post.save()
    return redirect(reverse('website:postCheck', args=[str(post.id)]))