开发者

How do I save a Django Model from request.POST?

I'm trying to save a new object from a django model using a POST data querydict. This is part of a PISTON handler. I've seen this done in numerous examples, but I just can't get it to work.

Here is my code:

class FestHandler(BaseHandler):
    model = Deal

    def create(self, request):
        """
        Creates a new fest.
        """
        attrs = self.flatten_dict(request.POST)
        postcopy = request.POST.copy()
        if self.exists(**attrs):
            return rc.DUPLICATE_ENTRY
        else:
            loc = Location.objects.get(pk=attrs['location'])
            postcopy['location'] = loc
            fest = Fest(postcopy)
            fest.save()
            return fest

Here is the error I receive every time:

Exception was: int() argument must be a string or a number, not 'QueryDict'

I realize what the error means, so basically I am asking how I can save a new "Fest" by passing in the whole POST dictionary without having to type in the keys manually every time like this:

loc = Location.objects.get(pk=attrs['location'])
fest开发者_开发知识库 = Fest(
    location=loc,
    name=attrs['name'],
    description=attrs['description'],
    details=attrs['details'],
)

Thanks for your help!


First, I think you'll be happier of you explicitly make your PK's into integers.

        loc = Location.objects.get(pk=int(attrs['location']))

Second, you should use a Form.

  1. It validates the fields for you.

  2. It will create the Model object from the Form object.

Read this. http://docs.djangoproject.com/en/1.2/topics/forms/modelforms/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜