Hi there.
I’m not able to figure out how to solve in a simple and clean way the
following problem.
Basically what I want to do is to edit the instances of the following
model:
Models.py
class Seller(models.Model):
brand = models.CharField(max_length=250)
...
slug = models.SlugField(unique=True)
The form is generated using the following code. The validator should
ensure that the entered brand is unique among the registered users. I
would use the same form both to create and to edit Seller instances.
Forms.py
class SellerForm(ModelForm):
class Meta:
model = Seller
def clean_brand(self):
try:
Seller.objects.get(brand=self.cleaned_data['brand'])
except Seller.DoesNotExist:
return self.cleaned_data['brand']
raise forms.ValidationError("This brand is already used.
Please choose another.")
Finally, the view for editing a Seller instance is the following:
Views.py
def edit(request):
if 'seller' in request.session:
this_seller = get_object_or_404(Seller, pk=request.session
['seller'])
else:
return render_to_response('default.html', {'notice': "Seller
must be logged in to edit the profile"})
if request.method == 'POST':
form = EditForm(request.POST, instance = this_seller)
if form.is_valid():
new_seller = form.save()
return render_to_response('default.html', {'notice':
"Seller profile has been updated"})
else:
return render_to_response('edit.html', {'edit_form':form})
else:
form = EditForm(instance = this_seller)
return render_to_response('edit.html', {'edit_form':form})
The problem I’m facing is the clean_brand validator. As a matter of
fact I want the brand to be unique for each user. The code works fine
when I firstly create a new brand. However when editing an existing
brand with the above code, a validation error is generated if the
brand is not modified, since the brand already exists in the
database.
Is there a simple way to solve this problem?
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en.