S
S
Serj B2018-09-03 21:29:21
Django
Serj B, 2018-09-03 21:29:21

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)

As a result, it gives me an error:
Cannot assign "9": "Profile.project" must be a "Project" instance.
at the same time, an entry is created in model.Project, but the function does not see it.
How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tema_sun, 2018-09-03
@Serj-B

It is necessary to transfer not PK, but an object instance.
self.object.project = project

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question