Within a template distinguish between create and update form

前端 未结 3 1563
轻奢々
轻奢々 2021-01-01 16:13

If the CreateView and UpdateView are using the same template \"model_form.html\" then within the template how would I differentiate if I am creating or updating a form?

相关标签:
3条回答
  • 2021-01-01 16:41

    In an update view, there'll be a form.instance, and form.instance.pk will not be None. In a create view, there may or may not be form.instance, but even if there is form.instance.pk will be None.

    0 讨论(0)
  • 2021-01-01 16:58

    From docs:

    CreateView

    object

    When using CreateView you have access to self.object, which is the object being created. If the object hasn’t been created yet, the value will be None.

     

    UpdateView

    object

    When using UpdateView you have access to self.object, which is the object being updated.

    Solution:

    {% if object %}
        <input type="submit" value="Update Author" />
    {% else %}
        <input type="submit" value="Add Author" />
    {% endif %}
    
    0 讨论(0)
  • 2021-01-01 17:04

    add this function in your both CreateView and UpdateView class:

    # For Create
    def get_context_data(self, **kwargs):
            kwargs['naming'] = 'Create'
            context = super(CLASSNAME, self).get_context_data(**kwargs)
            return context
    
    # For Update
    def get_context_data(self, **kwargs):
            kwargs['naming'] = 'Update'
            context = super(CLASSNAME, self).get_context_data(**kwargs)
            return context
    

    then reference those in your template with {{ naming }}

    example

    <button type="submit">{{ naming }}</button>
    
    0 讨论(0)
提交回复
热议问题