I'm trying to build a profile page, where a User
can fill in the Teacher
model.
My Teacher model, model.py
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher')
rate = models.CharField(max_length=200)
availability = models.BooleanField(default=False)
forms.py
class TeacherCreate(CreateView):
user_id = request.user.id #INCORRECT! Needs something to remember current user id.
model = Teacher
fields = ['rate','availability']
EDIT: I've also attempted adding:
def form_valid(self, form):
form.instance.user = self.request.user
return super(TeacherCreate, self).form_valid(form)
We don't allow the user to change his ID in this create view. In fact, I believe this should be the current users id, user_id
which is given by request.user.id
.
teacher_form.html
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<span color="red">{{ field.errors }}</span>
<label>
{{ field.label_tag }}
</label>
<div>{{ field }}</div>
</div>
{% endfor %}
<button type="submit">Submit</button>
</form>
Now the problem is that when I run it, I get the error:
NOT NULL constraint failed: users_teacher.user_id
which I believe is because I didn't specify the user_id.
How I'd like it to work:
First, check if the teacher already has a record in the database. E.G. if there is a row in the Teacher table, with user_id=current user.
If the teacher has a profile -> Call the update view.
If the teacher doesn't have a profile -> Use create view.