2

i want to update fields using ajax:

models.py

class EmployerInfo(models.Model):
    employer = models.ForeignKey(Employer, unique=True)
    address=models.CharField(max_length=100, blank=True)
    city=models.CharField(max_length=40, blank=True)

contactinfo.html

<form id="ajax-form">
    <fieldset> 
        <legend>Contact Information</legend> 
        <label>Address:</label> 
        <input type="text" id="address" value="{{ empinfo.address }}" />
        <label>City:</label>
        <input type="text" id="city" value="{{ empinfo.city }}" /> <i class="icon-ok"></i>
    </fieldset>
</form>
<script>

$(document).ready(function()
{
    $("form#ajax-form").find(":input").change(function()
     {
       var field_name=$(this).attr("id");
       var field_val=$(this).val();
       var params ={ param1:field_name, param2:field_val };

       $.ajax({ url: "/employer/contactinfo/save/",
                dataType: "json",
                data: params,           
                success: setResult      
             });
    });
});

urls.py

.....other urls

url(r'^employer/contactinfo/save/$', 'save_employer_info_ajax'),

view.py

def save_employer_info_ajax(request):
    emp=Employer.objects.get(user=request.user)
    emp_info=EmployerInfo.objects.get(employer=emp)
    f_name=request.GET['param1']
    f_value=request.GET['param2']
    return HttpResponse(json.dumps({"issuccess": 'yes'}), content_type="application/json")

f_name the name of the field i want to update. lets assume it be 'address'. how can i access that attribute, (ie emp_info.address) so that i can update (ie emp_info.address=f_value) using emp_info.save() function.

is there any method available other than emp_info.address, so that i can access the field name using string (ie emp_info[f_name]=f_value ) or something??

4

2 回答 2

4

你可以只使用 getattr 烘焙到 python

attr_name = 'employer_id'

if getattr(employee, attr_name) == 3:
    ...
于 2013-05-15T04:22:08.790 回答
2

您可以在查询集对象上使用更新方法。这有点 hacky,因为你真的只想更新一个对象。

def save_employer_info_ajax(request):
    emp_info_query = EmployerInfo.objects.filter(employer__user=request.user)
    update_dict = {request.GET['param1'] : request.GET['param2'] }
    emp_info_query.update(**update_dict)

请注意,我使用反向查找关系来EmployerInfo基于模型的user字段进行访问Employer。然后你构造一个字典来保存你希望更新的键和值,并将它传递给queryset的 update 方法,而不是模型实例

不过,您应该使用表单进行数据输入。应该对您输入数据库的所有字段进行验证。您可以使用动态表单根据您通过 ajax 提交的值来指定要包含的字段。

于 2013-05-15T04:57:21.373 回答