Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle views.py after joining two models in Django?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading