Barburka
Barburka

Reputation: 465

Do some stuff before saving form with CreateView

I want to populate GenericIPAddress Field before saving an instance in CreateView. It has to be done in View not in Form Class, because of access to request variable. Can I do that? Which method I had to override and how? Code I'm working with:

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

Upvotes: 1

Views: 113

Answers (2)

Sumeet Kumar
Sumeet Kumar

Reputation: 1019

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())

I am using your code as a reference to tell you how you can access request in form_valid. for more usage refer to this article here

Upvotes: 2

typae
typae

Reputation: 23

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/

Upvotes: 0

Related Questions