Leon
Leon

Reputation: 6544

Editing model with form.py

Can someone explain me the following? How can I update code, that I can use form on obj creating and editing (just one code)? Example

model.py:

class Car(models.Model):
    car = models.CharField('#', max_length=5)
    def __unicode__(self):
        return str(self.id)

forms.py:

class AddCar(forms.Form):
    car = forms.CharField(label='#', max_length=5, required=True, 
        widget=forms.TextInput(attrs={'class':'', 'title': '#', 
        'placeholder': '#', 'required': 'true'}))

views.py:

@csrf_protect
@login_required
def add_car(request):
    if request.method == 'POST': 
        form = AddCar(request.POST)
        if form.is_valid():
            pass
    else:
        form = AddCar()
    return render(request, 'add_car.html', {'form': form, })

So, I need to create a new url

url(r'^edit/(?P<car_id>\d+)/$', 'cars.views.edit_car', name='edit_car'),

Then in views:

@csrf_protect
@login_required
def edit_car(request, car_id):
    car = get_object_or_404(Car, pk=car_id)

Whats next? How to use AddCar form with values from car? How to check, if user update the information in form?

Thanks.

Update

In edit_car I use (docs)

form = AddCar(car)

But I have an error: 'Car' object has no attribute 'get' for all {{ form.field }} in template.

Upvotes: 1

Views: 56

Answers (2)

Leon
Leon

Reputation: 6544

form = AddCar({'car': get_object_or_404(Car, pk=car_id,).name,})

Without ModelForm

Upvotes: 1

Maciej Gol
Maciej Gol

Reputation: 15854

The car can be passed to the ModelForm instance as the instance keyword argument, ie.

AddCar(instance=car)

To detect changes, you could use the is_valid() method of the AddCar instance combined with cleaned_data dictionary. You would have to fetch the car object as already you are, instantiate the AddCar form with request.POST values, and then compare values between the car you've fetched and AddCar.cleaned_data.

Upvotes: 1

Related Questions