简体   繁体   English

在同一视图中的2个模型(窗体)之间创建OneToOne关系

[英]Creating a OneToOne Relationship between 2 models(forms) in the same view

I am building a signup page. 我正在建立一个注册页面。 I am using the default User model and a new model called UserInfo for additional user details. 我正在使用默认的用户模型和名为UserInfo的新模型以获取其他用户详细信息。 I need to establish a OneToOne relationship between the 2 models. 我需要在两个模型之间建立一个OneToOne关系。 To build the signup page, I made a form for each model and put them into the same signup view. 为了构建注册页面,我为每个模型制作了一个表单,并将它们放入相同的注册视图中。

My question is, how to I set user(the OneToOneField) in UserInfo to the User that is being created in the same view UserInfo is created? 我的问题是,如何在UserInfo的同一视图中将UserInfo中的user(OneToOneField)设置为正在创建的User? If you look in my views.py below, immediately after I saved User's form(signup_form), I tried a few things like.. 如果您在下面的views.py中查看,则在保存用户的表单(signup_form)之后,我立即尝试了类似的操作。

  • user2.user = User.objects.get(pk=pk) - doesn't seem to work user2.user = User.objects.get(pk = pk)-似乎不起作用
  • user2.user = request.user - doesn't work because request.user is an anonymous user in this case user2.user = request.user-不起作用,因为在这种情况下request.user是匿名用户
  • user2.user = user - didn't work user2.user =用户-无效

models.py: models.py:

class UserInfo(models.Model):

    TITLE = (
        ('Salesperson', 'Salesperson'),
        ('Sales Representative', 'Sales Representative'),
        ('Broker', 'Broker'),
        ('Broker of Record', 'Broker of Record'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    preferred_email = models.EmailField()
    office_phone_number = models.CharField(max_length=10)
    brokerage_of_agent = models.CharField(max_length=50)
    agent_title = models.CharField(max_length=20, choices=TITLE)

    def __str__(self):
        return self.preferred_email

forms.py: forms.py:

class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

class UserInfoForm(forms.ModelForm):

    class Meta:
        model = UserInfo
        fields = ['preferred_email', 'office_phone_number', 'brokerage_of_agent', 'agent_title']

views.py: views.py:

def signup(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect('../dashboard/')
    if request.method == 'POST':
        signup_form = SignupForm(request.POST)
        basic_info_form = UserInfoForm(request.POST)
        while (True):  # The while loop is used to get access to 'break' for the @gmail Email check
            if signup_form.is_valid():
                if not signup_form.cleaned_data['email'].endswith('@gmail.com'):
                    print('You must register with your @gmail.com Email')
                    break
                user = signup_form.save(commit=False)
                user.is_active = False
                user.save()

                ### Look here!  I need to write something here I think, but I'm not sure what to write
                user2 = basic_info_form.save(commit=False)
                user2.user = User.objects.get(pk=pk) 
                user2 = user2.save()

                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 = 'Activate your blog account.'
                to_email = signup_form.cleaned_data.get('email')
                email = EmailMessage(mail_subject, message, to=[to_email])
                email.send()
                return HttpResponse('Please confirm your email address to complete the registration')
    else:
        signup_form = SignupForm()
        basic_info_form = UserInfoForm()

    return render(request, 'signup.html', {'signup_form': signup_form, 'basic_info_form': basic_info_form})

HTML Template: HTML模板:

{% extends "base.html" %}
{% load static %}

{% block content %}
<h2>Sign up</h2>
<form method="post">
    {% csrf_token %}
    {% for field in signup_form %}
    <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
        <small style="display: none">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
    <p style="color: red">{{ error }}</p>
        {% endfor %}
    {% endfor %}

    {% for field in basic_info_form %}
    <p>
        {{ field.label_tag }}<br>
        {{ field }}
        {% if field.help_text %}
        <small style="display: none">{{ field.help_text }}</small>
        {% endif %}
        {% for error in field.errors %}
    <p style="color: red">{{ error }}</p>
        {% endfor %}
    {% endfor %}


    <button type="submit">Sign up</button>
</form>
{% endblock %}

user2.user = user实际上是正确的答案,但是由于笨拙的while循环使它搞砸了,所以我认为它不起作用。

暂无
暂无

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

相关问题 在两个用户模型之间创建关系 - Creating A Relationship Between Two User Models 如何在Django中不同模型的任何两个字段之间建立OneToOne关系? - How do i have OneToOne relationship between any two fields of different models in Django? 在Django中使用Foreignkey和OnetoOne关系构建模型? - building models with foreignkey and OnetoOne relationship in Django? 我在Django应用程序中的同一个类的两个对象之间有一个OneToOne关系。 是否有可能强制实现这种关系的独特性? - I have a OneToOne relationship between two objects of the same class in a Django app. Is it possible to enforce the uniqueness of this relationship? Django-对同一视图使用多种模型和形式 - Django - Use multiple models and forms for the same view 使用OnetoOne关系为Django模型创建工厂 - Creating factories for Django models with OnetoOne relationships 在Django中,对于同一类的两个对象之间的OneToOne关系,是否可以防止某个对象在数据库级别引用其自身? - In Django, for a OneToOne relationship between two objects of the same class, can an object be prevented from referring to itself at the db level? 在单独的文件中创建模型之间的关系 FLASK、SQLalchemy - Creating relationship between models when in separate files FLASK, SQLalchemy Django中的OneToMany和OneToOne关系之间的冲突 - conflict between OneToMany and OneToOne relationship in Django Django中2个型号的关系 - Relationship between 2 models in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM