Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass current user to initial for CreateView in Django

Tags:

python

django

In my project I have User model from standard auth Django model and the Todo model. User can have many Todo.

When signed in user creates a todo he must be assigned to the todo automatically. I want to pass current user to initial data of the CreateView. It seems to me that I'm on right way. This is how the form object looks:

class TodoView(CreateView):
  model = Todo
  fields = ('name', 'date')

  success_url = '/todos/'

  def get_initial(self):
    return {
      'user': self.request.user
    }

And this is a model:

class Todo(models.Model):
  user = models.ForeignKey(User)
  name = models.TextField()
  date = models.DateField()

But it seems that that's not enough because I have an exception when the valid data goes from the client side. This is the exception:

IntegrityError at /todos/new

todos_todo.user_id may not be NULL

Request Method:     POST
Request URL:    http://localhost:8000/todos/new
Django Version:     1.6.2
Exception Type:     IntegrityError
Exception Value:    

todos_todo.user_id may not be NULL

Exception Location:     /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 450
Python Executable:  /usr/bin/python
Python Version:     2.7.5

Is that possible at all to pass the current user to the model of the CreateView? How to do it in best practice in the Django?

like image 950
ka8725 Avatar asked Dec 09 '22 09:12

ka8725


1 Answers

You need to use the form_valid method instead of get_initial. Something like this:

def form_valid(self, form):
    form.instance.user = self.request.user
    return super(TodoView, self).form_valid(form)

I have never used get_initial, but I guess it doesn't do anything because you don't include the user field. That wouldn't be useful anyway, because you don't want the user to be able to change the value.

like image 51
Paulo Almeida Avatar answered Dec 11 '22 09:12

Paulo Almeida