user993563
user993563

Reputation: 19421

Saving django model forms data before user signs up

I am using django model forms, the form can be filled even by users who have not signed up, but the submission requires the user being signed up. Here is my models:

class Study(model.Model):
    marksobtained = models.CharField(max_length=5)
    highestmarks = models.CharField(max_length=5)
    teacher = models.CharField(max_length=300)

class StudyForm():
   some customisation stuff. 

and then the views.py

form = StudiesForm(request.POST or None,
                       instance=id and Studies.objects.get(id=id))
if form.is_valid():
      form.save()
      return render(request, 'calculate.html', {'detail': ret_dict, 'amt': amt})
      else:
          return render(request, 'forms.html', {'form':form})
    else:
          return render(request, 'forms.html', {'form':form})

Donot bother about the indentation and other stuff in views, this is just a model of what i am trying to do, as can be seen any anonymous user can submit the form as of now, i want it to further modify, as when an anonymous user submits the form, he should first be signed up and then his data should be added to the models.

How can this be implemented?

Upvotes: 2

Views: 253

Answers (2)

DrTyrsa
DrTyrsa

Reputation: 31981

  1. Make user FK not required. Save model.
  2. If request.user.is_authenticated() get him a cookie with id of created model. Redirect him on login page.
  3. For each user check if there is a cookie with model id, attach user to model, save.

Upvotes: 0

Matt Seymour
Matt Seymour

Reputation: 9415

If the user is not authenticated then save the form data to session.

Then log the user in the system.

Then pull the form data out of the session and save the information taking the authenticated users information.

Upvotes: 1

Related Questions