1
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.
Source:stackexchange.com