Here I've two models first one is Contact and second model is Sent_replies. So, what should I do in views.py so that If anyone send response in Contact, the data will also update in the Sent_replies model
models.py
class Contact(models.Model):
message_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
phone = models.CharField(max_length=100)
comment = models.TextField(max_length=100)
date = models.DateField()
def __str__(self):
return self.name
class Sent_replies(models.Model):
message_sender = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True)
def __str__(self):
return self.message.name
views.py
def contact(request):
if request.method == "POST":
name = request.POST.get("name")
email = request.POST.get("email")
phone = request.POST.get("phone")
comment = request.POST.get("comment")
if name != "":
contact = Contact(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
contact.save()
messages.success(request, 'Your response has been submitted successfully!!!')
return render(request, 'contact.html')
CodePudding user response:
there are way of doing this, logic in your view only or create a signal to handle it.
logic in your views.py:
if name != "":
contact = Contact.objects.create(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
Sent_replies.objects.create(message_sender=contact)
Using signal in your models.py file
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Contact)
def add_reply(sender, instance, created, **kwargs):
if created == True:
Sent_replies.objects.create(message_sender=instance)