发布Django,在数据库中插入会话登录用户数据



实际上,我想在数据库中插入会话登录用户数据,但我当我把这个代码,我得到所有注册用户在下拉列表中,但我想只有当前登录用户数据不是全部,我也想隐藏这个字段值。请帮助。

model.py

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User     

class Product(models.Model):
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True,max_length=200)
    category = models.ManyToManyField(Category, null=True, blank=True)
    price = models.DecimalField(decimal_places=2, max_digits=100, default=29.99)
    sale_price = models.DecimalField(decimal_places=2, max_digits=100,
                                            null=True, blank=True)
    slug = models.SlugField(unique=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    active = models.BooleanField(default=True)
    update_defaults = models.BooleanField(default=False)
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.title
    class Meta:
        unique_together = ('title', 'slug')
    def get_price(self):
        return self.price
    def get_absolute_url(self):
        return reverse("single_product", kwargs={"slug": self.slug})

view.py

class DealsForm(ModelForm):
    class Meta:
        model = Product
        fields = ['title','description','category','price','sale_price','slug','active','update_defaults','user']

最后一个字段用户,我想插入当前会话登录用户数据…如何…?

您可以将其排除在ModelForm

,

class DealsForm(ModelForm):
    class Meta:
        model = Product
        ...
        exclude = ('user',)

然后重写表单保存方法,

class DealsForm(ModelForm):
    class Meta:
         model = Product
         exclude = ('user',)
    def save(self, request, *args, **kwargs):
         obj = super(DealsForm, self).save(commit=False, *args, **kwargs)
         obj.user = request.user #store here users data 
         obj.save()

如果您排除ModelForm中的任何字段,则该字段将不会在模板上呈现

最新更新