Home > Enterprise >  How to add a new obj from html in django
How to add a new obj from html in django

Time:12-30

So im trying to make this page where i add new category which only has name. But when i try it, i just get a "non-string type" as the name. So it works i guess just doesn't take whatever i give it in my input in html.

HTML:

<input type="text"  placeholder="Name" id = "category-create-name" name= 
"category_name">
<input type="submit"  value="Post">

Model:

class Category(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

Form:

class CategoryCreateForm(forms.ModelForm):
class Meta:
    model = Category
    fields = ('name',)
    widgets = {
        'category_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name', 'id':'category-create-name'}),
        }

View:

class CategoryCreateView(CreateView):
form_class = CategoryCreateForm
template_name = 'product/new_category.html'
success_url = '/dashboard/'

CodePudding user response:

There are a couple of things I see here. First in your form. In the widgets attribute of class Meta, the keys in that dictionary need to be a field name that is in your fields attribute. In other words you need to change 'category_name' to 'name'. Second, in your template that is used for the view. You seem to be manually defining a separate input field rather than the one that your view and form are expecting. You should just define the form in your template like this:

<form method="POST">
   {% csrf_token %}
   {{ form_as_p }}
   <input type="submit"  value="Post">
</form>

In the template {{ form.as_p }} will take the form that you gave to your view, and automatically create it in the html when it is being rendered to the page.

  • Related