Answer the question
In order to leave comments, you need to log in
How to store objects in related models in Django?
I need to register a user, but when he registers, an entry must first be created in another model (Project) and the user must be bound (ForeignKey) to this entry. I decided that in the form_valid method I would select the maximum id value from the Project, add one to it and then create the record I need in the Project + Bind User by project_id + 1
class Registration(FormView):
template_name = 'profile/registration.html'
form_class = RegistrationForm
success_url = 'cabinet:main'
def form_valid(self, form):
self.object = form.save(commit=False)
qs = models.Project.objects.all().aggregate(Max('id'))
project_id = (qs['id__max']) + 1
project = models.Project(
id=project_id,
project_name='Новый проект',
)
project.save()
self.object.project = project_id #PrimaryKey
self.object = form.save()
messages.success(self.request, 'Вы успешно зарегестрированы')
return super().form_valid(form)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question