实际上我想在数据库中插入会话登录用户数据,但是当我把这个代码放到Dropdown中我得到所有注册用户但我想只有当前登录用户数据而且我想要隐藏这个字段值。请帮助
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']
我想要插入当前会话登录用户数据的最后一个字段用户..how ..?
答案 0 :(得分:0)
您可以将其从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
中的任何字段,则此字段不会在模板上呈现。