使用表单将 request.user.id 分配给模型中的 OneToOneField

Assign request.user.id to OneToOneField in Model using form

我正在为用户使用 django 身份验证。每个用户都可以创建一行 - 基于客户端模型。但我有问题,因为我无法在 form.is_valid 中分配字段 ID request.user.id.

因为 id 是必需的,所以我在表单 class Meta.

中排除了这个字段

请给我一些建议如何将 user.id 分配给我的 OneToOneField 字段。

我正在使用 PyCharm 并且当我输入表格时。我在我的模型中没有看到任何字段,所以我认为我在我的代码中犯了一些错误:(

型号:

class Client(models.Model):
    id = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, primary_key=True)
    name = models.CharField(max_length=256, unique=True)
    vat = models.CharField(max_length=12, unique=True)
    address = models.CharField(max_length=64)
    zip_code = models.CharField(max_length=10, help_text='Zip Code')
    city = models.CharField(max_length=64)
    country = models.CharField(max_length=6, default='US')
    forwarding_address = models.CharField(max_length=64, blank=True)
    forwarding_zip_code = models.CharField(max_length=10, blank=True)
    forwarding_city = models.CharField(max_length=64, blank=True)
    forwarding_country = models.CharField(max_length=6, blank=True)
    phone = models.CharField(max_length=20)

    def __str__(self):
        re = self.name + ' [' + str(self.id) + ']'
        return re

形式:

class ClientProfileForm(forms.ModelForm):
    class Meta:
        model = Client
        exclude = ['id']

查看:

def profile_create(request):
    if request.method == 'POST':
        form = ClientProfileForm(request.POST)
        if form.is_valid():
            form.save(commit=False)
            form.id = request.user.id
            form.save()
            return HttpResponseRedirect('/client/profile/')
        dict = {}
        dict['form'] = form
        return render(request, 'client/profile_edit.html', dict)
    else:
        if Client.objects.filter(id=request.user.id).exists():
            return HttpResponseRedirect('/client/profile/edit/')
        else:
            dict = {}
            dict['form'] = ClientProfileForm()
            return render(request, 'client/profile_edit.html', dict)

模板:

{% extends 'registration/base.html' %}
{% block title %} Client profile {% endblock %}

{% block content %}
    {{ form.non_field_errors }}
    <form role="form" action="" method="post">{% csrf_token %}

        {{ form.name.errors }}
        <div class="form-group login-input">
            <i class="fa fa-envelope overlay"></i>
            <input type="text" class="form-control text-input"
                   {% if form.name.value != nulls %} value="{{ form.name.value }}" {% endif %}
                   id="{{ form.name.name }}" name="{{ form.name.name }}">
        </div>

        {{ form.vat.errors }}
        <div class="form-group login-input">
            <i class="fa fa-envelope overlay"></i>
            <input type="text" class="form-control text-input"
                   {% if form.vat.value != nulls %} value="{{ form.vat.value }}" {% endif %}
                   id="{{ form.vat.name }}" name="{{ form.vat.name }}">
        </div>

        {{ form.address.errors }}
        <div class="form-group login-input">
            <i class="fa fa-envelope overlay"></i>
            <input type="text" class="form-control text-input"
                   {% if form.address.value != nulls %} value="{{ form.address.value }}" {% endif %}
                   id="{{ form.address.name }}" name="{{ form.address.name }}">
        </div>

        (....)

        <div class="row">
            <div class="col-sm-12">
                <button type="submit" class="btn btn-default btn-block">Create</button>
            </div>
        </div>
    </form>
{% endblock %}

干杯!

这不是正确的模式。应该是:

    if form.is_valid():
        obj = form.save(commit=False)
        obj.id = request.user.id
        obj.save()