简体   繁体   English

Django-将表单中的数据保存到数据库中

[英]Django - saving data from form in database

I have just finished a Django tutorial for an email sign up form and I am trying to tweak some parts of the code to match my needs (adding an additional field to the sign up form) 我刚刚完成了有关电子邮件注册表单的Django教程,并且尝试调整代码的某些部分以满足我的需求(在注册表单中添加了其他字段)

Based on the tutorial I created an email signup Model form: 根据本教程,我创建了电子邮件注册模型表单:

class JoinForm(forms.ModelForm):
    class Meta:
        model = Join
        fields = ["email","wunschrad"]

and I altered it a little bit by adding the wunschrad field 我通过添加wunschrad字段对其进行了一些更改

then I updated my model to include wunschrad and synced the database with south, all working out fine. 然后我更新了我的模型以包括wunschrad ,并将数据库与south同步,所有工作都很好。 below my model: 在我的模型下面:

class Join(models.Model):
    email = models.EmailField()
    wunschrad = models.CharField(max_length=120)
    friend = models.ForeignKey("self", related_name='referral', null=True, blank=True)
    ref_id = models.CharField(max_length=120, default='ABC', unique=True)
    ip_address = models.CharField(max_length=120, default='ABC')
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

    def __unicode__(self):
        return "%s" % (self.email)

    class Meta:
        unique_together = ("email", "ref_id",)

Where I ran into problems is how do I adopt my view to reflect this change. 我遇到问题的地方是如何采纳我的观点来反映这种变化。 Here is what I did (my changes highlighted in comments) 这是我所做的(我的更改在注释中突出显示)

def home(request):
    try:
        join_id = request.session['join_id_ref']
        obj = Join.objects.get(id=join_id)
    except:
        obj = None

    form = JoinForm(request.POST or None)
    if form.is_valid():
        new_join = form.save(commit=False)
        email = form.cleaned_data['email']
        wunschrad = form.cleaned_data['wunschrad'] #I ADDED THIS
        new_join_old, created = Join.objects.get_or_create(email=email, wunschrad=wunschrad) # I ADDED WUNSCHRAD HERE
        if created:
            new_join_old.ref_id = get_ref_id()
            if not obj == None:
                new_join_old.friend = obj
            new_join_old.ip_address = get_ip(request)
            new_join_old.save()

        return HttpResponseRedirect("/%s" %(new_join_old.ref_id))


    context = {"form": form}
    template = "home.html"
    return render(request, template, context)

My question/ problem is the following: This code snippet works but if a user signs up with the same email address and chooses once the first option of wunschrad and the second time the second option (for clarification: wunschrad is a drop-down list with two options) Django saves two versions in the database, like shown here: Django Admin Screenshot 我的问题/问题如下:该代码段有效,但是如果用户使用相同的电子邮件地址注册并且一次选择了wunschrad的第一个选项,而第二次选择了第二个选项(为澄清:wunschrad是一个具有以下内容的下拉列表)两个选项),Django在数据库中保存了两个版本,如下所示: Django Admin屏幕截图

Does anyone have an idea how to alter the code to save it only once per user? 有谁知道如何更改代码以将每个用户仅保存一次?

many many thanks in advance for the help! 非常感谢您的帮助!

So your problem here is by adding wunschrad to get_or_create you are telling Django to look for an entry in the database that has both of those values instead of just the email. 因此,这里的问题是,将wunschrad添加到get_or_create中,这是在告诉Django在数据库中查找包含这两个值而不只是电子邮件的条目。 Changing it to this should fix it: 将其更改为此应解决:

new_join_old, created = Join.objects.get_or_create(email=email)
new_join_old.wunschrad = wunschrad
new_join_old.save()

This will make sure it only creates a new object if the email isn't in the database already. 这将确保仅在电子邮件不在数据库中时才创建新对象。

As a side note if you want your email to be unique and raise an error if you try to save another entry with the same email add unique=True to models.EmailField() like: 附带说明一下,如果您希望您的电子邮件具有唯一性,并且如果您尝试使用相同的电子邮件保存另一个条目,则会引发错误,请在模型中添加unique = True。

models.EmailField(unique=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM