简体   繁体   English

如何在Django中使用CreateView / UpdateView在表单中使用当前用户填写字段?

[英]How can I fill a field with current user in form using CreateView/UpdateView in Django?

I've been looking for this for few days and I couldn't solve it, so here is my problem: 我一直在寻找这几天,但无法解决,所以这是我的问题:

I'm trying to create a product using just CreateView in views.py for now (My idea is to create forms and pass everything to a function in views.py), but there is one field that I want it to be auto-filled with the logged user ('owner'). 我现在尝试仅使用views.py中的CreateView来创建产品(我的想法是创建表单并将所有内容传递给views.py中的函数),但是有一个字段我希望将其自动填充与登录用户(“所有者”)。 I've tried using the get_initial in the createView for now, but it doesn't work. 我已经尝试过在createView中使用get_initial ,但是它不起作用。

I want to say that this it actually creates a form in which I have to fill all the fields and it works fine, but I want to auto-fill the 'owner' field with the current user logged in. 我想说的是,它实际上创建了一个表单,其中我必须填写所有字段并且工作正常,但是我想用当前登录的用户自动填写“所有者”字段。

For now I tried to use the get_initial as I said before, but seems that it does not work. 现在,我尝试使用我之前说过的get_initial,但似乎不起作用。 I also tried lots of things that I've seen here, in stackoverflow, but any of them worked for me. 我还在stackoverflow中尝试了很多我在这里看到的东西,但是它们中的任何一个对我都起作用。

Here I put all the relevant code, but if you need anything else please, ask for it and I'll upload it. 我在这里放置了所有相关代码,但是如果您需要其他任何内容,请索要它,然后我将其上传。

This is my views.py : 这是我的views.py

# view for the product entry page
class ProductCreate(CreateView):
    model = Product
    fields = ['owner', 'category', 'tag', 'name', 'content_tweet']
    success_url = reverse_lazy('index')

    def get_form(self, form_class=None):
        form = super(ProductCreate, self).get_form(form_class)
        return form

    def get_initial(self):
        return {
             'owner': self.request.user,
        }

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_superuser or request.user.is_vendor:
            raise PermissionDenied()
        return super().dispatch(request, *args, **kwargs)

This is the model I'm using in models.py : 这是我在models.py使用的模型:

class Product(models.Model):
    owner = models.ForeignKey(CustomUser, on_delete=models.PROTECT)
    name = models.CharField(_('Product Name'), max_length=150)
    category = models.ManyToManyField(Category)
    tag = models.ManyToManyField(Tag)
    content_tweet = models.CharField(_('Content Tweet'), max_length=150, blank=True)
    content_abstract = models.CharField(_('Content Abstract'), max_length=3000, blank=True)
    canvas_1 = models.FileField(upload_to='documents/canvas_1/', blank=True)
    price_tweet = models.IntegerField(_('Tweet Price in Tokens'), default=0)
    price_abstract = models.IntegerField(_('Abstract Price in Tokens'), default=50)
    price_canvas_1 = models.IntegerField(_('Canvas 1 Price in Tokens'), default=500)
    it_exist = models.BooleanField(_('is an existing idea?'), default=False)
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this product should be treated as active. '
            'Unselect this instead of deleting products.'
        ),
    )
    history = HistoricalRecords()

    class Meta:
        unique_together = ('name', 'owner')

    def get_categories(self):
        return ",".join([str(p) for p in self.category.all()])

    def get_tags(self):
        return ",".join([str(p) for p in self.tag.all()])

    def __str__(self):
        return self.name

And this is the template I'm using (for now) in my XX.html : 这是我现在(在我的XX.html )使用的模板:

{% for field in form %}
<div class="form-group">
    <div >
        <span class="text-danger la">{{ field.errors }}</span>
    </div>
    <label  >{{ field.label_tag }}</label>
    <div class="col-sm-10">{{ field }}</div>
</div>
{% endfor %}
def form_valid(self, form):
    form.instance.owner = self.request.user
    return super(ProductCreate, self).form_valid(form)

override form_valid method of CreateView as above 覆盖form_validCreateView form_valid方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Django CreateView和UpdateView中呈现Form实例? - How to render Form instance in Django CreateView & UpdateView? 在CreateView上需要表单域的正确Django方法,而在UpdateView上是可选的? - The proper Django way to make a form field required on CreateView, but optional on UpdateView? 如何使用Django UpdateView使用当前用户数据填充表单 - How to populate a form with current user data with Django UpdateView 使用 function 时,如何从 Django UpdateView 中的表单中获取当前字段,例如cleaned_data.get('some_field')? - How can get current field from form in Django UpdateView like cleaned_data.get('some_field') when use a function? 如何在Django中为CreateView和UpdateView创建通用模板 - How To Create Generic Templates for CreateView and UpdateView in Django 如何从 Django CreateView 检索表单数据? - How can I retrieve form data from Django CreateView? 在 django 中,如何在使用 CreateView 时在窗体的 clean 方法中访问请求 object? - In django, how can I access the request object in the form's clean method when using a CreateView? 如何使用 CreateView 在 Django 表单上设置初始值 - How do I set initial values on a Django form using CreateView 限制CreateView中的表单字段不将当前用户显示为模板中的选择 - Restrict form field in CreateView to not show current-user as a choice in template Django在CreateView中禁用/排除字段,但在UpdateView中启用/包含它 - Django Disable/Exclude Field in CreateView but enable/include it in UpdateView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM