[Answered ]-How to display a ForeignKey as RadioSelect options from DetailView in Django?

2đź‘Ť

âś…

In short, a DetailView is for displaying data. Given that you’re asking the user questions (“Which materials?”, “Which sizes?” etc.), you’ll almost certainly really do want to use forms. This is what forms are designed for!

In order for the following to work, I suggest you reverse how your ForeignKeys are defined; I assume you want the same material used in multiple products, not the other way ’round! Add a field like material = models.ForeignKey(Material, related_name='products') to your Product, and delete the product field from Material etc.

Using forms might end up being pretty easy in your situation. Check out the “Creating forms from models” documentation, and try something like the following:

# urls.py
from django.views.generic import CreateView

urlpatterns = patterns('', ...
    url(r'^(?P<pk>\d+)/$', CreateView.as_view(
        model = Product,
        template_name = "add_product.html"
    )),
)

This would get you the default Select widget — the “Creating forms from models” documentaiton (above) has information on customising the widget used to draw form fields. You would need to create a new form (inheriting from ModelForm) and point your view at that form:

# forms.py
from django import forms

from catalogue.models import Product

class ProductForm(forms.ModelForms):
    class Meta:
        model = Product 
        widgets = {
            'material': forms.RadioSelect()
            ...
        }

# urls.py

from catalogue.forms import ProductForm

# add the following parameter to your call to as_view():
...
    'form_class': ProductForm
👤supervacuo

Leave a comment