#Inserting data into the database(Mysql)

1 messages · Page 1 of 1 (latest)

rose cedar
#

views.py
def brand(request):
form = BrandForm()
if request.method == 'POST':
form = BrandForm(request.POST)
if form.is_valid():
brand = form.save(commit=False)
brand.brandname = form.cleaned_data['brandname']
brand.save()
transaction.commit()
return redirect('brand_list')
else:
print(form.errors)

return render(request, 'brand.html', {'form': form})

models.py
class Brands(models.Model):
brandname = models.CharField(max_length=25, unique=True)

forms.py
class BrandForm(forms.ModelForm):
class Meta:
model = Brands #the model the form is associated with
fields = ['brandname']

brand.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylsheet" href="product.css">
</head>
<body>
<div id=>
<form method="POST " action="{% url 'brand' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit"> Submit </button>
</form>
</div>
</body>
</html>

In urls.py I have used brand for the pathname in urlpatterns

I am not able to insert data into the brands table in Mysql

#

I am new to Django

warped musk
#

what happens if you try to submit the form?

#

since you are using a ModelForm with specified fields, you should not have to assign/save the fields manually later, also the commit=False and transaction.commit() seem unnecessary, you can shorten that block down to

        if form.is_valid():
            brand = form.save()
            return redirect('brand_list')
#

saving a ModelForm returns an instance of the associated model. with commit=False that would just return an instance object in memory, without having persisted it to the database yet, which sometimes is necessary to set certain relational field values separately, but not in this case

rose cedar
#

otherwise the program is running