在保存以将该模型与当前用户相关联之前,在 Python 中将当前用户的 id 传递给另一个模型

Posted

技术标签:

【中文标题】在保存以将该模型与当前用户相关联之前,在 Python 中将当前用户的 id 传递给另一个模型【英文标题】:Pass current user's id to another model before saving to associate that model with current user, in Python 【发布时间】:2015-09-15 21:50:00 【问题描述】:

我正在尝试将当前用户或登录用户 ID 传递给车辆模型中的 vehicle_user 字段。我创建了一个自定义用户,并且需要在添加车辆之前将车辆与当前用户关联。

车辆/forms.py

class VehicleCreationForm(forms.Form):

    WHEELER_TYPE = (
        ('T','Two Wheeler'),
        ('F','Four Wheeler')
    )
    Wheeler_Type = forms.ChoiceField(choices=WHEELER_TYPE)
    Company = forms.CharField(max_length=30)
    Model = forms.CharField(max_length=30)
    reg_id=forms.CharField(max_length=15)
    Color=forms.CharField(max_length=15)
    vehicle_user = CustomUser()
    v = vehicle_user.current_user()

    def save(self, commit=True):
        data = self.cleaned_data
        users = Vehicle( vehicle_type=data['Wheeler_Type'],company=data['Company'],
        model=data['Model'],Reg_id=data['reg_id'].upper(),color=data['Color'], vehicle_user='v')
        users.save()        

vehicles/models.py

class Vehicle(models.Model): 

    u_id = models.AutoField(primary_key=True, null=False) 

    WHEELER_TYPE = (
        ('T','Two Wheeler'),
        ('F','Four Wheeler')
    )


    vehicle_type = models.CharField(max_length=1, choices=WHEELER_TYPE)
    company = models.CharField(max_length=30)
    model = models.CharField(max_length=30)
    Reg_id = models.CharField(max_length=12, unique=True)
    color = models.CharField(max_length=30)

    vehicle_user=models.ForeignKey(CustomUser)

    def __unicode__(self):
        return self.Reg_id

车辆/views.py

def create_vehicle(request):
    if request.method == 'POST':
        form = VehicleCreationForm(request.POST, request.FILES)
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.id = request.id
            save_it.save()
            return HttpResponse("Vehicle Added")
    else:
        form = VehicleCreationForm()
        variables = RequestContext(request, 
        'form': form
        )
    return render_to_response(
    'create_vehicle.html',
    variables,
    )

自定义用户模型如下: customuser/models.py

class CustomUser(AbstractBaseUser, PermissionsMixin):
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message = 'Only alphanumeric numbers are allowed.')

    """
    A fully featured customuser model
    Email and Password are required.

    """

    username = models.CharField(unique=True, max_length=20, validators=[alphanumeric])
    email = models.EmailField(verbose_name='email address', unique='True', max_length=255)
    first_name = models.CharField(max_length=30, null=True)
    last_name = models.CharField(max_length=50, null=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True, null=False)
    is_staff = models.BooleanField(default=False, null=False)

    ###Our Own Models
    mobile_no = models.CharField(max_length=10, unique=True)
    state = models.CharField(max_length=30)
    city = models.CharField(max_length=30)


    objects = AuthUserManager()
    USERNAME_FIELD = 'mobile_no'
    REQUIRED_FIELDS = ['username', 'email']


    def current_user(request):
        current_user = request.id
        return current_user

    def get_full_name(self):
        fullname = self.first_name+" "+self.last_name
        return fullname

    def get_short_name(self):
        return self.username

    def __unicode__(self):
        return self.email

customuser/view.py

def login_user(request):
    state="Log in here"
    mobile_no=password=''

    if request.POST:
        #request.session.set_test_cookie()
        mobile_no = request.POST.get('mobile_no')
        password = request.POST.get('password')
        user = authenticate(mobile_no=mobile_no, password=password)

    if user is not None:
        if user.is_active:
            login(request, user)
            #form = VehicleCreationForm(request.POST)
            #uv_id = CustomUser.objects.filter(mobile_no=mobile_no)
            return HttpResponseRedirect('/user/%s/' % mobile_no)

            '''return render_to_response(
            'home.html',
             'user': request.user 
            )'''

        else:
            state="Your account is not active, please contact the site"
    else:
        state = "Your mobile no and/or password were incorrect."

    return render_to_response('login.html','state':state, 'mobile_no': mobile_no,context_instance=RequestContext(request))

【问题讨论】:

我不完全理解你想要做什么,但你有什么问题?它不工作?有什么错误吗? 我无法将当前用户 ID 传递给我在车辆模型中的外键。 但是用户认证是有效的,对吗? 【参考方案1】:

截图后编辑:

你想在这里做什么?您是否尝试将 request.user 提供给表单?

如果是这样,您可能没有告诉 Django 您的基本 auth_user 模型重载。您是否将 AUTH_USER_MODEL 设置设置为您的自定义用户模型?

在视图中生成表单时,按原样创建提供初始用户实例的表单。

form = VehicleCreationForm(initial='vehicle_user': CustomUser()'''any CustomUser instance eg. request.user''')

顺便说一句,我不太明白在创建对象属性之前如何设置它。

编辑:

如果你想将 ForeignKey 设置为vehicle_user,那么给它这样的:

form = VehicleCreationForm(initial='vehicle_user': request.user.id)

【讨论】:

我想将vehicle_user(customuser的外键)的值设置为当前用户的id。是的,AUTH_USER_MODEL设置为我的自定义模型

以上是关于在保存以将该模型与当前用户相关联之前,在 Python 中将当前用户的 id 传递给另一个模型的主要内容,如果未能解决你的问题,请参考以下文章

Rails - 如何让两个用户 ID 与模型相关联

与单独形式的多态关联

Cakephp 3 保存关联属于ToMany

正确的 Android 意图过滤器配置以将文件类型与 Activity 关联?

将用户与 Rails 中的嵌套模型相关联

如何将用户登录与表单中的模型相关联?