在Django中,如果将模型添加到数据库,如何更新用户配置文件?

时间:2016-10-02 18:54:55

标签: python django django-allauth

我正在创建一个用户可以上传文件的网站。我的上传表单正常工作,并且正确地将当前用户与上传的文件相关联。然而,一旦上传,我希望用户配置文件模型更新为该特定用户上传的文件数。我使用django-allauth和自定义管理模型。

models.py(用于识别当前用户)

class ConfigFiles(models.Model):
    user = models.ForeignKey(
    settings.AUTH_USER_MODEL, blank=True, null=True)

    Printer = models.CharField(_('Printer Model'),
    max_length=100, blank=True, null=True, unique=False, help_text="Something like 'i3'")
    printerbrand = models.CharField(_('Printer Brand'),
    max_length=100, blank=True, null=True, unique=False, help_text="Something like 'Prusa'")
    Plastic = models.CharField(_('Plastic'),    
    max_length=40, blank=True, null=True, unique=False, help_text="Something like 'ABS' or 'Nylon'")

    HDConfig = models.FileField(_('High Detail, Slow Speed'), 
    upload_to=UploadedConfigPath, validators=[validate_file_extension], help_text="Displayed as HD on Infinity-Box")
    LDConfig = models.FileField(_('Fast speed, Low Detail'), 
    upload_to=UploadedConfigLDPath, validators=[validate_file_extension], help_text="Displayed as FAST on Infinity-Box")

    pub_date = models.DateTimeField(_('date_joined'), 
    default=timezone.now)

这是我的自定义管理模型.py(没有自动更新configuploaded)

class UserProfile(models.Model):
    user = models.OneToOneField(DemoUser, primary_key=True, verbose_name='user', related_name='profile')

    avatar_url = models.CharField(max_length=256, blank=True, null=True)

    configuploaded = models.IntegerField(_('Number of uploaded Config files'), default=0, unique=False)
    filesuploaded = models.IntegerField(_('Number of uploaded STL files'), default=0, unique=False)


    dob=models.DateField(verbose_name="dob", blank=True, null=True)

    def __str__(self):
        return force_text(self.user.email)

    class Meta():
        db_table = 'user_profile'

编辑1

这里是view.py。

@login_required
def uplist(request):
    if request.method == 'POST':
        form = ConfigUpload(request.POST, request.FILES)
        if form.is_valid():

            comment = form.save(commit=False)
            comment.user = request.user
            #newdoc = ConfigFiles(HDConfig=request.FILES['HD file'])

            comment.save()


            messages.add_message(request, messages.SUCCESS, "Configuration added")    

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse_lazy('list'))
    else:
        form = ConfigUpload()  # A empty, unbound form
    print (request.user.first_name)
    # Load documents for the list page
    documents = ConfigFiles.objects.all()

    # Render list page with the documents and the form
    return render(
        request,
        'visitor/configupload.html',
        {
        'documents': documents,
        'form': form,
        }
    )

理想情况下,每当用户上传文件时,configuploaded变量都会相应增加。有没有一种简单的方法可以在模型中执行此操作,还是应该从我的views.py中执行此操作?

2 个答案:

答案 0 :(得分:0)

您可以在Django中使用Post Save Signal

from django.db.models.signals import *
from django.db.models import F

def file_upload_count(sender, instance, created, *args, **kwargs):
    if created:
        UserProfile.objects.filter(user = instance).update(filesuploaded = F('filesuploaded')+1)

post_save.connect(file_upload_count, sender=ConfigFiles)

每当上传一个新文件时,这将执行定义的函数,并将增加值或任何你想要的值。

尝试在模型文件中添加此代码

答案 1 :(得分:0)

有几种方法可以解决这个问题,如何最好地解决这个问题取决于你的用例。在我当前的网站中,我使用混合属性和信号来实现此功能。

使用属性 - 更少的数据库写入工作&即使您在模型上执行批量删除,但每次显示时都会生成一个查询。

class UserProfile(models.Model):
    #your stuff
    def _get_uploaded_files(self):
          return ConfigFiles.objects.filter(some_appropriate_filter).count()
    uploaded_files = property(_get_uploaded_files)

覆盖save方法以增加字段:

class ConfigFiles(models.Model):
#your model definition here
    def save(self, *args, **kwargs):
        super(ConfigFiles, self).save(*args, **kwargs)
        self.user.filesuploaded += 1

您也可以根据Atul Yadav的回答使用postave信号。然而,IMO它们不那么清晰(因为你最终定义了模型之外的功能),尽管如果你需要做几件事它们很有用