Search code examples
google-app-enginereferenceproperty

How to display product name in form


model.py

class Product(db.Model):
    product_name_jp = db.StringProperty(required=True)
    product_code = db.StringProperty(required=True)

class ProductPrice(db.Model):
    product = db.ReferenceProperty(Product,
                                   collection_name='price_collection')
    quantity = db.IntegerProperty()
    price = db.IntegerProperty()

forms.py

class ProductPriceForm(forms.Form):
    f_product = forms.ModelField(model=Product, default=None, label="Product Name")
    f_quantity = forms.TextField("Quantity ", required=True)
    f_price = forms.TextField("Price ", required=True)

views.py

def addproductprice(request):
    productprice_form = ProductPriceForm()



    if request.method =="POST" and productprice_form.validate(request.form):

        productprice_form.save()

    return render_to_response('myapp/message.html',{'form':productprice_form.as_widget(), 'message':'Insert Produce Price xxx '})

Resuls is

https://dl.dropboxusercontent.com/u/27576887/StackOverFlow/2.JPG

https://dl.dropboxusercontent.com/u/27576887/StackOverFlow/3.jpg

My question: How to display the product_name_jp instead of "myapp.models.Product object at xxx"

Thanks


Solution

  • Quote from the docs, under class kay.utils.forms.ModelField:

    If the Model class has __unicode__() method, the return value of this method will be used for rendering the text in an option tag. If there’s no __unicode__() method, Model.__repr__() will be used for this purpose.

    You can override this behavior by passing an attribute name used for the option tag’s value with option_name keyword argument on initialization of this field.

    That tells us you need to set the option_name keyword in this line

    f_product = forms.ModelField(model=Product, default=None, label="Product Name")
    

    It's not documented very well so I can't tell you exactly how to do that, could be one of the following

    f_product = forms.ModelField(model=Product, default=None, label="Product Name", option_name=Product.product_name_jp)
    

    or

    f_product = forms.ModelField(model=Product, default=None, label="Product Name", option_name='product_name_jp')
    

    or

    f_product = forms.ModelField(model=Product, default=None, label="Product Name", option_name=Product._properties['product_name_jp'])
    

    Perhaps something other than the ones I've suggested, I'm not sure, but you will probably find out by trying a couple.


    Edit:

    As mentiond by John in the comments, this was the one that worked

    f_product = forms.ModelField(model=Product, default=None, label="Product Name", option_name='product_name_jp')