I am trying to implement a registration key in the registration form which the user has to input to be able to create an account. In my users model, I have a key field which is the foreign key of the Key model. The relation looks like this
class RegistrationKey(models.Model):
key = models.CharField(max_length=30)
class User(AbstractUser):
...
key = models.ForeignKey(RegistrationKey, on_delete=models.CASCADE, null=True, blank=True)
I have tried to validate the input like this in the view
def registerPage(request):
form = MyUserCreationForm()
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
key_input = request.POST.get('key')
...
if RegistrationKey.objects.filter(key_input=key).exists() and form.is_valid():
user = form.save(commit=False)
user.key.add('key_input')
...
user.save()
In my form have I set the key field as a CharField as I can not display the keys for the user. This means that the user inputs a string but django needs an instance to be able to save it to the database. I don't know how to implement this. Is there any way to convert a string to an instance or is there a better way to query the the database, to check and see if the input is a valid key?
CodePudding user response:
def registerPage(request):
form = MyUserCreationForm()
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
if form.is_valid():
key_input = form.cleaned_data['key_input']
registration_key_object = RegistrationKey.objects.get(
key=key_input)
user.key = registration_key_object
user.save()
...
if you have a string(your_key) and you need object(RegistrationKey)
simply get it
reigstration_key_object = RegistrationKey.objects.get(key=your_key)
CodePudding user response:
There are multiple approach to implement this
Approach 1:
def registerPage(request):
form = MyUserCreationForm()
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
key_input = request.POST.get('key')
registration_key = RegistrationKey.objects.filter(key_input=key_input)
if Rregistration_key.exists() and form.is_valid():
registration_key = registration_key.first()
user = form.save(commit=False)
user.key = registration_key
user.save()
Approach 2:
def registerPage(request):
form = MyUserCreationForm()
if request.method == 'POST':
form = MyUserCreationForm(request.POST)
key_input = request.POST.get('key')
if form.is_valid():
try:
registration_key = RegistrationKey.objects.get(key_input=key_input)
except RegistrationKey.DoesNotExist:
pass
# raise your exception here
user = form.save(commit=False)
user.key = registration_key
user.save()