Django - 将对象传递到自定义表单字段

时间:2010-12-06 13:38:13

标签: django django-forms

我正在尝试使用jquery代码here创建评级表单字段 到目前为止,我的工作正常,但我需要做的是根据我想要评价的对象传入一个网址。请参阅以下代码行$.post("URL TO GO HERE", {rating: value}, function(db)。该网址类似于/rating/object_id,其中object_id将是我想要评分的对象的pk。传递对象ID的最佳方法是什么,以便我可以使用它。我是否需要先将其传递给RatingField,然后将其从那里传递到StarWidget?

class StarWidget(widgets.Select):
    """
    widget to show stars which the user can click on to rate
    """
    class Media:
        css = {
            'all': ('css/ui.stars.css',)
        }
        js = ('js/ui.stars.js',)

    def render(self, name, value, attrs=None):
        output = super(StarWidget, self).render(name, value, attrs)

        jquery = u"""
        <div id="stars-rating" class="rating_section">
            %s
            <span id="caption"></span>
        </div>
        <script type="text/javascript">
        $(function(){
            $("#stars-rating").stars({
                inputType: "select",
                captionEl: $("#caption"),
                cancelShow: false,
                callback: function(ui, type, value)
                {
                    // Hide Stars while AJAX connection is active
                    $("#stars-rating").hide();
                    $("#loader").show();
                    $.post("URL TO GO HERE", {rating: value}, function(db)
                    {
                        $("#loader").hide();
                        $("#stars-rating").show();
                    }, "json");
                }
            });
        });
        </script>

        """ % (output)

        return mark_safe(jquery)

class RatingField(forms.ChoiceField):
    """
    rating field.  changes the widget and sets the choices based on the model
    """
    widget = StarWidget

    def __init__(self, *args, **kwargs):
        super(RatingField, self).__init__(*args, **kwargs)

        self.label = "Rating:"
        self.initial = 3
        self.choices = Rating.RATING_CHOICES

1 个答案:

答案 0 :(得分:0)

我知道内置字段是以这种方式完成的,但将大量HTML或JS嵌入到Python代码中并不是一个好习惯。而是创建一个单独的模板片段,该片段由字段的render方法呈现。您可以传入对象的ID以在模板{% url %}功能中使用,或者只需通过调用reverse传递整个网址。