SHARE
TWEET

Untitled

a guest Sep 3rd, 2018 190 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Django formset set current user
  2. class NewStudentForm (forms.Form):
  3.     username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^w+$',
  4.         help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
  5.         error_message = _("This value must contain only letters, numbers and underscores."))
  6.     first_name = forms.CharField(label=_('first name'), max_length=30 )
  7.     last_name = forms.CharField(label=_('last name'), max_length=30, )
  8.     email = forms.EmailField(label=_('e-mail address') )
  9.     password = forms.CharField(label=_('password'), max_length=64, )
  10.  
  11.     class Meta:
  12.         model = User
  13.         fields = ("username","first_name", "last_name", "email", "password")
  14.  
  15.     def __init__(self, *args, **kwargs):
  16.         self._user = kwargs.pop('user')
  17.         super(NewStudentForm, self).__init__(*args, **kwargs)
  18.  
  19.  
  20.     def save(self, commit=True):
  21.         user = super(NewStudentForm, self).save(commit=False)
  22.         user.set_password(self.cleaned_data["password"])
  23.         if commit:
  24.             user.save()
  25.             profile = Profile.objects.create_profile(user)
  26.             profile.activiation_key = profile.ACTIVATED_KEY
  27.             profile.authorized = True
  28.             profile.save()
  29.             user.is_active=True
  30.             user.save()
  31.             student = models.Student()
  32.             student.user = user
  33.             student.teacher = self._user
  34.             student.plaintext_pwd = self.cleaned_data["password"]
  35.             student.save()
  36.         return UserWarning
  37.    
  38. @login_required
  39. def new_student(request):
  40.     from django.forms.formsets import formset_factory
  41.     try:
  42.         if request.method == 'GET':
  43.             newStudentFormset = formset_factory(forms.NewStudentForm, extra=2)
  44.             formset = newStudentFormset()
  45.             return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username })
  46.         elif request.method == 'POST':
  47.             if LOGIN_FORM_KEY in request.POST:
  48.                 return _handle_login(request)
  49.             data = request.POST.copy()
  50.             newStudentFormset = formset_factory(forms.NewStudentForm)
  51.             formset = newStudentFormset(data) ### Pass current user to formset? ###
  52.             if formset.is_valid():
  53.                 formset.save()
  54.                 request.user.message_set.create(message="Save successful.")
  55.                 return shortcuts.redirect(student)
  56.             else:
  57.                 return shortcuts.render_to_response('NewStudent.html', { 'newStudentFormSet':formset, 'active_username': request.user.username, 'error_message':formset.errors})
  58.         return http.HttpResponseNotAllowed(['GET', 'POST'])
  59.     except models.Student.DoesNotExist:
  60.         return http.HttpResponseNotFound('<h1>Requested Student not found</h1>')
  61.    
  62. class NewStudentFormSet(BaseFormSet):
  63.     def __init__(self, *args, **kwargs):
  64.         self. user = kwargs.pop('user', None)
  65.         super(NewStudentFormSet, self).__init__(*args, **kwargs)
  66.  
  67.     def _construct_forms(self):
  68.         self.forms = []
  69.         for i in xrange(self.total_form_count()):
  70.             self.forms.append(self._construct_form(i, user=self.user))
  71.    
  72. ...
  73.             data = request.POST.copy()
  74.             newStudentFormset = formset_factory(forms.NewStudentForm, formset=forms.NewStudentFormSet)
  75.             formset = newStudentFormset(data, user=request.user)
  76. ...
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top