【问题标题】:Auto Add record when Button is Pressed in Django View在 Django 视图中按下按钮时自动添加记录
【发布时间】:2013-08-17 12:24:14
【问题描述】:

在我的数据库中,Instrument 对象可以有许多 CalibrationCertificate 对象,这些对象仅包含 Instrument 的 ForeignKey、发布日期和过期日期。这两个日期都是自动计算的,不需要用户输入。因此,有没有办法在Instrument_Detail 视图上放置一个按钮,该按钮将向数据库添加一个新的CalibrationCertificate 记录,并将instrument 字段设置为当前对象?

【问题讨论】:

  • 不,在 Instruments 的 DetailView 中。

标签: django forms django-views


【解决方案1】:

恕我直言,这是最好的解决方案。要在重定向视图中自定义 url,请使用 get_redirect_url。

views.py

class AddCalibrationCertificateView(RedirectView):
    http_method_names = ['post']
    url = '/instrument/1/'

    def post(self, request, *args, **kwargs):
        '''Here you add new certificate object, use self.kwargs['instrument_pk']
           to get related instrument
        '''
        return super(AddCalibrationCertificateView, self).post(request, *args, **kwargs)

new_cert = AddCalibrationCertificateView.as_view()

urls.py

url(r'^add/certificate/(?P<instrument_pk>\d+)/$', 'views.new_cert', name='new_cert'),

instrument.html

<form action="{% url 'new_cert' 1 %}" method="post">{% csrf_token %}
    <input type="submit" value="Add cert" />
</form>

【讨论】:

  • 使用方法2,你如何在模板中渲染它?
  • @RowanIngram 你的意思是渲染 CreateView 吗?只需添加模板文件。 CBV 为您做一切。示例:docs.djangoproject.com/en/dev/ref/class-based-views/…
  • 不,我的意思是我应该在模板中做什么才能达到预期的结果,也就是说,一个所有值都是自动填充的表单,只需要用户按'提交'?
  • @RowanIngram 我已将帖子更新为我认为最好的解决方案
猜你喜欢
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多