我试图在用户界面中创建可编辑的表格,一切正常,直到我尝试插入新的模型参数,如:
usr = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete = models.CASCADE)
之后出现此类错误:django.db.utils.IntegrityError:NOT NULL约束失败:devices_device.usr_id
我试图实现这一点,因为当我保存数据时,每个用户都可以看到它。但目标是分离用户信息。也许有一种更简单的方法。
使用django 1.11.10版本
Models.py
class Device(models.Model):
usr = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ip = models.CharField(max_length=50)
port_number = models.CharField(max_length=50)
Views.py
def save_device_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
devices = Device.objects.all()
data['html_device_list'] = render_to_string('devices/additional/partial_devices_list.html', {
'devices': devices
})
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def device_create(request):
if request.method == 'POST':
form = DeviceForm(request.POST)
else:
form = DeviceForm()
return save_device_form(request, form, 'devices/additional/partial_device_create.html')
更新:
partial_device_create.html
<form method="post" action="{% url 'device_create' %}" class="js-device-create-form">
{% csrf_token %}
<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"> Create new device </h4>
</div>
<div class="modal-body">
{% include 'devices/additional/partial_device_form.html' %}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"> Uždaryti </button>
<button type="submit" class="btn btn-primary"> Pridėti </button>
</div>
</form>
save_device_form.html
{% load widget_tweaks %}
{% for field in form %}
<div class="form-group{% if field.errors %} has-error{% endif %}">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{% render_field field class="form-control" %}
{% for error in field.errors %}
<p class="help-block">{{ error }}</p>
{% endfor %}
</div>
{% endfor %}
答案 0 :(得分:0)
def save_device_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form = form.save(commit=False) # < use these 3 below lines for save data
form.usr = request.user
form.save()
根据您需要 usr 的设备型号,所以您需要像我在代码中一样保存用户