Reputation: 391
I have written code to display a form on the html page in django. When I click on the update button, everytime, it is showing an empty form. But what I want is, if I have entered some data previously, that data should be displayed in the form normally. Then I have to be able to edit it. But, I am getting an empty form everytime.
views.py:
def update_longterm(request):
if not request.user.is_authenticated:
return render(request, 'cups4/index.html')
else:
form = LongtermForm(request.POST or None, request.FILES or None)
if form.is_valid():
longterm = form.save(commit=False)
longterm.user = request.user
longterm.body = form.cleaned_data['body']
longterm.save()
return render(request, 'cups4/detail_longterm.html', {'longterm': longterm})
context = {
"form": form,
}
return render(request, 'cups4/create_template.html', context)
Models.py:
class NotNecessary(models.Model):
title = models.TextField("NotNecessary",editable=False)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
user = models.ForeignKey(User, default=1,on_delete=models.CASCADE)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
Forms.py:
class LongtermForm(forms.ModelForm):
class Meta:
model = Longterm
fields = [ 'body',]
template:
{% extends 'base.html' %}
{% block title %}Immediate{% endblock %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<h3>Immediate Goals</h3>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'cups4/form_template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
Everytime, a new form is displayed. Instead, I want the previous data to be loaded. How to do that? Thanks in advance!
Upvotes: 2
Views: 1895
Reputation: 1152
There may be two situations:
When you are updating already created object, then you may fetch it from the database and pass as: form = LongtermForm(instance=your_object)
In other case, if your are adding a new object and you want to see the previously entered information by the user in case of some errors. You may render form as:
form = LongtermForm(request.POST or None, request.FILES or None)
In both the cases please make sure you are rendering form.errors and form.non_field_errors in case if you are manually rendering your form in create_template.html, otherwise django will take care of it automatically , if you render it like , for eg. {{ form.as_p }}
Upvotes: 1