0

I have different models:

Cars
Pictures (models.ForeignKey(Cars))
CarsOptions(models.OneToOneField(Cars))

Then I want, that user can add new cars. Forms.py:

class NewCarsForm(ModelForm):
    class Meta:
        model = Cars
        exclude = ('checked','user')

In views.py:

@login_required
def add_car(request):
    form = NewCarsForm(request.POST or None)
    if form.is_valid(): 
        cmodel = form.save()
        cmodel.save()
        return redirect(profile)
    return render(request, 'add_car.html', { 'form': form,})

I have a few questions (yes, I read this).

  1. As you can see, user can add only "car", not pictures and options. How to do this on one page in one form?
  2. exclude = ('checked','user'), it means, that I want to make all new positions with checked=0, so I can filter them. And the user-field - users cant choose user in a list. How to take user id (who adds car) in form.save()?

Thanks.

Update:

class Pictures(models.Model):
    cars = models.ForeignKey(Cars, related_name='pictures')
    width = models.PositiveIntegerField(editable=False, default=640)
    height = models.PositiveIntegerField(editable=False, default=480)
    image = models.ImageField(upload_to=lambda inst, fname: 'users_img/' + 'cars' + fname, height_field='height', width_field='width', max_length=100)
    def __unicode__(self):
        return str(self.id)
4
  • 1. This is 3 different model forms. If the 3 have permanent one-to-one relations to each other why not to combine them in 1 model? Commented Mar 10, 2013 at 18:38
  • not 3, one model with 1 2 1 Commented Mar 10, 2013 at 18:50
  • It's not clear do you mean a single Django form you want or do you mean a single html form? Commented Mar 10, 2013 at 22:30
  • Use inline formset and getting the user is easy. If no one answer this, I will answer it later. Commented Mar 11, 2013 at 0:37

1 Answer 1

2

forms.py

class NewCarsForm(ModelForm):
    class Meta:
        model = Cars
        exclude = ('checked','user')

PicturesFormset = inlineformset_factory(Cars, Pictures, 
    fields=('field_name', 'field_name'), can_delete=True)

CarsOptionsFormset = inlineformset_factory(Cars, CarsOptions, 
    fields=('field_name', 'field_name'), can_delete=True)

views.py

@login_required
def add_car(request):
    cars = Cars(user=request.user)
    if request.method == 'POST':
        form = NewCarsForm(request.POST, instance=cars)
        if form.is_valid(): 
            cmodel = form.save()

            picture_formset = PicturesFormset(request.POST, request.FILES,
                instance=cmodel)
            if picture_formset.is_valid():
                picture_formset.save()

            option_formset = CarsOptionsFormset(request.POST, instance=cmodel)
            if option_formset.is_valid():
                option_formset.save()

            return redirect(profile)

    form = NewCarsForm()
    picture_formset = PicturesFormset(instance=Cars())
    option_formset = CarsOptionsFormset(instance=Cars())

    return render(request, 'add_car.html', { 
        'form': form,
        'picture_formset': picture_formset,
        'option_formset': option_formset,
    })

template

<form method="POST" enctype="multipart/form-data">
    {% csrf_token %}

    <h4>Car:</h4>
    {{ form.as_p }}

    <h4>Picture:</h4>
    {{ picture_formset.as_p }}

    <h4>Options:</h4>
    {{ option_formset.as_p }}

    <input type="submit" value="Submit">
</form>
Sign up to request clarification or add additional context in comments.

10 Comments

IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'")
remove option_formset...Try to save Cars and Picture only, we will see if that error will shown again. Test it one by one so that you will know the root of the problem. In that way, it is easy to debug and fix the problem
I remove 1 by one, so I have only Cars, but the error is the same.
Change it to ForeignKey to allow the user enter other data. OneToOneField only allow to save one data per user.
Because you forgot to put enctype="multipart/form-data" in the template form
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.