开发者

How to edit extend user instance in own form?

开发者 https://www.devze.com 2023-02-23 00:39 出处:网络
I can\'t edit Instructor instance. Adding new instructor works pretty, but When I\'m trying to save the existed instructor instance i have error: \"User with this username already exist!\". This is my

I can't edit Instructor instance. Adding new instructor works pretty, but When I'm trying to save the existed instructor instance i have error: "User with this username already exist!". This is my view code:

@login_required

def instructor_edit(request, userprofile_id):
    user_group = check_user_group(request)
    if request.user.is_authenticated():
        user_to_edit = User.objects.get(userprofile__id=userprofile_id)
        try:
            instructor_to_edit = UserProfile.objects.get(id=userprofile_id)
        except UserProfile.DoesNotExist:
           开发者_JS百科 return Http404
        if request.method == "POST":
            uform = UserForm(request.POST, instance=user_to_edit)
            form = AddInstructorForm(request.POST, request.FILES, instance=instructor_to_edit)
            if request.POST.get('cancel'):
                return HttpResponseRedirect('/')
            if uform.is_valid() and form.is_valid():
                # adding new user
                added_user = uform.save()
                added_user.set_password(request.POST.get('password'))
                grupa = Group.objects.get(name=u'instructor')
                added_user.groups.add(grupa)
                added_user.save()
                # saving instructor to database
                instructor = form.save(commit=False)
                instructor.user = added_user
                instructor.save()
                form.save_m2m()
                warning = "Instructor changed!"
                return render_to_response('archiwum/message.html', {'warning' : warning, 'user_group' : user_group,}, context_instance = RequestContext(request))
            else:
                uform = UserForm(request.POST)
                form = AddInstructorForm(request.POST, request.FILES)
                return render_to_response('archiwum/add_instructor.html', {'user_group':user_group, 'uform':uform, 'form':form,}, context_instance = RequestContext(request))
        else:
            uform = UserForm(instance=user_to_edit)
            form = AddInstructorForm(instance=instructor_to_edit)
        return render_to_response('archiwum/add_instructor.html', {'user_group' : user_group, 'uform':uform, 'form' : form,}, context_instance = RequestContext(request))
    else:
        warning = "You don't have permissions to do it!"
        return render_to_response('archiwum/message.html', {'warning' : warning}, context_instance = RequestContext(request))

EDIT: I put my forms too. Mayby it'll help you!

class UserForm(forms.ModelForm):
    username = forms.RegexField(max_length=30, regex=r'^[\w.@+-]+$', widget = forms.TextInput(attrs={'size': 93,}), error_messages={'required':'Proszę wpisać nazwę użytkownika!', 'invalid':'Nazwa zawiera niedozwolone znaki!'},)
    password = forms.CharField(widget=forms.PasswordInput(attrs={'size': 93,}), error_messages={'required': 'Proszę wpisać hasło!'})
    confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'size': 93,}), error_messages={'required': 'Proszę powtórzyć hasło'},)
    first_name = forms.CharField(widget = forms.TextInput(attrs={'size': 93,}), error_messages={'required': 'Proszę wpisać imię!'})
    last_name = forms.CharField(widget = forms.TextInput(attrs={'size': 93,}), error_messages={'required': 'Proszę wpisać nazwisko!'})
    email = forms.EmailField(widget = forms.TextInput(attrs={'size': 93,}), error_messages={'required': 'Proszę wpisać adres e-mail!', 'invalid':'Adres e-mail jest niepoprawny!'},)
    is_active = forms.BooleanField(required=False, initial=True, help_text="Odznacz to pole zamiast usuwać użytkownika, żeby unieaktywnić konto.")

    class Meta:
        model = User
        fields = ["username", "password", "confirm_password", "first_name", "last_name", "email",]

    def clean_username(self):    
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(_("Użytkownik o tej nazwie już istnieje! Wybierz inną nazwę."))

    def clean_confirm_password(self):
            if self.cleaned_data['password'] != self.cleaned_data['confirm_password']:
                raise forms.ValidationError('Popraw hasło!')
            else:
                if len(self.cleaned_data['password']) < 6 and len(self.cleaned_data['password']) >0:
                    raise forms.ValidationError('Hasło musi się składać przynajmniej z 6 znaków!')


class AddInstructorForm(ModelForm):
    #pesel = PLPESELField
    prefix = forms.CharField(label="Tytuł naukowy", widget = forms.TextInput(attrs={'size': 30,}), required=False)
    birth_date = forms.DateField(label="Data urodzenia", widget=SelectDateWidget(years=range(1930,2011)), required=False, error_messages={'required': 'Proszę podać datę urodzenia!', 'invalid':'Proszę podać poprawną datę!'})    
    adress = forms.CharField(label="Adres (miasto, ulica, kod pocztowy)", widget = forms.TextInput(attrs={'size': 93,}), required=False)
    description = forms.CharField(label="Uwagi", widget=forms.Textarea(attrs={'rows': 5, 'cols': 120,}), required=False)

    class Meta:
        model = UserProfile
        fields = ('second_name', 'prefix', 'instr_subjects', 'birth_date', 'adress', 'phone', 'pesel', 'account', 'photo', 'remove_the_photo', 'description', 'curriculum_vitae', 'remove_the_cv',)


If you're calling is_valid() on an UserForm object it will run clean_username and this will always throw a ValidationError if a User object with the given username already exists / was created before. (This means you cannot do something like 'editing' an existing user with it)

0

精彩评论

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

关注公众号