Reputation: 16469
I am trying to create a model form in Django. This form has inputs for first_name, last_name, email, and contact_request.
I have two models:
from django.db import models
class User(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
# phone_number =
email = models.EmailField()
def __str__(self):
return self.first_name + " " + self.last_name
class Meta:
db_table = "home_users"
class ContactRequest(models.Model):
user = models.ForeignKey(User)
message = models.TextField(max_length=500)
datetime_created = models.DateTimeField("Date/time created")
class Meta:
db_table = "home_contactrequests"
In my form, upon submission, because there is a OneToMany relationship between Users
and ContactRequests
, a new row will be added to both home_users
and home_contactrequests
when there is a new email submitted through the form. If the email exists in the home_users
table, then a new row will only be added to home_contactrequests
with it's foreign key referencing a user.id
I'm not quite sure how to implement this right now as I am new to model forms and Django as well. I was wondering if someone could guide me to show me the process and logic involved in creating this type of form.
Upvotes: 0
Views: 45
Reputation: 174614
Use get_or_create
on the User
model to fetch a user if one with that email already exists:
Here is one way you would wire this up in your view:
def some_view(request):
form = SomeForm(request.POST or None)
if form.is_valid():
obj, created = User.objects.get_or_create(email=form.cleaned_data['email'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'])
ContactRequest.objects.create(user=obj,
message=form.cleaned_data['message'],
datetime_created=datetime.datetime.now())
return redirect('/thanks')
return render(request, 'form.html', {'form': form})
You can help yourself a bit by setting the auto_now_add
option for the datetime_created
field; this way your timestamp is automatically saved.
Upvotes: 1