首页 > 解决方案 > 写入当前条目而不是在 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'
)

标签: pythondjango

解决方案


推荐阅读