试图让用户选择生日 - django

时间:2017-08-26 00:33:57

标签: django django-models django-forms

我在Django项目中有一个表单,我希望用户输入他的生日,这样我就可以保存在数据库中并在以后的项目中使用...

我有一个模型,我想创建一个Modelform,它会询问日期然后格式化它并将其保存在数据库中。我一直试图解决这个问题3天,并且无法让它工作......我不得不删除我的数据库文件大约5次,因为它无法正常工作并弄乱了数据库......

当用户提交表单时,返回的是三个单独的项目,包括带正确日期信息的dob_month,dob_day,dob_year

这是我到目前为止所拥有的。

models.py文件

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)  # server
    first_name = models.CharField(max_length=25, default='first')
    last_name = models.CharField(max_length=25, default='last')
    dob = models.DateField(auto_now_add=False, blank=True)
    city = models.CharField(max_length=45)  # user
    state = models.CharField(max_length=25, default='state')
    phone = models.BigIntegerField(default=0)  # user
    privacy = models.SmallIntegerField(default=1)  # user
    created = models.DateTimeField(auto_now_add=True)  # server

这是forms.py文件:

class ProfileForm(forms.ModelForm):
    split_choices = (('1', 'public'),
                     ('2', 'private'))
    privacy = forms.TypedChoiceField(
        choices=split_choices, widget=forms.RadioSelect, coerce=int
    )
    dob = forms.DateField(widget=extras.SelectDateWidget)
    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'dob', 'city', 'state', 'phone', 'privacy']

这里是view.py文件(处理表单的特定def ...)

def profile_setup(request):
    if 'username' not in request.session:
        return redirect('login')
    else:
        # the following is just going to grab the currently logged in user and
        # save the profile information to the appropriate user
        username = request.session['username']
        currentUser = User.objects.get(username = username)
        # the following is the provessing for the form where the user entered
        # the profile informaiton
        if request.method == 'POST':
            form = ProfileForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                first_name = cd['first_name']
                last_name = cd['last_name']
                dob_month = form.cleaned_data.get("dob_month")
                dob_day = form.cleaned_data.get("dob_day")
                dob_year = form.cleaned_data.get("dob_year")
                city = cd['city']
                state = cd['state']
                phone = cd['phone']
                privacy = cd['privacy']
                # this is the new record that is going to be created and saved
                new_profile = Profile.objects.create(
                    user = currentUser,
                    first_name = first_name,
                    last_name = last_name,
                    dob_month = dob_month,
                    dob_day = dob_day,
                    dob_year = dob_year,
                    city = city,
                    state = state,
                    phone = phone,
                    privacy = privacy,
                )
                return redirect('home_page')
        else:
            # this is what is going to be saved into the html file and used to
            # render the file
            form = ProfileForm()
            message = 'fill out form below'
            parameters = {
                'form':form,
                'currentUser':currentUser,
                'message':message,
            }
            return render(request, 'tabs/profile_setup.html', parameters)

**更新部分**

所以我想说我有一个如下模型:

class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250, null=True)
    count = models.SmallIntegerField(default=1)
    status = models.SmallIntegerField(choices=GROUP_STATUS_CHOICES, default=1)
    reference_code = models.IntegerField(default=0)

andi的模型形式如下:

class CreateGroupForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name', 'count', 'description']

并且用户提交以下表单:

name : omar jandali
count : 5
description : random group

然后我可以按以下方式处理表单:

form = CreateGroupForm(request.POST, instance=new_group)
new_group = Group(
    name = name,
    description = desciption,
    count = count,
    status = status,
)

或者我仍然需要分配清理过的数据......

1 个答案:

答案 0 :(得分:1)

您不需要做太多工作来处理表单。使用Django Model表单,大部分工作都是为您完成的。如果要创建新记录,请确保将instance添加到表单标记中,如下所示:

form = ProfileForm(request.POST, instance= new_profile)

然后在method.request之前添加:

new_profile = Profile(
    user = ...
    created = ...
    )

其中“...”是您希望与该表单实例关联的值。

摆脱new_profile = Profile.objects.create(...

基本上,您需要设置特定实例中用户未提供的值,然后在实例化表单时调用它们。