如何检索当前登录用户以在模型中使用动态文件名

时间:2019-05-20 21:46:32

标签: python django sqlite

我正在尝试将当前'upload_to='目录设置为与当前登录用户的用户名相同,以便将每个上传的文件保存到用户自己的目录中。

我试图遵循django documentation,它看起来与此类似……

from django.db import models


def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)


class UploadReports(models.Model):
    upload = models.FileField(upload_to=user_directory_path, null=True)

我也曾尝试添加RequestMiddleware来实现这一点,但是在实现它时感觉不对。

我希望它抓住当前登录的用户并在目录路径中使用它。出现的错误是:AttributeError at /stylist/ 'UploadReports' object has no attribute 'user'

1 个答案:

答案 0 :(得分:2)

解决方案::Django文档没有指定需要添加到模型中的用户,尽管确实希望有一个。

完成后,模型如下所示:

> Task :compileSimulationsJava NO-SOURCE

> Task :compileSimulationsScala
Pruning sources from previous analysis, due to incompatible CompileSetup.
there were 6 feature warnings; re-run with -feature for details
one warning found

> Task :processSimulationsResources NO-SOURCE
> Task :simulationsClasses

> Task :gatlingRun
16:40:27.238 [main] INFO io.gatling.core.config.GatlingConfiguration$ - Gatling will try to use 'gatling.conf' as custom config file.
16:40:27.598 [GatlingSystem-akka.actor.default-dispatcher-3] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
16:40:28.242 [GatlingSystem-akka.actor.default-dispatcher-3] INFO io.gatling.core.stats.writer.ConsoleDataWriter - Initializing
16:40:28.242 [GatlingSystem-akka.actor.default-dispatcher-4] INFO io.gatling.core.stats.writer.LogFileDataWriter - Initializing
16:40:28.248 [GatlingSystem-akka.actor.default-dispatcher-3] INFO io.gatling.core.stats.writer.ConsoleDataWriter - Initialized
16:40:28.253 [GatlingSystem-akka.actor.default-dispatcher-4] INFO io.gatling.core.stats.writer.LogFileDataWriter - Initialized
Simulation org.mycompany.karate.perf.MyAPI started...
16:40:28.359 [GatlingSystem-akka.actor.default-dispatcher-2] ERROR com.intuit.karate.gatling.KarateAction - 'classpath:org/mycompany/karate/tests/myAPI.feature@test=myTag' crashed on session Session(my-api,1,1558395628341,Map(),0,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$329/1759250827@7cee98de), forwarding to the next one
java.lang.NullPointerException: null
        at com.intuit.karate.Resource.<init>(Resource.java:55)
        at com.intuit.karate.core.FeatureParser.parse(FeatureParser.java:75)
        at com.intuit.karate.FileUtils.parseFeatureAndCallTag(FileUtils.java:155)
        at com.intuit.karate.Runner.callAsync(Runner.java:183)
        at com.intuit.karate.gatling.KarateAction.execute(KarateAction.scala:77)
        at io.gatling.core.action.Action.$bang(Action.scala:38)
        at io.gatling.core.action.Action.$bang$(Action.scala:38)
        at com.intuit.karate.gatling.KarateAction.io$gatling$core$action$ChainableAction$$super$$bang(KarateAction.scala:37)
        at io.gatling.core.action.ChainableAction.$bang(Action.scala:63)
        at io.gatling.core.action.ChainableAction.$bang$(Action.scala:61)
        at com.intuit.karate.gatling.KarateAction.io$gatling$core$action$ExitableAction$$super$$bang(KarateAction.scala:37)
        at io.gatling.core.action.ExitableAction.$bang(BlockExit.scala:138)
        at io.gatling.core.action.ExitableAction.$bang$(BlockExit.scala:136)
        at com.intuit.karate.gatling.KarateAction.$bang(KarateAction.scala:37)
        at io.gatling.core.controller.inject.Workload.startUser(Workload.scala:55)
        at io.gatling.core.controller.inject.Workload.injectUser(Workload.scala:64)
        at io.gatling.core.controller.inject.open.OpenWorkload.$anonfun$injectBatch$1(OpenWorkload.scala:35)
        at io.gatling.core.controller.inject.open.OpenWorkload.$anonfun$injectBatch$1$adapted(OpenWorkload.scala:35)
        at io.gatling.core.controller.inject.open.UserStream.withStream(UserStream.scala:58)
        at io.gatling.core.controller.inject.open.OpenWorkload.injectBatch(OpenWorkload.scala:35)
        at io.gatling.core.controller.inject.Injector.$anonfun$inject$1(Injector.scala:60)
        at io.gatling.core.controller.inject.Injector.$anonfun$inject$1$adapted(Injector.scala:59)
        at scala.collection.Iterator.foreach(Iterator.scala:941)
        at scala.collection.Iterator.foreach$(Iterator.scala:941)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
        at scala.collection.MapLike$DefaultValuesIterable.foreach(MapLike.scala:213)
        at io.gatling.core.controller.inject.Injector.io$gatling$core$controller$inject$Injector$$inject(Injector.scala:59)
        at io.gatling.core.controller.inject.Injector$$anonfun$1.applyOrElse(Injector.scala:92)
        at io.gatling.core.controller.inject.Injector$$anonfun$1.applyOrElse(Injector.scala:82)
        at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:38)
        at akka.actor.FSM.processEvent(FSM.scala:684)
        at akka.actor.FSM.processEvent$(FSM.scala:681)
        at io.gatling.core.controller.inject.InjectorFSM.processEvent(InjectorFSM.scala:37)
        at akka.actor.FSM.akka$actor$FSM$$processMsg(FSM.scala:678)
        at akka.actor.FSM$$anonfun$receive$1.applyOrElse(FSM.scala:672)
        at akka.actor.Actor.aroundReceive(Actor.scala:517)
        at akka.actor.Actor.aroundReceive$(Actor.scala:515)
        at io.gatling.core.akka.BaseActor.aroundReceive(BaseActor.scala:24)
        at akka.actor.ActorCell.receiveMessage(ActorCell.scala:588)
        at akka.actor.ActorCell.invoke(ActorCell.scala:557)
        at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:258)
        at akka.dispatch.Mailbox.run(Mailbox.scala:225)
        at akka.dispatch.Mailbox.exec(Mailbox.scala:235)
        at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
        at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
        at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
        at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
16:40:28.359 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.action.Exit - End user #1
16:40:28.360 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Start user #1
16:40:28.363 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Injecting 4 users in scenario my-api, continue=true
16:40:28.364 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.Injector - End user #1
16:40:29.347 [GatlingSystem-akka.actor.default-dispatcher-2] DEBUG io.gatling.core.controller.inject.open.OpenWorkload - Injecting 0 users in scenario my-api, continue=true
16:40:29.373 [GatlingSystem-akka.actor.default-dispatcher-2] ERROR com.intuit.karate.gatling.KarateAction - 'classpath:org/mycompany/karate/tests/myAPI.feature@test=myTag' crashed on session Session(my-api,2,1558395629372,Map(),0,OK,List(),io.gatling.core.protocol.ProtocolComponentsRegistry$$Lambda$329/1759250827@7cee98de), forwarding to the next one

如果您在此处添加用户,则请勿忘记,将用户添加到表单的字段中,例如:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'uploads/{0}/{1}'.format(instance.user.username, filename)


class UploadReports(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    xls = models.FileField(upload_to=user_directory_path)

将字段添加到表单后,模板表单中将出现一个新字段,其中包含可能的用户列表。就像大多数人可能不喜欢的那样,我不希望表单包含用户。因此,如class DocumentForm(forms.ModelForm): class Meta: model = UploadReports fields = ('xls', 'user') 所述,您必须ilja这样的表格:

exclude

一旦排除了表单,它将返回抛出该用户不存在的错误。因此,您需要像这样在class DocumentForm(forms.ModelForm): class Meta: model = UploadReports fields = ('xls', 'user') exclude = ('user', ) # make sure this is a tuple 的{​​{1}}方法中添加用户:

post

这不是一件容易的事,但完成后却是有收获的!