Erickson Kitoz
Erickson Kitoz

Reputation: 53

Foreign key fields in Django

What is best way to save foreign key fields without letting user to select from the parent model? Let say i have these models

Models

class Category(models.Model):
    category_id = models.AutoFiled(primary_key=True)

class Brand(models.Model):
    brand_id = models.AutoFiled(primary_key=True)

class Product(models.Model):
    category = models.ForeignKey(Category)
    brand = models.ForeignKey(Brand)
    name = models.CharField(max_length = 10, blank=True)

Forms

Class ProductForm(forms.ModelForm):
    class Meta:
        Model = Product
        fields = ['name']

Views

def create_product(request):
    if request.method == "POST":
        form = ProductForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.success(request, 'Successfully Saved!', 'alert-success')
            return redirect('products')
   else:
        return render(request, ' manageproducts/create_product.html', {'form':form})

I want a user to enter only a name but in the database i want a form to post category_id, brand_id and name. How can i do that?

Upvotes: 0

Views: 662

Answers (1)

minglyu
minglyu

Reputation: 3337

You can try HiddenInput widget, which would render as <input type="hidden" ...>. But this requires some js code to provide the correct category and brand values before the form submission

from django import forms

class ProductForm(ModelForm):
    class Meta:
        model = Product
        fields = ('category', 'brand', 'name')
        widgets = {
            'category': forms.HiddenInput(),
            'brand': forms.HiddenInput()
        }

UPDATE

def update_product(request, pk=None):
    try:
        product = Product.ojbects.get(pk=pk)
    except Product.DoesNotExist:
        raise Http404

    form = ProductForm(request.POST or None, instance=product)
    if request.method == "POST":
        if form.is_valid():
            # category and brand will be unchanged
            form.save()
            messages.success(request, 'Successfully Saved!', 'alert-success')
            return redirect('products')
    else:
        return render(request, ' manageproducts/create_product.html', {'form':form})

Without selecting category and brand is only reasonable for updating, for creation of new product, you have to select a new category and brand, otherwise it will break Foreign Key Constraints

Upvotes: 1

Related Questions