Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a new obj from html in django

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" class="form-control" placeholder="Name" id = "category-create-name" name= 
"category_name">
<input type="submit" class="login-button" value="Post">

Model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/'

>Solution :

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" class="login-button" 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading