没有立即将用户保存到数据库

时间:2019-02-16 15:54:19

标签: python django

我遇到一个问题,在用户注册后,他们被重定向到具有@login_required的仪表板视图;但是,由于用户由于某种原因(而不是立即)在30秒后被保存到我的数据库中,因此他们无法访问它。我想知道如何注册用户并立即保存他们,以便他们通过@login_required字段并可以正确地重定向到仪表板。

注册视图

def teacher_sign_up(request):
    form = TeacherSignUpForm(request.POST)

    if request.method == 'POST':
        form = TeacherSignUpForm(request.POST, request.FILES)

        if form.is_valid():
            user = form.save()
            return redirect('/teacher/dashboard')

        else:
            messages.error(request, 'Make sure all your information is valid')

    else:
        form = TeacherSignUpForm()


    context = {'form' : form}
    return render(request, 'accounts/teacher_sign_up.html', context)

仪表板视图

@login_required
def dashboard(request):
    return render(request, 'teacher/dashboard.html')

forms.py

    class RegisterForm(forms.ModelForm):
        email = forms.EmailField(widget=forms.EmailInput(attrs={'class' : 'form-control', 'placeholder' : 'Email', 'id' : 'email', 'required' : 'True'}))
        first_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'First name', 'id' : 'first-name', 'required' : 'True'}))
        last_name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'form-control', 'placeholder' : 'Last name', 'id' : 'last-name', 'required' : 'True'}))
        password = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'placeholder' : 'Password', 'id' : 'password', 'required' : 'True'}))
        password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class' : 'form-control', 'placeholder' : 'Confirm password', 'id' : 'password2', 'required' : 'True'}))
        class Meta:
            model = User
            # what fields from that model you want
            fields = ('first_name', 'last_name', 'email', 'password', 'password2')

        def clean_email(self):
            email = self.cleaned_data.get('email')
            qs = User.objects.filter(email=email)
            if qs.exists():
                raise forms.ValidationError("Email is taken")
            return email

        def clean_password2(self):
            # Check that the two password entries match
            password = self.cleaned_data.get("password")
            password2 = self.cleaned_data.get("password2")
            if password and password2 and password != password2:
                raise forms.ValidationError("Passwords don't match")
            return password2

        def save(self, commit=True):
            # Save the provided password in hashed format
            user = super(RegisterForm, self).save(commit=False)
            user.first_name = self.cleaned_data["first_name"]
            user.last_name = self.cleaned_data["last_name"]
            user.set_password(self.cleaned_data["password"])
            #user.active = False send confirmation email
            if commit:
                user.save()
            return user

class TeacherSignUpForm(RegisterForm):
    avatar = forms.ImageField()
    country = CountryField().formfield(widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'true'}))
    instrument1 = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control'}))
    instrument2 = forms.ChoiceField(choices=instrument_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    instrument3 = forms.ChoiceField(choices=instrument_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    instrument4 = forms.ChoiceField(choices=instrument_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    instrument5 = forms.ChoiceField(choices=instrument_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    level1 = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control'}))
    level2 = forms.ChoiceField(choices=level_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    level3 = forms.ChoiceField(choices=level_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    level4 = forms.ChoiceField(choices=level_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    level5 = forms.ChoiceField(choices=level_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    language1 = forms.ChoiceField(choices=language_list, widget=forms.Select(attrs={'class' : 'form-control'}))
    language2 = forms.ChoiceField(choices=language_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    language3 = forms.ChoiceField(choices=language_list, required=False, widget=forms.Select(attrs={'class' : 'form-control'}))
    resume = forms.FileField()

    def save(self, commit=True):
        user = super(TeacherSignUpForm, self).save(commit=False)
        user.avatar = self.cleaned_data['avatar']
        user.instrument1 = self.cleaned_data['instrument1']
        user.instrument2 = self.cleaned_data['instrument2']
        user.instrument3 = self.cleaned_data['instrument3']
        user.instrument4 = self.cleaned_data['instrument4']
        user.instrument5 = self.cleaned_data['instrument5']
        user.level1 = self.cleaned_data['level1']
        user.level2 = self.cleaned_data['level2']
        user.level3 = self.cleaned_data['level3']
        user.level4 = self.cleaned_data['level4']
        user.level5 = self.cleaned_data['level5']
        user.language1 = self.cleaned_data['language2']
        user.language2 = self.cleaned_data['language2']
        user.language3 = self.cleaned_data['language3']
        user.resume = self.cleaned_data['resume']

        user.teacher = True
        if commit:
            user.save()
        return user

2 个答案:

答案 0 :(得分:0)

在不知道您确切的数据库设置的情况下,我怀疑重定向无法正常工作,因为新用户尚未登录,因此@login_required装饰器将用户重定向到登录页面。

要注册用户,请立即保存他们并重定向到信息中心,您需要先login新用户:

if form.is_valid():
    user = form.save()
    login(request, user)
    return redirect('/teacher/dashboard')

答案 1 :(得分:0)

我想通过适当的身份验证为Passuf答案添加更多内容

// add the geojson to the map
const geoJson = L.geoJson(freeBus).addTo(map);

// use external library to save geojson
const saveTxt = (content, filename) => {
  const file = filename + ".json";
  saveAs(new File([JSON.stringify(content)], file, {
      type: "text/plain;charset=utf-8"
    }), file);
};

// invoke the function by passing geojson to be saved
// and .txt file name
saveTxt(geoJson.toGeoJSON(), "test");

您可以从获得身份验证并登录

user = form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/teacher/dashboard')

如果您的数据库没有刷新,您也可以使用

from django.contrib.auth import authenticate,login