Django:如何在通用创建 View 上设置隐藏字段?

标签 django django-generic-views

我正在运行 Django 1.6.x

为了扩展我的用户,我添加了另一个存储数据的模型:

class UserProfile (models.Model):
    user = models.ForeignKey(User)
    height = models.IntegerField(blank=True, null=True)

现在我想添加一个 View ,它允许用户在那里添加自己的信息。开始于 django.views.generic.edit.CreateView ,但还想至少提供一个编辑/更新。

所以我添加了导入并创建了一个 View :
from django.views.generic.edit import CreateView, UpdateView
# .... 
class UserProfileCreateView(CreateView):
    model = UserProfile
    fields = ['height']

我还在 urls.py 中添加了条目:
    url(r'^userprofile/new/$', login_required(UserProfileCreateView.as_view()), name="add_userprofile")

但是现在我被困在如何以正确的方式分配用户 ID 的问题上。我想在后台设置这个字段。任何提示?

最佳答案

你可以这样做:

  • 从请求对象中获取用户。
  • 覆盖 UserProfileCreateView 类上的 form_valid 方法,
  • 将用户附加到表单实例并保存。
  • class UserProfileCreateView(CreateView):
        model = UserProfile
        fields = ['height']
    
         def form_valid(self, form):
             user = self.request.user
             form.instance.user = user
             return super(UserProfileCreateView, self).form_valid(form)
    

    此代码适用于 Python 2.7.x

    关于Django:如何在通用创建 View 上设置隐藏字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21652073/

    相关文章:

    python - 将旧的基于函数的通用 CRUD View 转换为新样式的基于类的通用 CRUD View

    python - 如何使用 django.views.generic.date_based.archive_index 获取前五个对象?

    python - 添加重定向到 CreateAPIView

    python - 使用 Django,如何将模型的 ForeignKey 添加到 CreateView?

    python - 如何使用 WMS 层在 django-leaflet-admin 中设置传单配置

    Django,让url参数进入 View

    python - Django Haystack-Xapian 搜索因特殊字符和空格而失败

    python - 如何在没有设置文件的情况下更改 scrapy 用户代理

    python - 记录未显示在模板中

    python - 将 Django 模型导入另一个应用程序