2

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?

user993563
  • 18,601
  • 10
  • 42
  • 55

2 Answers2

1

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.

Matt Seymour
  • 8,880
  • 7
  • 60
  • 101
0
  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.
DrTyrsa
  • 31,014
  • 7
  • 86
  • 86
  • please elaborate more, i could not comprehend it, if you have tutorials/posts/links that explain steps please post them here. Thanks – user993563 Mar 03 '12 at 12:39
  • @user993563 What exactly seems difficult here? – DrTyrsa Mar 03 '12 at 14:59
  • 1. get him a cookie with id of created model. 2. make user FK not reqd?? does it mean that the user model should not be foreign keyed?? i am kind of intermediate with django, hence please elaborate thanks. – user993563 Mar 04 '12 at 07:01
  • @user993563 [1](https://docs.djangoproject.com/en/dev/topics/http/sessions/#examples), 2 `ForeignKey('auth.User', blank=True, null=True)` If something is unclear feel, free to ask. – DrTyrsa Mar 05 '12 at 07:12
  • I have no way to say if an anonymous user is not registered yet or just not logged in yet and already has an account. So I need to check at login if the user has the object reference in session / cookie. I don't understand your point 3: when do you check the user's session? Login time seems to be appropriate but I don't know how to do it, I couldn't find any signal. I don't get your point number 2, did you mean 'if not request.user.is_authenticated()'? – Bastian Jul 25 '12 at 14:20