Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8637085
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T10:23:31+00:00 2026-06-12T10:23:31+00:00

I used this code previously it worked fine and i was suggested to use

  • 0

I used this code previously it worked fine and i was suggested to use ModelForm by another member, it did make sense to use the form.is_valid() function etc.. so thought of giving it a try.

I went through some other examples on the internet but mine does not seem to work for some reason, or may be I am not doing it right, I get the following when I print the form in the view, and it goes to the else statement, so my form does not get saved

<input id="id_product" type="text" name="product" value="aassddf" maxlength="250" />
FAIL

My model.py

from django.db import models
from django.forms import ModelForm

class Category(models.Model):
    name = models.CharField(max_length=250)

    def __unicode__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(Category)
    product = models.CharField(max_length=250)
    quantity = models.IntegerField(default=0)
    price = models.FloatField(default=0.0)

    def __unicode__(self):
        return self.product

class ProductForm(ModelForm):
    class Meta:
        model = Product

My views.py

from models import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

def index(request):
    ...
    ...

def add_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST)
        print form['product']
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/product')
        else:
            print 'FAIL'
    return HttpResponseRedirect('/product')

My html

<form method="post" action="add_product/">
        {% csrf_token %}
        <label for="category">Category</label>
        <select name="category" id="category">
        {% for category in category_list %}
          <option> {{ category.name }} </option>
        {% endfor %}
        </select>

        <label for="product">Product</label>
        <input type="text" name="product" id="product">

        <label for="quantity">Quantitiy</label>
        <input type="text" name="quantity" id="quantity">

        <label for="price">Price</label>
        <input type="text" name="price" id="price">

        <input type="submit" value="Add New product" id="create">
    </form>

Is there a better way i could save the data, using ModelForms ??
Thanks in advance for the help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T10:23:32+00:00Added an answer on June 12, 2026 at 10:23 am

    Thanks to Daniel Roseman and Anuj Gupta I think I finally re-worked on my code on got it working in a standard way so it will generate the html form and validate errors.

    So for anyone else who is trying to work django forms here is the code I worked on.

    My model.py is was almost the same one i posted on the question but i removed

    class ProductForm(ModelForm):
        class Meta:
            model = Product
    

    I created a new form.py here is the code-

    from django import forms
    from models import Category
    
    class ProductForm(forms.Form):
        # Put all my Categories into a select option
        category = forms.ModelChoiceField(queryset=Category.objects.all())
        product = forms.CharField()
        quantity = forms.IntegerField()
        price = forms.FloatField()  
    

    My views.py changed had a lot of changes –

    def add_product(request):
        success = False
    
        if request.method == "POST":        
            product_form = ProductForm(request.POST)
    
            if product_form.is_valid():             
                success = True
    
                category = Category.objects.get(name=product_form.cleaned_data['category'])
                product = product_form.cleaned_data['product']
                quantity = product_form.cleaned_data['quantity']
                price = product_form.cleaned_data['price']
    
                new_product = Product(category = category, product = product, quantity = quantity, price = price )
                new_product.save()
    
                new_product_form = ProductForm()
    
                ctx2 = {'success':success, 'product_form':new_product_form}
                return render_to_response('product/add_product.html', ctx2 , context_instance=RequestContext(request))
        else:
            product_form = ProductForm()
        ctx = {'product_form':product_form}
        return render_to_response('product/add_product.html', ctx , context_instance=RequestContext(request))
    

    Finally in my html page i used {{ product_form.as_p }} so it created the forms dynamically

    {% if success %}
        <h3> product added successfully </h3>
    {% endif %}         
    <form method="post" action=".">
        {% csrf_token %}
    
        {{ product_form.as_p }}
    
        <input type="submit" value="Add New product" id="create">
        <input type="reset" value="reset" id="reset">   
    </form>
    

    This may not be the perfect solution, but for a starter like me this sounds good, and at times you just get lost while reading the docs lol, hope it helps some one.

    Cheers

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I used this code previously in netbeans 6.9.1 but it does not seem to
I don't understand why I'm getting this error. I used the same code previously
I used this code to print the current page: <form> <input type=button value=Print onClick=window.print();
This piece of code has previously worked but I have C&P it to a
This question came about because code that worked previously in .NET 4.0 failed with
i used this code: List<string> lists=new List<string>(apple,orange,banana,apple,mang0,orange); string names; names=lists.Distinct() is that correct?
I used this code to draw a line in a panel. private bool isMoving
I used this code in my Android application: import org.apache.http.client.methods.HttpPost; ... HttpClient httpclient =
I used this code for sending and returning result. <script type=text/javascript> $(document).ready(function() { $('.special').click(function(){
I used this code in my users views and had no trouble: <% if

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.