Исправление ошибки RelatedObjectDoesNotExist в /agents/ в django

Я создаю сайт CRM на django, но у меня возникла проблема, когда я хочу связать пользователя с организацией.

Примечание : пользователь должен войти в систему, чтобы иметь возможность создать агента

model.py

class User(AbstractUser):
    pass

class UserProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)# every USER has one profile
    
    def __str__(self):
        return self.user.username

class Agent(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)# every agent has one user
    organisation = models.ForeignKey(UserProfile,on_delete=models.CASCADE)
    
    def __str__(self):
        return self.user.email

    # create signal to listen to event in order to create a profile user once a new user is created.
def post_user_created_signal(sender,instance,created,**kwargs):
    if created:
        UserProfile.objects.create(user = instance)

post_save.connect(post_user_created_signal,sender=User)

views.py

class AgentCreateView(LoginRequiredMixin, generic.CreateView)
    template_name = "agent_create.html"
    form_class = AgentModelForm

    def get_success_url(self):
        return reverse("agents:agent-list")

    def form_valid(self, form):
        agent = form.save(commit=False)
        agent.organisation = self.request.user.userprofile
        agent.save()
        return super(AgentCreateView, self).form_valid(form)

Когда пользователь пытается создать агента, появляется следующая ошибка.

RelatedObjectDoesNotExist в /agents/

User has no userprofile.

Метод запроса: GET URL запроса: http://127.0.0.1:8000/agents/. Django Version: 4.0.6 Тип исключения: RelatedObjectDoesNotExist Значение исключения:

У пользователя нет профиля пользователя.

Местоположение исключения: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_descriptors.py, line 461, in get Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python.exe Версия Python: 3.10.4 Python Path:

.

['F:\DJANGO', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\LT GM\AppData\Local\Programs\Python\Python310', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib', 'C:\Users\LT ' 'GM\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin']

.

Время сервера: Sun, 17 Jul 2022 18:54:40 +0000

Строка проблемы находится здесь:

agent.organisation = self.request.user.userprofile

У self.request.user еще нет userprofile.

Возможно, вам нужно изменить логику в вашем коде.

Вернуться на верх