我正在尝试创建一个文档表单,并将文档位置写入用户当前的数据库条目中,当我尝试这样做时,它会不断创建一个新条目,就像我试图在该部分中使用pk = p一样写入数据将覆盖整个条目。
views.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/',)
forms.py
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='max. 42 megabytes'
)