🔖 Day5 - Custom Post Form (form.py)

2018 - 06 - 26
🔖 Day5 - Custom Post Form (form.py)
1. [Django Form] 要在Django 建立Form作post threads用,可以新建form.py under app 。 例如app - blog的posts是在Django 預設的admin page才可以貼文, 我們可以把該model class重新定義一下。 在新增的blog/form.py內面建立表單:
from django import forms
from .models import Post
class PostForm(forms.ModelForm):

class Meta:
    model = Post
    fields = ('title', 'content', 'photo', 'photo_upload',)

class Meta裡面,我們表明哪個model需要制作表單, 而fields則說明表單有哪些細項。
2. [Set url] 接著我們又建立新 urlpatterns給post page用 e.g.settings/urls.py
urlpatterns=[
    ...,
    path(r'post_new/', post_new, name='post_new'),
]

還有到views.pydefine post_new這個function
from .forms import PostForm

def post_new(request):
    user = request.user
    if not user.is_authenticate or user.username != "admin":
        return app_index(request)

    if request.method == "POST":
        postform = PostForm(request.POST)
        if postform.is_valid:
            postform.save()
            return app_index(request)
    else: 
        return render(request, 'post_new.html', {'form':postform})

這裡我們驗證了帳目是admin才可以進入版面,而且回傳{'form':postform}post_new.html作表單用
3. [Create a new template] 建立templates/post_new.html。 利用Django 內建的{{form.as_p}}都可以順利完成,也可以自定介面: 以上面form.py定義的field包括有title, content, photo, photo_upload e.g.
<form method="POST">
{% csrf_token %}
{% for field in form %}
    <label for='{{ field.name }}'>{{ field.label_tag }}</label>
    {{ field }}
    {% if field.help_text %}
        {% field.help_text %}
    {% endif %}
{% endfor %}
</form>


Comments

Alex
<a href=J-A-V-A-S-C-R-I-P-T:alert()>hello
Jan. 23, 2018, 11:30 p.m.

New Comment

Please Login to comment