使用Django和x-editable将更改保存到数据库 [英] Save Changes to Database using Django and x-editable
问题描述
我是JS,HTML,Django和所有其他相关知识的新手,但我无法通过阅读文档或使用Google自行解决问题.
I am new to JS, HTML, Django and all that related stuff, and I was not able to solve my problem on my own by reading documentation or using Google.
我想在django环境中使用x-editable将内联更改保存到数据库.下面的模板可以正常工作,但是现在我想用新名称覆盖数据库条目.
I want to save inline-changes using x-editable to the database in an django environment. The template below works perfectly, but now I would like to overwrite the database entries with the new names.
我试图将代码简化为问题的相关部分.
I tried to reduce the code to the relevant parts of my problem.
models.py:
models.py:
class MyClass(models.Model):
name = models.CharField(max_length=120)
views.py:
def list(request):
return render(request, 'list.html', {'list':MyClass.objects.all()}
urls.py:
url(r'^list/$', 'myapp.views.list', name='list'),
list.html:
list.html:
{% extends "base.html" %}
{% block content %}
<script>
$(document).ready(function() {
$.fn.editable.defaults.mode = 'inline';
$('.name').editable({
});
});
</script>
<h1>Names</h1>
<div>
<table border='1'>
{% for l in list %}
<tr><td><a class="name">{{ l.name }}</a></td></tr>
{% endfor %}
</table>
</div>
{% endblock %}
------------------------------------------------------------
我最有前途的方法是创建一个更新视图.
--------------------------------------------------------
My most promising approach was to create an update view.
def list_update(request, pk):
l = get_object_or_404(MyClass, pk=pk)
form = ListForm(request.POST or None, instance=l)
if form.is_valid():
form.save()
return redirect('list')
return render(request, '', {'form':form})
并将以下行添加到上面的代码中:
and add the following lines to the code above:
urls.py
url(r'^update/(?P<pk>\d+)$', 'myapp.views.list_update', name='list_update'),
list.html
$('.name').editable({
pk: l.pk,
url: '{% url 'list_update' l.pk%}',
});
但是这种尝试会导致NoReverseMatch错误,并且 l.pk 似乎为空.感谢您提供有关如何正确执行此操作的帮助.
But this attempt results in an NoReverseMatch error and l.pk seems to be empty. I appreciate any help on how to do this in the right way.
推荐答案
urls.py:
url(r'^xed_post$', views.xed_post, name='xed_post'),
views.py中的Django视图代码(基于函数):
Django view code (function based) in views.py:
from django.http import JsonResponse
def xed_post(request):
"""
X-Editable: handle post request to change the value of an attribute of an object
request.POST['model']: name of Django model of which an object will be changed
request.POST['pk']: pk of object to be changed
request.POST['name']: name of the field to be set
request.POST['value']: new value to be set
"""
try:
if not 'name' in request.POST or not 'pk' in request.POST or not 'value' in request.POST:
_data = {'success': False, 'error_msg': 'Error, missing POST parameter'}
return JsonResponse(_data)
_model = apps.get_model('swingit', request.POST['model']) # Grab the Django model
_obj = _model.objects.filter(pk=request.POST['pk']).first() # Get the object to be changed
setattr(_obj, request.POST['name'], request.POST['value']) # Actually change the attribute to the new value
_obj.save() # And save to DB
_data = {'success': True}
return JsonResponse(_data)
# Catch issues like object does not exist (wrong pk) or other
except Exception as e:
_data = {'success': False,
'error_msg': f'Exception: {e}'}
return JsonResponse(_data)
然后,在list.html中:
then, in list.html:
{% extends "base.html" %}
{% block content %}
<script>
$(document).ready(function() {
$.fn.editable.defaults.mode = 'inline';
$('.name').editable({
params: {
csrfmiddlewaretoken:'{{csrf_token}}',
model:'MyClass'
},
url: '/xed_post',
error: function(response, newValue) {
return response.responseText;
},
success: function(response, newValue) {
if(!response.success) return response.error_msg;
}
});
});
</script>
<h1>Names</h1>
<div>
<table border='1'>
{% for l in list %}
<tr><td><a class="name" data-name="name" data-type="text" data-pk="{{ l.pk }}">{{ l.name }}</a></td></tr>
{% endfor %}
</table>
</div>
{% endblock %}
请注意,将css类和Django字段名称同时使用名称"会造成混淆.data-name ="name"是Django字段名称,而class ="name"是css类.
Note that using "name" for both the css class and the Django field name is confusing. data-name="name" refers to the Django field name, while class="name" refers to the css class.
这篇关于使用Django和x-editable将更改保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!