We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
User creation not working
### Describe the Bug
<!-- A clear and concise description of what the bug is. -->
Due to a problem in the user form's logging, an error occurs when new users are created and a new role is assigned in the creation process

### Steps to Reproduce

1. Go to the user management
2. Create new user and select at least one role
4. See error

### Expected Behavior
<!-- A clear and concise description of what you expected to happen. -->
The user including a corresponding user profile should be created

### Actual Behavior
<!-- A clear and concise description of what actually happened. -->
An error occurs and the user is created without a user profile
```
RelatedObjectDoesNotExist at /augsburg/users/new

User has no profile.
```
### Additional Information
<!-- Add any other context (e.g. logs, screenshots, etc.) about the problem here. -->

<details>

Environment:


Request Method: POST
Request URL: http://localhost:8000/augsburg/users/new

Django Version: 3.1.8
Python Version: 3.7.10
Installed Applications:
['cms.apps.CmsConfig',
 'gvz_api.apps.GvzApiConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.messages',
 'django.contrib.sessions',
 'django.contrib.sitemaps',
 'django.contrib.staticfiles',
 'corsheaders',
 'widget_tweaks',
 'easy_thumbnails',
 'filer',
 'mptt',
 'rules.apps.AutodiscoverRulesConfig']
Installed Middleware:
['corsheaders.middleware.CorsMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'cms.middleware.timezone_middleware.TimezoneMiddleware']



Traceback (most recent call last):
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/src/cms/decorators.py", line 53, in wrap
    return function(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 85, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "/home/timo/job/integreat/integreat-cms/src/cms/views/users/region_user_view.py", line 100, in post
    user = region_user_form.save()
  File "/home/timo/job/integreat/integreat-cms/src/cms/forms/users/user_form.py", line 96, in save
    logger.info("%r was assigned to %r", role, user.profile)
  File "/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 424, in __get__
    self.related.get_accessor_name()

Exception Type: RelatedObjectDoesNotExist at /augsburg/users/new
Exception Value: User has no profile.

</details>

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/cms/forms/users/user_form.py`
Content:
```
1 import logging
2 
3 from django import forms
4 from django.contrib.auth import get_user_model
5 from django.contrib.auth.models import Group as Role
6 from django.contrib.auth.password_validation import (
7     validate_password,
8     password_validators_help_texts,
9 )
10 from django.utils.translation import ugettext_lazy as _
11 
12 
13 from ..custom_model_form import CustomModelForm
14 
15 logger = logging.getLogger(__name__)
16 
17 
18 class UserForm(CustomModelForm):
19     """
20     Form for creating and modifying user objects
21     """
22 
23     roles = forms.ModelMultipleChoiceField(queryset=Role.objects.all(), required=False)
24     password = forms.CharField(
25         widget=forms.PasswordInput,
26         validators=[validate_password],
27         help_text=password_validators_help_texts,
28     )
29 
30     class Meta:
31         """
32         This class contains additional meta configuration of the form class, see the :class:`django.forms.ModelForm`
33         for more information.
34         """
35 
36         #: The model of this :class:`django.forms.ModelForm`
37         model = get_user_model()
38         #: The fields of the model which should be handled by this form
39         fields = [
40             "username",
41             "first_name",
42             "last_name",
43             "email",
44             "is_staff",
45             "is_active",
46             "is_superuser",
47         ]
48 
49     def __init__(self, data=None, instance=None):
50 
51         # instantiate ModelForm
52         super().__init__(data=data, instance=instance)
53 
54         # check if user instance already exists
55         if self.instance.id:
56             # set initial role data
57             self.fields["roles"].initial = self.instance.groups.all()
58             # don't require password if user already exists
59             self.fields["password"].required = False
60             # adapt placeholder of password input field
61             self.fields["password"].widget.attrs.update(
62                 {"placeholder": _("Leave empty to keep unchanged")}
63             )
64         # fix password label
65         self.fields["password"].label = _("Password")
66 
67     # pylint: disable=signature-differs
68     def save(self, *args, **kwargs):
69         """
70         This method extends the default ``save()``-method of the base :class:`~django.forms.ModelForm` to set attributes
71         which are not directly determined by input fields.
72 
73         :param args: The supplied arguments
74         :type args: list
75 
76         :param kwargs: The supplied keyword arguments
77         :type kwargs: dict
78 
79         :return: The saved user object
80         :rtype: ~django.contrib.auth.models.User
81         """
82 
83         # save ModelForm
84         user = super().save(*args, **kwargs)
85 
86         # check if password field was changed
87         if self.cleaned_data["password"]:
88             # change password
89             user.set_password(self.cleaned_data["password"])
90             user.save()
91 
92         # assign all selected roles which the user does not have already
93         for role in set(self.cleaned_data["roles"]) - set(user.groups.all()):
94             role.user_set.add(user)
95             logger.info("%r was assigned to %r", role, user.profile)
96 
97         # remove all unselected roles which the user had before
98         for role in set(user.groups.all()) - set(self.cleaned_data["roles"]):
99             role.user_set.remove(user)
100             logger.info("The role %r was removed from %r", role, user.profile)
101 
102         return user
103
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/cms/forms/users/user_form.py b/src/cms/forms/users/user_form.py
--- a/src/cms/forms/users/user_form.py
+++ b/src/cms/forms/users/user_form.py
@@ -92,7 +92,10 @@
         # assign all selected roles which the user does not have already
         for role in set(self.cleaned_data["roles"]) - set(user.groups.all()):
             role.user_set.add(user)
-            logger.info("%r was assigned to %r", role, user.profile)
+            if hasattr(user, "profile"):
+                logger.info("%r was assigned to %r", role, user.profile)
+            else:
+                logger.info("%r was assigned to %r", role, user)
 
         # remove all unselected roles which the user had before
         for role in set(user.groups.all()) - set(self.cleaned_data["roles"]):

{"golden_diff": "diff --git a/src/cms/forms/users/user_form.py b/src/cms/forms/users/user_form.py\n--- a/src/cms/forms/users/user_form.py\n+++ b/src/cms/forms/users/user_form.py\n@@ -92,7 +92,10 @@\n         # assign all selected roles which the user does not have already\n         for role in set(self.cleaned_data[\"roles\"]) - set(user.groups.all()):\n             role.user_set.add(user)\n-            logger.info(\"%r was assigned to %r\", role, user.profile)\n+            if hasattr(user, \"profile\"):\n+                logger.info(\"%r was assigned to %r\", role, user.profile)\n+            else:\n+                logger.info(\"%r was assigned to %r\", role, user)\n \n         # remove all unselected roles which the user had before\n         for role in set(user.groups.all()) - set(self.cleaned_data[\"roles\"]):\n", "issue": "User creation not working\n### Describe the Bug\r\n<!-- A clear and concise description of what the bug is. -->\r\nDue to a problem in the user form's logging, an error occurs when new users are created and a new role is assigned in the creation process\r\n\r\n### Steps to Reproduce\r\n\r\n1. Go to the user management\r\n2. Create new user and select at least one role\r\n4. See error\r\n\r\n### Expected Behavior\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nThe user including a corresponding user profile should be created\r\n\r\n### Actual Behavior\r\n<!-- A clear and concise description of what actually happened. -->\r\nAn error occurs and the user is created without a user profile\r\n```\r\nRelatedObjectDoesNotExist at /augsburg/users/new\r\n\r\nUser has no profile.\r\n```\r\n### Additional Information\r\n<!-- Add any other context (e.g. logs, screenshots, etc.) about the problem here. -->\r\n\r\n<details>\r\n\r\nEnvironment:\r\n\r\n\r\nRequest Method: POST\r\nRequest URL: http://localhost:8000/augsburg/users/new\r\n\r\nDjango Version: 3.1.8\r\nPython Version: 3.7.10\r\nInstalled Applications:\r\n['cms.apps.CmsConfig',\r\n 'gvz_api.apps.GvzApiConfig',\r\n 'django.contrib.admin',\r\n 'django.contrib.auth',\r\n 'django.contrib.contenttypes',\r\n 'django.contrib.messages',\r\n 'django.contrib.sessions',\r\n 'django.contrib.sitemaps',\r\n 'django.contrib.staticfiles',\r\n 'corsheaders',\r\n 'widget_tweaks',\r\n 'easy_thumbnails',\r\n 'filer',\r\n 'mptt',\r\n 'rules.apps.AutodiscoverRulesConfig']\r\nInstalled Middleware:\r\n['corsheaders.middleware.CorsMiddleware',\r\n 'django.middleware.security.SecurityMiddleware',\r\n 'django.contrib.sessions.middleware.SessionMiddleware',\r\n 'django.middleware.locale.LocaleMiddleware',\r\n 'django.middleware.common.CommonMiddleware',\r\n 'django.middleware.csrf.CsrfViewMiddleware',\r\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\r\n 'django.contrib.messages.middleware.MessageMiddleware',\r\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\r\n 'cms.middleware.timezone_middleware.TimezoneMiddleware']\r\n\r\n\r\n\r\nTraceback (most recent call last):\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/exception.py\", line 47, in inner\r\n    response = get_response(request)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/core/handlers/base.py\", line 181, in _get_response\r\n    response = wrapped_callback(request, *callback_args, **callback_kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py\", line 70, in view\r\n    return self.dispatch(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py\", line 43, in _wrapper\r\n    return bound_method(*args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py\", line 21, in _wrapped_view\r\n    return view_func(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/utils/decorators.py\", line 43, in _wrapper\r\n    return bound_method(*args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/src/cms/decorators.py\", line 53, in wrap\r\n    return function(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/contrib/auth/mixins.py\", line 85, in dispatch\r\n    return super().dispatch(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/views/generic/base.py\", line 98, in dispatch\r\n    return handler(request, *args, **kwargs)\r\n  File \"/home/timo/job/integreat/integreat-cms/src/cms/views/users/region_user_view.py\", line 100, in post\r\n    user = region_user_form.save()\r\n  File \"/home/timo/job/integreat/integreat-cms/src/cms/forms/users/user_form.py\", line 96, in save\r\n    logger.info(\"%r was assigned to %r\", role, user.profile)\r\n  File \"/home/timo/job/integreat/integreat-cms/.venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py\", line 424, in __get__\r\n    self.related.get_accessor_name()\r\n\r\nException Type: RelatedObjectDoesNotExist at /augsburg/users/new\r\nException Value: User has no profile.\r\n\r\n</details>\n", "before_files": [{"content": "import logging\n\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group as Role\nfrom django.contrib.auth.password_validation import (\n    validate_password,\n    password_validators_help_texts,\n)\nfrom django.utils.translation import ugettext_lazy as _\n\n\nfrom ..custom_model_form import CustomModelForm\n\nlogger = logging.getLogger(__name__)\n\n\nclass UserForm(CustomModelForm):\n    \"\"\"\n    Form for creating and modifying user objects\n    \"\"\"\n\n    roles = forms.ModelMultipleChoiceField(queryset=Role.objects.all(), required=False)\n    password = forms.CharField(\n        widget=forms.PasswordInput,\n        validators=[validate_password],\n        help_text=password_validators_help_texts,\n    )\n\n    class Meta:\n        \"\"\"\n        This class contains additional meta configuration of the form class, see the :class:`django.forms.ModelForm`\n        for more information.\n        \"\"\"\n\n        #: The model of this :class:`django.forms.ModelForm`\n        model = get_user_model()\n        #: The fields of the model which should be handled by this form\n        fields = [\n            \"username\",\n            \"first_name\",\n            \"last_name\",\n            \"email\",\n            \"is_staff\",\n            \"is_active\",\n            \"is_superuser\",\n        ]\n\n    def __init__(self, data=None, instance=None):\n\n        # instantiate ModelForm\n        super().__init__(data=data, instance=instance)\n\n        # check if user instance already exists\n        if self.instance.id:\n            # set initial role data\n            self.fields[\"roles\"].initial = self.instance.groups.all()\n            # don't require password if user already exists\n            self.fields[\"password\"].required = False\n            # adapt placeholder of password input field\n            self.fields[\"password\"].widget.attrs.update(\n                {\"placeholder\": _(\"Leave empty to keep unchanged\")}\n            )\n        # fix password label\n        self.fields[\"password\"].label = _(\"Password\")\n\n    # pylint: disable=signature-differs\n    def save(self, *args, **kwargs):\n        \"\"\"\n        This method extends the default ``save()``-method of the base :class:`~django.forms.ModelForm` to set attributes\n        which are not directly determined by input fields.\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :return: The saved user object\n        :rtype: ~django.contrib.auth.models.User\n        \"\"\"\n\n        # save ModelForm\n        user = super().save(*args, **kwargs)\n\n        # check if password field was changed\n        if self.cleaned_data[\"password\"]:\n            # change password\n            user.set_password(self.cleaned_data[\"password\"])\n            user.save()\n\n        # assign all selected roles which the user does not have already\n        for role in set(self.cleaned_data[\"roles\"]) - set(user.groups.all()):\n            role.user_set.add(user)\n            logger.info(\"%r was assigned to %r\", role, user.profile)\n\n        # remove all unselected roles which the user had before\n        for role in set(user.groups.all()) - set(self.cleaned_data[\"roles\"]):\n            role.user_set.remove(user)\n            logger.info(\"The role %r was removed from %r\", role, user.profile)\n\n        return user\n", "path": "src/cms/forms/users/user_form.py"}], "after_files": [{"content": "import logging\n\nfrom django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group as Role\nfrom django.contrib.auth.password_validation import (\n    validate_password,\n    password_validators_help_texts,\n)\nfrom django.utils.translation import ugettext_lazy as _\n\n\nfrom ..custom_model_form import CustomModelForm\n\nlogger = logging.getLogger(__name__)\n\n\nclass UserForm(CustomModelForm):\n    \"\"\"\n    Form for creating and modifying user objects\n    \"\"\"\n\n    roles = forms.ModelMultipleChoiceField(queryset=Role.objects.all(), required=False)\n    password = forms.CharField(\n        widget=forms.PasswordInput,\n        validators=[validate_password],\n        help_text=password_validators_help_texts,\n    )\n\n    class Meta:\n        \"\"\"\n        This class contains additional meta configuration of the form class, see the :class:`django.forms.ModelForm`\n        for more information.\n        \"\"\"\n\n        #: The model of this :class:`django.forms.ModelForm`\n        model = get_user_model()\n        #: The fields of the model which should be handled by this form\n        fields = [\n            \"username\",\n            \"first_name\",\n            \"last_name\",\n            \"email\",\n            \"is_staff\",\n            \"is_active\",\n            \"is_superuser\",\n        ]\n\n    def __init__(self, data=None, instance=None):\n\n        # instantiate ModelForm\n        super().__init__(data=data, instance=instance)\n\n        # check if user instance already exists\n        if self.instance.id:\n            # set initial role data\n            self.fields[\"roles\"].initial = self.instance.groups.all()\n            # don't require password if user already exists\n            self.fields[\"password\"].required = False\n            # adapt placeholder of password input field\n            self.fields[\"password\"].widget.attrs.update(\n                {\"placeholder\": _(\"Leave empty to keep unchanged\")}\n            )\n        # fix password label\n        self.fields[\"password\"].label = _(\"Password\")\n\n    # pylint: disable=signature-differs\n    def save(self, *args, **kwargs):\n        \"\"\"\n        This method extends the default ``save()``-method of the base :class:`~django.forms.ModelForm` to set attributes\n        which are not directly determined by input fields.\n\n        :param args: The supplied arguments\n        :type args: list\n\n        :param kwargs: The supplied keyword arguments\n        :type kwargs: dict\n\n        :return: The saved user object\n        :rtype: ~django.contrib.auth.models.User\n        \"\"\"\n\n        # save ModelForm\n        user = super().save(*args, **kwargs)\n\n        # check if password field was changed\n        if self.cleaned_data[\"password\"]:\n            # change password\n            user.set_password(self.cleaned_data[\"password\"])\n            user.save()\n\n        # assign all selected roles which the user does not have already\n        for role in set(self.cleaned_data[\"roles\"]) - set(user.groups.all()):\n            role.user_set.add(user)\n            if hasattr(user, \"profile\"):\n                logger.info(\"%r was assigned to %r\", role, user.profile)\n            else:\n                logger.info(\"%r was assigned to %r\", role, user)\n\n        # remove all unselected roles which the user had before\n        for role in set(user.groups.all()) - set(self.cleaned_data[\"roles\"]):\n            role.user_set.remove(user)\n            logger.info(\"The role %r was removed from %r\", role, user.profile)\n\n        return user\n", "path": "src/cms/forms/users/user_form.py"}]}