开发者

Method to create a model instance based on a request object

I have a model like this:

class UserSubmission(models.Model):
    mantra = models.CharField(max_length=64)
    ip = models.CharField(max_length=15) # xxx.xxx.xxx.xxx

I want to create a function like so:

def create_submission(request, mantra):
    s = UserSubmission(mantra=mantra)
    ip_meta_entry = 'HTTP_X_REAL_IP' in request.META and 'HTTP_X_REAL_IP' or 'REMOTE_ADDR'
    s.ip = request.META[ip_meta_entry]
    s.save()
    return s

Note: The above is purely for demonstration purposes and not exactly what I'm doing but I digress...

Where would be the ideal place t开发者_如何学运维o put a function like so? Class method on the model? In the manager? What would be best practice.


I tend to put functions that use request in views.py. Aside from error checking, your code should work fine.

def create_submission(request, mantra):
    ip_meta_entry = 'HTTP_X_REAL_IP' in request.META and 'HTTP_X_REAL_IP' or 'REMOTE_ADDR'
    s = UserSubmission(
        mantra=mantra,
        ip=request.META[ip_meta_entry])
    s.save()
    return s
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜