2011-04-09 30 views
1

我無法編輯教師實例。添加新的教練工作很好,但是當我試圖保存現有的教練實例我有錯誤:「用戶使用此用戶名已存在!」。這是我的看法代碼:如何在自己的表單中編輯擴展用戶實例?

@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: 
      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)) 

編輯:我也把我的形式。梅比它會幫助你!

class UserForm(forms.ModelForm): 
    username = forms.RegexField(max_length=30, regex=r'^[\[email protected]+-]+$', 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',) 
+0

你還應該包括代碼在這裏,因爲很可能他們是爲這個'ValidationError'的原因。 – 2011-04-09 17:48:46

回答

2

如果你是一個UserForm對象上調用is_valid()它將運行clean_username,這將始終拋出,如果ValidationError一個User對象與給定username已經存在/是之前創建的。 (這意味着你不能這樣做「編輯」與它現有用戶)爲您的表單類