如何将当前user_id输入django数据库表?

问题描述 投票:0回答:1

我正在尝试在用户界面中创建可编辑的表,一切正常,直到我尝试插入新的模型参数,如:

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.朋友

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.朋友

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">&times;</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 %}
python ajax django sqlite
1个回答
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所以你需要像我在我的代码中那样保存usr

© www.soinside.com 2019 - 2024. All rights reserved.