0

My model Resume has a user field as foreign key:

class Resume(models.Model):
    name = models.CharField(max_length=25)
    base_info = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    User = get_user_model()
    superuser = User.objects.get(username=<superuser_username>)
    user = models.ForeignKey(User, on_delete=models.CASCADE,
                             default=superuser.id)

(Set default as superuser since I added that after some migrations and it is working right.)

I want to set the user field automatically login user where the new ResumeForm saved.

I think saving the user in view is better than in template but following doesn't work:

def resume_form(request):
    if request.method == 'POST':
        form = ResumeForm(request.POST, request.FILES)
        form.user = request.user
        if form.is_valid():
            resume = form.save()
            return redirect('resume:list')
    else:
        form = ResumeForm()
    return render(request, 'resume/index.html', {
        'form': form,
    })

How can I do that?

+) Where is the proper part to save(set) user, in view or template? (or any other can access to user context?)

홍한석
  • 439
  • 7
  • 21
  • 1
    This has been answered many many many times before. – Daniel Roseman Feb 07 '18 at 16:20
  • Note, you must not do queries at class level like you do to get the superuser ID in your model. Remove that code to a function and use the callable as the default. – Daniel Roseman Feb 07 '18 at 16:21
  • Sorry for duplication. Btw, the second comment means `user = models.ForeignKey(User, on_delete=models.CASCADE, default= get_user_model().objects.get(username=).id)` or make a new function like `get_superuser_id()`? (or you mean [`select_related()`](https://docs.djangoproject.com/en/2.0/ref/models/querysets/#select-related)?) And would you remind to notice me the documentation on that? (Guessing it's about performance) – 홍한석 Feb 07 '18 at 17:39

0 Answers0