在Django中,如何在保存之前为request.POST数据添加新值?

时间:2016-09-30 03:39:21

标签: python django request immutability

我试图允许用户手动输入文本字段(如果他们有许可证信息),或者让它自动生成(根据表单信息)原始内容。

因为我的测试(使用print命令)而导致表单正确更新,如果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')

2 个答案:

答案 0 :(得分:1)

我认为最好的方法是覆盖模型中的save方法。

class UploadedFiles(models.Model):
    def save(self, *args, **kwargs):
        if not self.LicenseTag:
            if self.user:
                liscname = self.user.get_full_name() or self.user.email
                self.LicenseTag = "{0} {1}".format(liscname, self.Title)

        super(UploadFiles,self).save(*args,**kwargs)

然后,同样的事情在你的管理员工作,而不需要做很多努力工作。我冒昧地优化了许可证标签的派生方式。

现在你的观点变得更加简单了。

def STLupload(request):
    if request.method == 'POST':
        form = NewUpload(request.POST, request.FILES)
        if form.is_valid():
            lisc = '%s %s' % (filetitle, liscname)

            #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 :(得分:0)

我认为最好是保存(commit=False)然后添加必填字段

form = MyForm(request.POST)
if form.is_valid():
    obj = form.save(commit=False)
    obj.licence = 'your license code'
    obj.save()