我有一个django模型,它包含一些字段和相关的选项:
class Product(models.Model):
CONDITION_CHOICES = (
("GOOD", "Good"),
("BAD", "Bad"),
("UNKNOWN", "Unknown"),
)
name = models.CharField(max_length=200, blank=True, null=True)
colour = models.CharField(max_length=200, blank=True, null=True)
condition = models.CharField(max_length=20, choices=CONDITION_CHOICES, blank=True, null=True)
condition_source = models.CharField(max_length=20, blank=True, null=True)
condition_last_updated = models.DateTimeField(blank=True, null=True)
我还有一个bootstrap驱动的表单,如下所示:
<div class="form-group">
<label class="control-label"><strong>Condition</strong></label>
<br/>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-outline-primary">
<input type="radio" name="condition" value="GOOD" autocomplete="off">
Good
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="condition" value="BAD" autocomplete="off">
Bad
</label>
<label class="btn btn-outline-primary">
<input type="radio" name="condition" value="UNKNOWN" autocomplete="off">
Unknown
</label>
</div>
</div>
我正在尝试这样做,这样当用户单击UI中的一个按钮时,产品模型就会更新(特别是condition、condition_source和condition_last_updated字段)。实际的模型有多个字段与选择选项相关联,所以我希望模型在用户处理表单时实时更新,而无需重新加载页面。
任何指导都将在这里被感谢-我已经看过intercooler.js,但不确定这是不是适合这项工作的工具。
发布于 2019-02-08 20:37:37
由于您尚未指定condition_source
应包含的内容,因此我已将其设置为string some_source
Ajax:
$('.btn').on('click', function(){
$.post(
'/your_vew/',
{
'source': "some_source",
'condition': $(this).find('input').val(),
'csrfmiddlewaretoken': '{{csrf_token}}'
},
function(data){
console.log(data.response);
}
);
});
urls.py:
urlpatterns = [
...
path('your_vew/', views.your_view),
...
]
views.py:
from django.http import JsonResponse
from datetime import datetime
def your_view(request):
data = {'response': ''}
if request.method == 'POST':
p1 = Product.objects.filter(pk=1).update(
condition_source=request.POST.get('source'),
condition=request.POST.get('condition'),
condition_last_updated=datetime.now()
)
if p1:
data['response'] = 'Record updated!'
return JsonResponse(data)
发布于 2019-02-08 20:31:38
现在,您有几个选择。我所做的就是以类的形式使用Jquery ajax方法,并在这个类中为我的应用程序设置函数。Django需要csrf令牌来处理传入请求。因此,我找到了这两个函数,它们从客户端检索cookie csrf令牌。
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
将csrf令牌存储在变量中后,您需要将其传递给ajax beforeSend函数,例如:
ajax_setup(enable_async){
enable_async = true;
$.ajaxSetup({
async: enable_async,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
}
}
完整的ajax请求如下所示
update_user_language(user_id, lang, callback){
this.ajax_setup(true);
$.ajax({
url: this.url,
type: "POST",
data: {
'user_id':user_id,
'lang':lang,
},
dataType: 'json',
success: function(data){
db_request_after();
if(callback !== undefined) callback(data);
},
error: function(){
db_request_error();
},
});
}
请注意回调变量。这允许ajax调用传递从the服务检索到的数据的函数。
一旦发送了请求,就需要设置view.py来接受请求并处理POST变量。
def sample_view(request):
if request.method == "POST"
user_id = request.POST.get('user_id')
lang = request.POST.get('lang')
#update the model value
user = User.objects.get(pk=user_id)
user.language = lang
user.save()
return JsonResponse({'message':'user updated'})
else:
return render(...)
https://stackoverflow.com/questions/54598544
复制相似问题