34👍
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.
31👍
From docs:
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.
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 %}
- [Django]-Django model object with foreign key creation
- [Django]-How to get the previous URL from a POST in Django
- [Django]-How to assign items inside a Model object with Django?
2👍
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>
- [Django]-Django : How can I find a list of models that the ORM knows?
- [Django]-How to deal with this ERROR (1049, "Unknown database '/users/ohyunjun/work/astral/mysql'")
- [Django]-Changing a project name in django
1👍
the simplest way is to use template yesno
filter as
{{ object|yesno:'Update Author,Create Author' }}
or in your case as the author is same word in both so
{{ object|yesno:'Update,Create' }} Author
object
becomes yes if only there is an object instance and that would be the update view
while it becomes no in create view
.
- [Django]-Generating file to download with Django
- [Django]-How to have a Python script for a Django app that accesses models without using the manage.py shell?
- [Django]-With DEBUG=False, how can I log django exceptions to a log file