Django表单渲染乱序

时间:2018-07-14 01:31:49

标签: django templates render modelform

我正在学习如何使用ModelForms,并且已经成功获取了要呈现的表单,但是字段并没有按照我希望它们显示的顺序显示。我试图更改forms.py中的顺序,但没有效果。我该如何更改订单;例如,将title放在顶部而不是底部,并使picture字段倒数第二而不是第二?

models.py

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Post(models.Model):

    title = models.CharField(max_length=150)
    price = models.CharField(max_length=100)
    body = models.TextField()
    pub_date = models.DateTimeField(null=True)
    author = models.ForeignKey(User, null=True)
    category = models.CharField(max_length=150, null=True)
    picture = models.ImageField(upload_to='ad_pictures', default='')

    def __str__(self):
        return self.title

forms.py

from django import forms
from .models import Post
from django.contrib.auth.models import User

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = {
            'title',
            'body',
            'category',
            'price',
            'picture',
        }

views.py

def create(request):
    form = PostForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        return render(request, 'classifieds/latest-ads.html')
    else:
        form = PostForm()
        args = {'form': form}
        return render(request, 'classifieds/create-post.html', args)

create.html

{% extends 'base.html' %}

{% block head %}
<!-- {% load static %}
<link rel="stylesheet" href="{% static 'accounts/login.css' %}" type="text/css"> -->
<title>Create Post</title>
{% endblock %}

{% block body %}

<div class="container"><br>
  <form method="POST" action='' enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" value="submit">Submit</button>
  </form>
</div>
{% endblock %}

我想指出的是,在this视频中,上传者可以操纵顺序并在模板中更改渲染,但我不能。

任何见识都将不胜感激。

1 个答案:

答案 0 :(得分:0)

不需要field_order = ['price', 'title', 'body', 'category', 'picture']

只需将{}的{​​{1}}替换为()

所以您应该拥有:

fields