开发者

Validating Unique Fields in Django

I don't know if I'm approaching the problem in the right way. The intended outcome is to have a form that displays only name and description. Once the user submits the form I want to add the current user as owner and check if there's already an entry that has the same name and user. If there is, I want to return the form with errors. If not, I want to save Status.

My model:

class Status(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    owner = models.ForeignKey(User)
    active = models.BooleanField(default=True)

    class Meta:
        unique_together = ('name','owner')

My View:

def settings_status(request):
    status_form = StatusForm()

    if request.method == 'POST':
        status_form = StatusForm(request.POST)
            if status_form.is_valid():
                new_status = Status()
                new_status.name = status_form.cleaned_data['name']
                new_status.description = status_form.cleaned_data['description']
                new_status.owner = request.user
                new_status.save()

    return render_to_response('base/s开发者_高级运维ettings_status.html',{
        'status_form'           :       status_form,
}, context_instance=RequestContext(request))

I have tried numerous things, but I keep running into the problem that if I add owner to the object separately then it isn't available to the model's clean function and therefore can't be used to check if name and owner are unique.


Several ways to do this:

for example, passing in the user (owner) to the form:

forms.py:

class StatusForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user','')
        super(StatusForm, self).__init__(*args, **kwargs)
        self.fields['name'] = forms.CharField(label='Name')
        self.fields['description'] = CharField(label='Description', widget=forms.Textarea)

    def clean(self):
        cleaned_data = self.cleaned_data
        name = cleaned_data.get('name')

        if Status.objects.filter(name=name, owner=self.user).exists():
            self._errors['name'] self.error_class(['Status with this name exists'])  

        return cleaned_data

views.py:

def settings_status(request):

    if request.method == 'POST':
        status_form = StatusForm(request.POST, user=request.user)
            if status_form.is_valid():
                new_status = Status()
                new_status.name = status_form.cleaned_data['name']
                new_status.description = status_form.cleaned_data['description']
                new_status.owner = request.user
                new_status.save()
    else:
        status_form = StatusForm(user=request.user)

    context = {'status_form':status_form,}

    return render_to_response('base/settings_status.html', context,
                context_instance=RequestContext(request))

Also look at setting initial data depending on your form setup and consider using a ModelForm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜