python - 写入当前条目而不是在 django 中创建新条目
问题描述
我正在尝试创建一个文档表单并将文档位置写入用户的当前数据库条目,当我尝试这样做时它会不断创建一个新条目,以及如果我尝试在写入的部分中使用 pk=p data 它将覆盖整个条目。
视图.py
** I import everything here **
@login_required(login_url='/accounts/login/')
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
p = request.user.pk
newdoc = CustomUser.objects.get(pk=p)
newdoc = CustomUser(docfile = request.FILES['docfile'])
# I also attempted the following which overwrit the entire user
# newdoc = CustomUser(pk=p, docfile = request.FILES['docfile']))
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('list'))
else:
form = DocumentForm() # A empty, unbound form
current_user = request.user
# Render list page with the documents and the form
return render(request, 'list.html', {'form': form,'pk':current_user.pk})
用户的models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
pass
def __str__(self):
return self.email
docfile = models.FileField(upload_to='static/users/',)
表格.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)
解决方案
推荐阅读
- git - 远程存储库是否等同于中央存储库?
- sql - 从平面文件源加载到 OLEDB 目标时出现 SSIS-日期错误
- c - Notepad++、NppExec、CreateProcess() 失败,错误代码为 2,Windows 10
- django - Django Channels 消费者消费 1 次通话两次
- flutter - 如何在 .bash_profile 中永久添加颤振路径?
- javascript - 无法使用本机反应在 Firebase 中更新
- java - 如何循环用户输入直到输入整数?
- sql - 了解 Snowflake 中的锁和查询状态(对单个表进行多次更新)
- python - 在 Rasa 中使用自定义操作后,我的机器人无法加载
- c# - NUnit 不会运行我的单元测试;说缺少测试适配器,但我确实安装了它