Home > OS >  When I include a hidden field in my modelform, the modelform is not submitted
When I include a hidden field in my modelform, the modelform is not submitted

Time:09-30

I am trying to build up a posting webpage.

This is how it works:
you click a button, the posting form will appear, you fill in the form, you click the submit button, and the process is complete. And when the form is submitted, a url parameter will be passed as the value of a hidden input in the modelform in the views.py.

Everything had been working fine until I added in my modelform the 'username' field which has the HiddenInput as a widget. It seems like modelform is not submitted at all.

Here are my codes:
models.py

from django.db import models
from django.db.models import CharField, TextField, DateField

class Post(models.Model):
    username = CharField(max_length=30)
    content = TextField()
    dt_created = DateField(auto_now_add=True)
    dt_modified = DateField(auto_now=True)

    def __str__(self):
        return self.content

forms.py

from django import forms
from django.forms import Textarea, HiddenInput
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['content', 'username']
        widgets = {
            'content': Textarea(attrs={
                'class': 'write_input',
                'placeholder': 'write your story here...'
            }),
            'username': HiddenInput(attrs={
                'value': ' '
            })
        }
        labels = {
            'content': ''
        }

views.py

from django.shortcuts import render, redirect
from .forms import PostForm
from .models import Post

def account_main(request, username):
    context = dict()
    if request.method == 'POST':
        form = PostForm(request.POST, initial={'username': username})
        if form.is_valid():
            form.save()
            return redirect('account_main', username=username)
    form = PostForm()
    posts = Post.objects.all().order_by('dt_created')

    context['username'] = username
    context['form'] = form
    context['posts'] = posts
    return render(request, 'Account/account_main.html', context=context)

I have been looking at Google and Stack Overflow for a few hours, but I could not find any solution that somehow solves the issue. Could somebody please lend me a hand? And thank you very much in advance.

CodePudding user response:

If you want to use the Username field as a hidden field and don't pass any value in Username while submitting the form, it throws an exception error.

To avoid this you must set the username field as

--in models.py--

username = CharField(max_length=30, blank=true,null=true)

  • Related