2

我正在使用 django-floppyforms。如何将一些值传递给 html 模板?(用于初始化字段和简单打印)。下面的代码解释了设置:

模型.py:

class ContactMessage(models.Model):    
    msg_sender = models.ForeignKey(User, related_name="sent_messages")
    msg_receiver = models.ForeignKey(User, related_name="received_messages")
    listing = models.ForeignKey(Listing)
    msg_title = models.CharField(max_length=200)
    msg_body = models.TextField()

网址.py:

url(r'^listing/(?P<listing_id>\d+)/reply/$', views.ReplyListingView.as_view(), name='reply_listing'),

视图.py:

class ReplyListingView(CreateView):
    model = ContactMessage
    form_class = CreateContactMessageForm

表格.py:

class CreateContactMessageForm(forms.ModelForm):

    class Meta:
        model = ContactMessage

        exclude = ['msg_sender',
                   'msg_receiver',
                   'listing',
                  ]

        widgets = {
            'msg_title': forms.TextInput({"value": ????}),
            'msg_body': forms.Textarea,
        }   

contactmessage_form.html:

{% extends 'base.html' %}

{% block content %}
<div class="row">
  <div class="col-md-6">
      <p>USER: {{request.user}} 
         SENDER: {{ form.sender }} 
         RECEIVER: {{ form.receiver }}
         LISTING: {{ form.listing }}
      </p>
      <form method="post">
        {% csrf_token %}
        {{form}}
        <input class="btn btn-success" type="submit" value="Send" />
        <button type="button" class="btn btn-default" onClick="window.history.back();">
                Cancel
        </button>
      </form>
  </div>
</div>

{% endblock %}

所以:

假设在某个上下文中,我知道listing、sender和receiver(背景解释:URL有listing_id,所以listing的标题和所有者是已知的;而且sender应该是当前登录的用户)。

现在我想显示一个ReplyListingView,将这三个值传递给它,然后让它显示CreateContactMessageForm,这样:

  1. msg_title 小部件预先填充了给定列表的“title”字段的值(即,而不是上面代码中的“????”部分)

  2. <p>USER:...</p>我可以访问 html(部分)中的发送者、接收者和列表字段的值。

我怎样才能做到这一点?

我希望这个问题足够清楚。

谢谢 :)

4

4 回答 4

0

有一个初始视图变量。

看看这个网站,他们有所有的视图方法和变量: http ://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/CreateView/

您还可以覆盖实例化表单的方法并添加初始

于 2014-02-10T17:08:35.743 回答
0

假设 floppyforms 就像 django 表单一样工作(看起来就是这样),只需使用初始:https ://docs.djangoproject.com/en/dev/ref/forms/api/#dynamic-initial-values

于 2014-02-10T15:59:10.977 回答
0

关于标题,您应该使用 将初始数据传递给表单get_initial

关于其他非形式的东西,你的视图应该通过get_context_data.

class ReplyListingView(CreateView):
    model = ContactMessage
    form_class = CreateContactMessageForm

    def get_initial(self):
        d = super(ReplyListingView, self).get_initial()
        d['title'] = "blah"
        return d

    def get_context_data(self, **kwargs):
        d = super(ReplyListingView, self).get_context_data(**kwargs)
        d['foo'] = 'bar'
        return d
于 2014-02-13T11:45:59.600 回答
0
class ReplyListingView(CreateView):

    model = ContactMessage
    form_class = CreateContactMessageForm

    #add this line to the view
    initial={"field_name":"value"}
于 2014-02-10T18:08:49.840 回答