我试图让用户手动输入文本字段,如果他们有许可证信息,或让它自动生成(基于表单信息),如果它的原始内容。在Django中,如何在保存前添加一个新的值给request.POST数据?
我被卡住了,因为从我的测试(使用打印命令)窗体正确更新与表单中给出的信息如果LicenseTag字段留空。问题是更新的信息没有被保存在数据库中。经过研究,这似乎是一个不变性的问题,这就是为什么我加了request.POST.copy()
并测试了注释掉的部分定义mutability=True
。
这里是我的views.py
def STLupload(request):
if request.method == 'POST':
form = NewUpload(request.POST, request.FILES)
data = request.POST.copy()
if form.is_valid():
#Dis gona need alot of work
firstname = request.user.first_name
lastname = request.user.last_name
displayname = request.user.display_name
email = request.user.email
if (firstname or lastname == "None"):
if displayname == "None":
liscname = email
else:
liscname = '%s %s' % (firstname, lastname)
else:
liscname = displayname
filetitle = request.POST.get(
'Title'
, '')
lisc = '%s %s' % (filetitle, liscname)
if data['LicenseTag'] == "":
'''
mutable = request.POST._mutable
request.POST._mutable = True
request.POST['LicenseTag'] = lisc
request.POST._mutable = mutable
'''
data['LicenseTag'] = lisc
print (request.POST.get(
'LicenseTag'
, ''))
print ("blank")
else:
print (form)
#Save current username
comment = form.save(commit=False)
comment.user = request.user
comment.save()
#Flash success message
messages.add_message(request, messages.SUCCESS, "File uploaded successful")
# Redirect to the document list after POST
return HttpResponseRedirect(reverse_lazy('STLup'))
else:
form = NewUpload() # A empty, unbound form
谁能帮我弄清楚如何保存生成的信息到我的数据库?
编辑#1
Models.py
from django.db import models
import os
#import django.db.models.deletion
from django.db import models
from django.core.exceptions import ValidationError
from django.core.files.storage import FileSystemStorage
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.conf import settings
from django.contrib.auth.models import User
# Create your models here.
def user_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
return os.path.join('uploads', str(instance.Title), filename)
def validate_file_extension(value):
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.stl','.STL']
if not ext in valid_extensions:
raise ValidationError(u'Please upload a .stl file type only')
def validate_img_extension(value):
ext = os.path.splitext(value.name)[1]
valid_extensions = ['.jpg','.png','.JPG']
if not ext in valid_extensions:
raise ValidationError(u'Please upload a .jpg or .png only')
class UploadedFiles(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True)
STL = models.FileField(_('STL Upload'),
upload_to=user_directory_path, validators=[validate_file_extension])
Photo = models.ImageField(_('Photo'),
upload_to=user_directory_path, validators=[validate_img_extension])
Title = models.CharField(_('Title of object'),
max_length=40, blank=False, null=True, unique=False)
Category = models.CharField(_('Category'),
max_length=40, blank=False, null=True, unique=False)
SubCategory = models.CharField(_('SubCategory'),
max_length=40, blank=True, null=True, unique=False)
SubSubCategory = models.CharField(_('*SubSubCategory (optional)'),
max_length=40, blank=True, null=True, unique=False)
FileType = models.BooleanField(_('Local?'),
default=0, unique=False)
Description = models.TextField(_('File Description'),
max_length=200, blank=True, null=True, unique=False)
LicenseTag = models.CharField(_('*License (optional, leave blank for original content)'),
max_length=200, blank=True, null=True, unique=False)
Xdim_mm = models.IntegerField(_('X dimension (mm)'),
default=0)
Ydim_mm = models.IntegerField(_('Y dimension (mm)'),
default=0)
Zdim_mm = models.IntegerField(_('Z dimension (mm)'),
default=0)
pub_date = models.DateTimeField(_('date_joined'), default=timezone.now)
这是我forms.py。
from django import forms
from django.core.validators import MinLengthValidator
from .models import UploadedFiles
class NewUpload(forms.ModelForm):
class Meta:
model = UploadedFiles
fields = ('Title', 'STL','Photo','Description', 'Category', 'SubCategory', 'SubSubCategory', 'LicenseTag')
什么是您的模型?你的表格是什么?你为什么试图修改POST?几乎从不需要那 – e4c5
我已经添加了我的模型和表单。我想要做的就是根据用户输入表单数据创建一个数据库条目。如果还有另一种方式来做到这一点,那么我如何建议我接受任何其他想法。 – RknRobin