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

时间:2015-06-29 12:20:29

标签: python mysql django foreign-key-relationship

我正在尝试将当前用户或登录用户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()        

辆/ 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))

1 个答案:

答案 0 :(得分:1)

enter image description here

屏幕截图后修改

你想在这做什么?您是否尝试将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})