在使用CreateView保存表单之前做一些事情

时间:2018-05-19 18:45:30

标签: python django

我想在CreateView中保存实例之前填充GenericIPAddress字段。由于访问请求变量,必须在View not in Form Class中完成。我能这样做吗?我必须覆盖哪种方法以及如何?代码I使用:

models.py

class Message(models.Model):
    author = models.CharField(max_length=60)
    email = models.EmailField()
    message = models.TextField(max_length=1200)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    is_read = models.BooleanField(default=False)

    def __str__(self):
        return self.author + '/' + self.message[:20]

forms.py

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message
        fields = ['author', 'email', 'message']
        labels = {
            'author': 'Autor',
            'email': 'E-mail',
            'message': 'Wiadomość'
        }

views.py

class SendMessage(CreateView):
    form_class = MessageForm
    template_name = 'blog/send_message.html'

    def post(self, request, *args, **kwargs):
        result = super(SendMessage, self).post(request, *args, **kwargs)
        ip, is_routable = get_client_ip(request)
        if ip:
            self.fields['ip_address'] = ip  #I do it wrong
        return result

2 个答案:

答案 0 :(得分:2)

def form_valid(self,form):
        super(SendMessage, self).form_valid(form)
        ip, is_routable = get_client_ip(self.request)
        if ip:
            self.fields['ip_address'] = ip       
        return HttpResponseRedirect(self.get_success_url())

我使用您的代码作为参考,告诉您如何在form_valid中访问request。 有关更多用法,请参阅本文here

答案 1 :(得分:0)

from django.db.models.signals import pre_save
from django.dispatch import receiver
from app.models import Message


@receiver(pre_save, sender=Message)
def some_signal(sender, **kwargs):
    # populate GenericIPAddress Field

https://docs.djangoproject.com/en/2.0/topics/signals/