简体   繁体   中英

How to update db record from Django form

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.

  1. I can't figure out how to dynamically pass the id of the record from HTML. When I hardcode the id, everything is ok. Here's the code. I tried 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.
  2. I expected Django to automacically fill up the textboxes by the correponding values of the selected records, but the they are rendered blank (as a result, I have to fill all the textboxes, even if I want to change one of the fields). Here' my view.

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">&times;</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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM