I am a newbie to Django, so this might sound like a stupid question, but please bear with me. I have created a form for inserting records into my db, and now I am trying to use this same form for updating records. But it does not seem to work correctly. Here is my code.
action="/task_list/update_task/{{ id }} /"
which does not work and "/update_task//" appears in URL, causing Django to raise error message because no view is found. Ideally, I would like to pass the Django-s embedded id, and not the id from the model, otherwise I have to manually include id = models.IntegerField(primary_key=True)
command in my model and exclude it from the form which does not seem to be "best practice", given that Django has its own ids. Here is the code: URL:
url(r'^task_list/update_task/(?P<task_id>\d+)/$',task_views.updateTask),
View:
def updateTask(request, task_id):
#cur_usr_sale_point = PersonUnique.objects.filter(employees__employeeuser__auth_user = request.user.id).values_list('agreementemployees__agreement_unique__sale_point_id',flat=True)
selected_task = Tasks.objects.get(id=task_id)
if request.method == 'POST':
task_form = TaskForm(request.POST,instance=task_id)
if task_form.is_valid():
task_form.save();
taskTable = Tasks.objects.all()
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'taskTable': taskTable},context_instance=RequestContext(request))
else:
taskTable = Tasks.objects.all()
task_form = TaskForm()
return render_to_response('task_management/task_list.html',{'createTask_form':task_form, 'taskTable': taskTable},context_instance=RequestContext(request))
The Django form
class TaskForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(TaskForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.error_messages={'required': 'Придется не поленится и заполнить это поле...'}
field.widget.attrs['cl
class Meta:
model=Tasks
fields = '__all__'
exclude=['id']
The template:
{% for task in taskTable %}
<tr>
<td onclick = "updateTaskWindow()"> <span style="display:block;" class="glyphicon glyphicon-pencil"></span></a>
</td>
<td>{{task.description_short}}</td>
</tr>
{% endfor %}
The Bootstrap modal window which should be used for updating:
<form class="modal fade" id="updateTaskWindow" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" action="/task_list/update_task/{{ pk }}/" method="post">{% csrf_token %}
<div class="modal-dialog modal-lg form-horizontal" role="form">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">Обновить задачу</h4>
</div>
<div class="modal-body" style="font-size: smaller">
{{ createTask_form.as_p }}
</div>
<div class="modal-footer">
<input class="btn btn-default btn-sm" type="submit" value="Обновить"/>
</div>
</div>
</div>
</form>
The model:
class Tasks(models.Model):
id = models.IntegerField(primary_key=True)
description_short = models.CharField(max_length=500)
description_full = models.TextField()
status = models.ForeignKey(TaskStatus, on_delete=models.CASCADE)
type = models.ForeignKey(TaskType, on_delete=models.CASCADE)
date_start = models.DateTimeField(blank=True, null=True)
date_end = models.DateTimeField(blank=True, null=True)
is_important = models.IntegerField(blank=True, null=True)
effective_from = models.DateTimeField(blank=True, null=True)
effective_to = models.DateTimeField()
class Meta:
managed = False
db_table = 'tasks'
And the JS:
var updateTaskWindow = function() {
$('#updateTaskWindow').modal('show');
}
I spent hours trying to implement this, but did not succeed. Please help !!!
First change you form to have inputs for each field of your model, read about forms here
then do something like the following
if request.method == 'POST':
task_form = TaskForm(request.POST,instance=selected_task )
if task_form.is_valid():
# inside your model instance add each field with the wanted value for it
newrecord = Tasks(name=task_form.cleaned_data['name']);
task_form.save();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.