Home > Net >  Is there a reason why this django form isn't valid?
Is there a reason why this django form isn't valid?

Time:01-01

my form is valid only when i use {{ post_form }} without specifying the field, i know this because when i tried it i was able to save it to the data base, so i think i'm doing something wrong in my template.

by the way none of these fields are required so i believe they should be able to go empty in the data base... right?

this is the html form:

<section id="newpost-form">
    <form action="{% url 'newpost' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <label for="id_title">Title</label>
        {{ post_form.title }}
        <label for="id_image">Thumbnail</label>
        {{ post_form.image }}
        {{ post_form.content }}
        {{ post_form.media }}      // this one is for a ckeditor rich text area called content
        <button type="submit" >Create</button>
    </form>
</section>

this is forms.py

class NewPost(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['image', 'title', 'content', 'status', 'author',]

i would like not to show the fields 'status' and 'author' because im handling them in the views.py after the 'is_valid():'

and my views.py in case it is relevant:

if request.method == 'POST':
    post_form = NewPost(request.POST, request.FILES)
    if post_form.is_valid():
            ...

CodePudding user response:

A better solution would be to exclude the fields from the model form, and in your template, {{post_form.as_p}}, and define attributes in your forms.py fields

For example:

form.html:

<section id="newpost-form">
    <form action="{% url 'newpost' %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        {{ post_form.as_p }}
        <button type="submit" >Create</button>
    </form>
</section>

forms.py:

class NewPost(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['image', 'title', 'content']

        labels = {'image': ('Image:'),'title': ('Title:'),'content': ('Content:')}

        widgets = {
            'image': forms.TextInput***imagefield or whichever field type used***(attrs={'class': 'form-control', 'placeholder': ''}),
            'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': ''}),
            'content': forms.TextArea(attrs={'class': 'form-control', 'placeholder': ''}),

CodePudding user response:

if not don't need autor and status then remove it from your fields

class NewPost(forms.ModelForm):
    class Meta:
        model = Post
        fields= ['image', 'title', 'content',]
  • Related