在FORM请求中定义自我kwarg参数

时间:2018-01-11 10:37:55

标签: django django-forms django-views

这是我想要解决的问题。 在我的应用中,我邀请用户加入团队。所以我创建了一个只询问邮件,生成随机密码,创建用户然后向用户发送邮件的表单。 用户通过提供名字姓氏并更新他的密码来转发邮件并完成注册,并最终成为团队的一部分。

我试一试,但我的代码很糟糕:

def ApplicantRegister2(request, pk1=None):
    InviteFormSet = formset_factory(ApplicantForm2)

    if request.method == 'POST':
        formset = InviteFormSet(request.POST)

        if(formset.is_valid()):
            for i in formset:
                mail = i.cleaned_data['Email']
                user = MyUser(email = mail)
                password = MyUser.objects.make_random_password()
                user.set_password(password)
                user.is_active = False
                user.is_candidate = True
                user.save()
                u1 = user.id #get user id
                a1 = MyUser.objects.get(email = request.user.email) #get HRuser email
                a2 = Project.objects.filter(project_hr_admin = a1)  #get all project created by the HRuser
                a3 = a2.latest('id') # extract the last project
                a4 = a3.team_id # extract the team linked to the project
                a4.applicant.add(u1) # add the member to the team

                current_site = get_current_site(request)
                message = render_to_string('acc_active_email.html', {
                    'user':user,
                    'domain':current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                    })
                mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
                to_email = user.email
                email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
            messages.success(request, 'testouille la fripouille')
            return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk1':a3.id}))
        else:
            print("The entered form is not valid")

    else:
        formset = InviteFormSet()
    return render(request,'applicant_register.html', {'formset':formset})

我不喜欢我提取最后创建的项目的事实,所以我在我的网址中添加了相关项目,现在http://127.0.0.1:8000/registration/project/59/auth_team_register3/ 与59 beeign项目ID kwarg。

我想用它而不是a3 = a2.latest('id'),但是提供self.kwargs ['pk1']给我错误或者自我没有定义或者反馈'applicant_register3'并带有关键字参数'{​​'pk1':''}'找不到。

已编辑的代码:

 def applicantregister2(request, pk1):

    InviteFormSet = formset_factory(ApplicantForm2)

    if request.method == 'POST':
        formset = InviteFormSet(request.POST)

        if(formset.is_valid()):

            for i in formset:
                mail = i.cleaned_data['Email']
                if MyUser.objects.filter(email = mail).exists():
                    user = MyUser.objects.get(email=mail)
                    u1 = user.id # get user ID
                    a2 = Project.objects.get(id = 'pk1')
                    a2.applicant.add(u1)

                    invited_user = MyUser.objects.get(email = mail)
                    current_site = get_current_site(request)
                    message = render_to_string('acc_join_email.html', {
                        'user': invited_user.first_name,
                        'domain':current_site.domain,
                        })
                    mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
                    to_email = mail
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
                else:
                    user = MyUser(email = mail)
                    password = MyUser.objects.make_random_password()
                    user.set_password(password)
                    user.is_active = False
                    user.is_candidate = True
                    user.save()
                    u1 = user.id #get user id
                    a2 = Project.objects.get(id = 'pk1')

                    a2.applicant.add(u1)
                    current_site = get_current_site(request)
                    message = render_to_string('acc_active_email.html', {
                    'user':user,
                    'domain':current_site.domain,
                    'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                    'token': account_activation_token.make_token(user),
                    })
                    mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
                    to_email = user.email
                    email = EmailMessage(mail_subject, message, to=[to_email])
                    email.send()
            messages.success(request, 'testouille la fripouille')
            return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs='pk1'))
        else:
            print("The entered form is not valid")

    else:
        formset = InviteFormSet()
    return render(request,'applicant_register.html', {'formset':formset})

HTML代码:

{% extends 'base.html' %}
{% load static %}
{% block body %}
<div class="container paddingtop80 marginbottom30">
  <div class="jumbotron greenback">
      Test
      <a href="{% url 'registration:applicant_register3' pk1=project.id %}" class="btn btn-success" role="button"><span class="glyphicon glyphicon-plus"></span>   Add Applicants</a>
  </div>
</div>


{% endblock %}

视图:

class RecruitmentPage(generic.ListView):
    import pdb; pdb.set_trace()
    template_name = "recruitment_index.html"
    model = Project ## may need to be changed

    def get_object(self, queryset=None):
        return get_object_or_404(Project, id=self.kwargs['pk1'])

1 个答案:

答案 0 :(得分:0)

您有基于功能的视图

Public Function SumByColor(pRange1 As Range, pRange2 As Range) As Double 
    'Update 20140210 
     Application.Volatile 
     Dim rng As Range 
     Dim xTotal As Double 
     xTotal = 0 
     For Each rng In pRange1 
         If rng.Font.Color = pRange2.Font.Color Then 
              xTotal = xTotal + rng.Value 
         End If 
     Next 
     SumByColor = xTotal 
End Function

因此def ApplicantRegister2(request, pk1=None): ... 无法工作。没有self.kwargs['pk1']。只需使用self即可。请注意,您有pk1,因此在使用之前,您可能需要检查它是否为pk1=None。这取决于您的网址。

我强烈建议您将None命名为基于功能的视图。

underscore_case

目前,def applicant_register2(request, pk1=None): 看起来像一个类,这会让任何其他查看代码或Stack Overflow问题的Python开发人员感到困惑。