user registration is working after the local server is restarting

Hello there , I have Document Management system that working as follow :
1st the admin register the roles in the following code


def create_types(request):
    print("Create Types:", request._messages)
    if not request.user.is_staff:
        return redirect('signin')
    else:
        form = TypeForm()
        #message_msgs.success(request, 'Type is Created!')
        if request.method == 'POST':
            form = TypeForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                try:
                    Type.objects.get(type_name=cd['type_name'])
                except:
                    role = Type.objects.create(type_name=cd['type_name'])
                    role.save()
                    messages.success(request, 'Type is Successfully Created!')
                    return redirect('displaytypes')
                error = f"{cd['type_name']} is already registered"
    user = User.objects.get(id=request.user.id)
    msg_ntf = message_notification(request)
    notifications = msg_ntf['notifications']
    message_msgs = msg_ntf['message_msgs']
    if MyProfile.objects.filter(profile_user_id=user.id):
        profile = MyProfile.objects.get(profile_user_id=user.id)
    else:
        profile = MyProfile.objects.filter(profile_user_id=user.id)
    return render(request, 'create-role.html', {'forms': form, 'profile': profile, 'message_msgs': message_msgs})

2nd the admin create office for each roles the code is here

def create_offices(request, type_id):

    if not request.user.is_staff:
        return redirect('signin')
    else:
        msg_ntf = message_notification(request)
        notifications = msg_ntf['notifications']
        message_msgs = msg_ntf['message_msgs']
        form = OfficeForm()
        type_name = Type.objects.get(type_id=type_id)
        if request.method == 'POST':
            form = OfficeForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data

                try:
                    Office.objects.get(
                        office_name=cd['office'])
                except:
                    office = Office.objects.create(
                        office_type_name_id=type_id, office_name=cd['office'])
                    office.save()
                    messages.success(request, 'Office is Successfully Edited!')
                    redirect('displayoffices', type_id=type_id)
                error = f"{cd['office']} is already registered"

        user = User.objects.get(id=request.user.id)
        if MyProfile.objects.filter(profile_user_id=user.id):
            profile = MyProfile.objects.get(profile_user_id=user.id)
        else:
            profile = MyProfile.objects.filter(profile_user_id=user.id)
        return render(request, 'create-office.html', {'forms': form, 'profile': profile, 'type_id': type_id, 'message_msgs': message_msgs, 'type_name': type_name})

3rd the admin can create for each office under the specific roles ,the code is here

def create_users(request):
    ty = Type.objects.all()
    off = Office.objects.all()
    user = User.objects.all()

    if not request.user.is_staff:
        return redirect('signin')
    else:
        error = ""
        form = SignUPForm()
        form.fields['type_name'].choices = get_type()
        if request.method == "POST":
            print(request.POST)
            form = SignUPForm(request.POST)
            if form.is_valid():
                off_id = Office.objects.get(office_name=request.POST['state'])
                print(off_id)
                selected_office = request.POST['state']
                cd = form.cleaned_data
                username = f"{cd['first_name']}.{cd['last_name']}"
                while True:
                    try:
                        User.objects.get(username=username)
                        username += '1'
                    except User.DoesNotExist:
                        cd['username'] = username
                        break
                cd['password'] = cd['username']
                cd['office_id'] = off_id.office_id


                del cd['submit']
                del cd['type_name']
                u = User.objects.create_user(**{i: cd[i] for i in cd})
                u.save()
                messages.success(request, f'User is Successfully Created! username is {username}')
                return redirect('user')
            else:
                error = 'Please enter valid information'
        user = User.objects.get(id=request.user.id)
        if MyProfile.objects.filter(profile_user_id=user.id):
            profile = MyProfile.objects.get(profile_user_id=user.id)
        else:
            profile = MyProfile.objects.filter(profile_user_id=user.id)
        msg_ntf = message_notification(request)
        notifications = msg_ntf['notifications']
        message_msgs = msg_ntf['message_msgs']
        return render(request, 'create-users.html', {'forms': form, 'profile': profile, 'error': error, 'message_msgs': message_msgs})

But when I tray to register the user after the registration of role and office , the error " ‘Please enter valid information’" is coming and when i restart the local server it working fine , I dont know why it is now working correctly? any one who can help me please ???

What is this get_type function being referenced here?

You’re creating the form in the line above this, but then in your POST section of the view you’re creating the form again - this time with the request.POST data, but you’re not updating the form with the choices.

My initial reaction is that you’re doing something in get_type that isn’t being properly initialized except for when the app is started.

1 Like

the get_type function is here :

def get_type():
    """ GET Type SELECTION """
    all_countries = [('-----', '---Select a Type---')]
    all_data = [type_name.type_name for type_name in Type.objects.all().exclude(
        type_name='admin')]
    #print("all_data", all_data)
    for x in all_data:
        y = (x, x)
        all_countries.append(y)
    return all_countries

it is used to choose the role of the user from the reigsterd roles …type_name is role in code

What does your SignUPForm look like?

It looks LIke


class SignUPForm(forms.Form):
    first_name = formGenerator('text', 'user', 'First Name')
    last_name = formGenerator('text', 'user', 'Last Name')
    type_name = forms.ChoiceField(choices=get_type(),
                                  widget=forms.Select(
                                      attrs={'class': 'form-control', 'id': 'id_type'}),
                                  label='Select User Type'
                                  )
    submit = formGenerator('submit', value="Save User")

Yes, the issue is that by using the results of a function in the choices attribute of the field definition, this is evaluated once, when the class is loaded. It doesn’t change as entries are added to the model.

Note that you can pass the callable to choices instead of the function results. See the docs at choices.

1 Like

Thank you for your answer , but the docs are not enough for me to understand , how can I use the callable to choices instead of the function In my case?

get_type is the callable.

get_type() calls the function and returns a result.

1 Like

Thank so much for your time sir!!