Red Red - 1 year ago 106
Python Question

Editing a Row using Django Forms

I wanted to edit a row in Django 1.9 using Django forms:

So what I did is

For the get request I initialized the form instance (

def get(self, request):
myModel = model.myModel.objects.get(user=request.user)
form_instance = MyForm(initial=myModel.__dict__)
return render(request, 'mytemplate.html', {'form': form_instance} )

def post(self, request):
form_instance = MyForm(request.POST)
if form_instance.is_valid():
return redirect('..')
return render(request, 'mytemplate.html', {'form': form_instance} )

This is my

class MyModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
Booth = models.OneToOneField(BoothLocation)
class BoothLocation(models.Model):
LocationID = models.CharField(max_length = 25)

and I have a

class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('Booth')
labels = {'Booth':_('Booth Chosen')}

My problem is that my model have a one to one field, therefore whenever I execute

form_instance = MyForm(request.POST)

it will return an error stating that the onetoonefield must be unique, but I'm just updating it. Is there a way to override this validation?

And by the way, the field really needs to be one on one.

Answer Source

Doing this bit wrong

form_instance = MyForm(initial=myModel.__dict__)

it should be

form_instance = MyForm(instance=myModel)

Oops, forgot to add, in order to handle the situation where the form validation fails, your post meethod might need something like this:

form_instance = MyForm(request.POST, instance=myModel)

you would need to fetch the instance again. As a side note, your code can be greatly simplified by combining your two functions into one and adding if else inside it

if request.method == 'POST':

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download