Create a form to activate user permission





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







2















I want a django form which is an instance of a User and get an html form as constitued by radio buttons to activate or deactivate a permission.



A html code of this kind is expected at the end:



<div class="form-group">
<label for="change_user">Can edit user:</label>
<div class="labeled" id="change_user">
<input class="with-gap" name="change_user_False" type="radio" id="change_user_False" value="False">
<label for="change_user_False">No</label>
<input class="with-gap" name="change_user_True" type="radio" id="change_user_True" value="True" checked="">
<label for="change_user_True">Yes</label>
</div>
</div>


The example permission here will be "change_user" and the goal is to handle all the process in a clean django form. I do not know what is the most appropriate way...



Use on a simple form and manage everything in the clean function by passing in parameter a User object.



from django import forms

class PermissionForm(forms.Form):
change_user = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'No'), (False, 'Yes')), required=True)

def __init__(self, *args, **kwargs):
self.fields['change_user'].initial = select_user.has_permission('auth.change_user ')

def clean(self, select_user):
if self.cleaned_data['change_user']:
select_user.permissions.add('change_user')


Or use a form of the User instance:



from django.contrib.auth.models import User
from django import forms

class ProfileForm(forms.ModelForm):
class Meta:
model = User
fields =
widget = ...


But how to generate a widget in radioselect on a permission and catch errors when returned data wrong ?










share|improve this question































    2















    I want a django form which is an instance of a User and get an html form as constitued by radio buttons to activate or deactivate a permission.



    A html code of this kind is expected at the end:



    <div class="form-group">
    <label for="change_user">Can edit user:</label>
    <div class="labeled" id="change_user">
    <input class="with-gap" name="change_user_False" type="radio" id="change_user_False" value="False">
    <label for="change_user_False">No</label>
    <input class="with-gap" name="change_user_True" type="radio" id="change_user_True" value="True" checked="">
    <label for="change_user_True">Yes</label>
    </div>
    </div>


    The example permission here will be "change_user" and the goal is to handle all the process in a clean django form. I do not know what is the most appropriate way...



    Use on a simple form and manage everything in the clean function by passing in parameter a User object.



    from django import forms

    class PermissionForm(forms.Form):
    change_user = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'No'), (False, 'Yes')), required=True)

    def __init__(self, *args, **kwargs):
    self.fields['change_user'].initial = select_user.has_permission('auth.change_user ')

    def clean(self, select_user):
    if self.cleaned_data['change_user']:
    select_user.permissions.add('change_user')


    Or use a form of the User instance:



    from django.contrib.auth.models import User
    from django import forms

    class ProfileForm(forms.ModelForm):
    class Meta:
    model = User
    fields =
    widget = ...


    But how to generate a widget in radioselect on a permission and catch errors when returned data wrong ?










    share|improve this question



























      2












      2








      2








      I want a django form which is an instance of a User and get an html form as constitued by radio buttons to activate or deactivate a permission.



      A html code of this kind is expected at the end:



      <div class="form-group">
      <label for="change_user">Can edit user:</label>
      <div class="labeled" id="change_user">
      <input class="with-gap" name="change_user_False" type="radio" id="change_user_False" value="False">
      <label for="change_user_False">No</label>
      <input class="with-gap" name="change_user_True" type="radio" id="change_user_True" value="True" checked="">
      <label for="change_user_True">Yes</label>
      </div>
      </div>


      The example permission here will be "change_user" and the goal is to handle all the process in a clean django form. I do not know what is the most appropriate way...



      Use on a simple form and manage everything in the clean function by passing in parameter a User object.



      from django import forms

      class PermissionForm(forms.Form):
      change_user = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'No'), (False, 'Yes')), required=True)

      def __init__(self, *args, **kwargs):
      self.fields['change_user'].initial = select_user.has_permission('auth.change_user ')

      def clean(self, select_user):
      if self.cleaned_data['change_user']:
      select_user.permissions.add('change_user')


      Or use a form of the User instance:



      from django.contrib.auth.models import User
      from django import forms

      class ProfileForm(forms.ModelForm):
      class Meta:
      model = User
      fields =
      widget = ...


      But how to generate a widget in radioselect on a permission and catch errors when returned data wrong ?










      share|improve this question
















      I want a django form which is an instance of a User and get an html form as constitued by radio buttons to activate or deactivate a permission.



      A html code of this kind is expected at the end:



      <div class="form-group">
      <label for="change_user">Can edit user:</label>
      <div class="labeled" id="change_user">
      <input class="with-gap" name="change_user_False" type="radio" id="change_user_False" value="False">
      <label for="change_user_False">No</label>
      <input class="with-gap" name="change_user_True" type="radio" id="change_user_True" value="True" checked="">
      <label for="change_user_True">Yes</label>
      </div>
      </div>


      The example permission here will be "change_user" and the goal is to handle all the process in a clean django form. I do not know what is the most appropriate way...



      Use on a simple form and manage everything in the clean function by passing in parameter a User object.



      from django import forms

      class PermissionForm(forms.Form):
      change_user = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'No'), (False, 'Yes')), required=True)

      def __init__(self, *args, **kwargs):
      self.fields['change_user'].initial = select_user.has_permission('auth.change_user ')

      def clean(self, select_user):
      if self.cleaned_data['change_user']:
      select_user.permissions.add('change_user')


      Or use a form of the User instance:



      from django.contrib.auth.models import User
      from django import forms

      class ProfileForm(forms.ModelForm):
      class Meta:
      model = User
      fields =
      widget = ...


      But how to generate a widget in radioselect on a permission and catch errors when returned data wrong ?







      python django django-forms






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 3 at 21:31









      Darkaird

      483624




      483624










      asked Jan 3 at 21:18









      BukyBuky

      340115




      340115
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You can resolve your question using Django UpdateView with a ModelForm like this example (See the comments in order to understand what's going on):



          forms.py:



          from django import forms
          from YOUR_APP_NAME import models

          class UserPermissionsForm(forms.ModelForm):
          change_user = forms.ChoiceField(
          widget=forms.RadioSelect,
          choices=[(True, 'Yes'), (False, 'no')],
          required=True # It's required ?
          )

          class Meta:
          model = models.YOUR_MODEL_NAME
          fields = ('change_user',) # I'll use only one field


          views.py:



          from django.views.generic import UpdateView
          from django.urls import reverse_lazy
          from django.contrib import messages
          from django.contrib.auth.models import Permission
          from YOUR_APP_NAME import models, forms


          class UserPermissionView(UpdateView):
          model = models.YOUR_MODEL_NAME
          template_name = 'user_permission.html' # Your template name
          form_class = forms.UserPermissionsForm
          initial = {} # We'll update the form's fields by their initial values

          def get_initial(self):
          """Update the form_class's fields by their initials"""

          base_initial = super().get_initial()
          # Here we'll check if the user has the permission of 'change_user'
          user_has_permission = self.request.user.user_permissions.filter(
          codename='change_user'
          ).first()
          base_initial['change_user'] = True if user_has_permission else False
          return base_initial

          def form_valid(self, form):
          """
          Here we'll update the user's permission based on the form choice:
          If we choose: Yes => Add 'change_user' permission to the user
          No => Remove 'change_user' permission from the user
          """
          change_user = form.cleaned_data['change_user']
          permission = Permission.objects.get(codename='change_user')
          if change_user == 'True':
          self.request.user.user_permissions.add(permission)
          # Use django's messaging framework
          # We'll render the results into the template later
          messages.success(
          self.request,
          'Updated: User [{}] Can change user'.format(self.request.user.username)
          )
          else:
          self.request.user.user_permissions.remove(permission)
          messages.success(
          self.request,
          'Updated: User [{}] Cannot change user'.format(self.request.user.username)
          )
          return super().form_valid(form)

          def get_success_url(self):
          """
          Don't forget to add your success URL,
          basically use the same url's name as this class view
          """
          # Note here, we'll access to the URL based on the user pk number
          return reverse_lazy('user_permissions', kwargs={'pk': self.request.user.pk})


          urls.py:



          from django.urls import path
          from YOUR_APP_NAME import views


          urlpatterns = [
          path(
          'client/<int:pk>/', # Access the view by adding the User pk number
          views.UserPermissionView.as_view(),
          name='user_permissions'
          ),
          ... # The rest of your paths
          ]


          And finally the template:



          user_permissions.html:



          {% if messages %}
          {% for message in messages %}
          {{ message }}
          {% endfor %}
          <br><br>
          {% endif %}

          <div>User: {{ user.username }}</div>
          <form method="POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type='submit'>Submit</button>
          </form>


          And here are some screenshots of the flow of this solution:



          First



          second



          third



          And of course, you can check if the add/remove actions of the permission under the Django Admin Panel.






          share|improve this answer


























          • It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

            – Buky
            Jan 4 at 20:22








          • 1





            try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

            – Chiheb Nexus
            Jan 4 at 22:48











          • I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

            – Buky
            Jan 7 at 18:26













          • Still i didn't get your point. Sorry

            – Chiheb Nexus
            Jan 7 at 20:57












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54029943%2fcreate-a-form-to-activate-user-permission%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          You can resolve your question using Django UpdateView with a ModelForm like this example (See the comments in order to understand what's going on):



          forms.py:



          from django import forms
          from YOUR_APP_NAME import models

          class UserPermissionsForm(forms.ModelForm):
          change_user = forms.ChoiceField(
          widget=forms.RadioSelect,
          choices=[(True, 'Yes'), (False, 'no')],
          required=True # It's required ?
          )

          class Meta:
          model = models.YOUR_MODEL_NAME
          fields = ('change_user',) # I'll use only one field


          views.py:



          from django.views.generic import UpdateView
          from django.urls import reverse_lazy
          from django.contrib import messages
          from django.contrib.auth.models import Permission
          from YOUR_APP_NAME import models, forms


          class UserPermissionView(UpdateView):
          model = models.YOUR_MODEL_NAME
          template_name = 'user_permission.html' # Your template name
          form_class = forms.UserPermissionsForm
          initial = {} # We'll update the form's fields by their initial values

          def get_initial(self):
          """Update the form_class's fields by their initials"""

          base_initial = super().get_initial()
          # Here we'll check if the user has the permission of 'change_user'
          user_has_permission = self.request.user.user_permissions.filter(
          codename='change_user'
          ).first()
          base_initial['change_user'] = True if user_has_permission else False
          return base_initial

          def form_valid(self, form):
          """
          Here we'll update the user's permission based on the form choice:
          If we choose: Yes => Add 'change_user' permission to the user
          No => Remove 'change_user' permission from the user
          """
          change_user = form.cleaned_data['change_user']
          permission = Permission.objects.get(codename='change_user')
          if change_user == 'True':
          self.request.user.user_permissions.add(permission)
          # Use django's messaging framework
          # We'll render the results into the template later
          messages.success(
          self.request,
          'Updated: User [{}] Can change user'.format(self.request.user.username)
          )
          else:
          self.request.user.user_permissions.remove(permission)
          messages.success(
          self.request,
          'Updated: User [{}] Cannot change user'.format(self.request.user.username)
          )
          return super().form_valid(form)

          def get_success_url(self):
          """
          Don't forget to add your success URL,
          basically use the same url's name as this class view
          """
          # Note here, we'll access to the URL based on the user pk number
          return reverse_lazy('user_permissions', kwargs={'pk': self.request.user.pk})


          urls.py:



          from django.urls import path
          from YOUR_APP_NAME import views


          urlpatterns = [
          path(
          'client/<int:pk>/', # Access the view by adding the User pk number
          views.UserPermissionView.as_view(),
          name='user_permissions'
          ),
          ... # The rest of your paths
          ]


          And finally the template:



          user_permissions.html:



          {% if messages %}
          {% for message in messages %}
          {{ message }}
          {% endfor %}
          <br><br>
          {% endif %}

          <div>User: {{ user.username }}</div>
          <form method="POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type='submit'>Submit</button>
          </form>


          And here are some screenshots of the flow of this solution:



          First



          second



          third



          And of course, you can check if the add/remove actions of the permission under the Django Admin Panel.






          share|improve this answer


























          • It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

            – Buky
            Jan 4 at 20:22








          • 1





            try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

            – Chiheb Nexus
            Jan 4 at 22:48











          • I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

            – Buky
            Jan 7 at 18:26













          • Still i didn't get your point. Sorry

            – Chiheb Nexus
            Jan 7 at 20:57
















          0














          You can resolve your question using Django UpdateView with a ModelForm like this example (See the comments in order to understand what's going on):



          forms.py:



          from django import forms
          from YOUR_APP_NAME import models

          class UserPermissionsForm(forms.ModelForm):
          change_user = forms.ChoiceField(
          widget=forms.RadioSelect,
          choices=[(True, 'Yes'), (False, 'no')],
          required=True # It's required ?
          )

          class Meta:
          model = models.YOUR_MODEL_NAME
          fields = ('change_user',) # I'll use only one field


          views.py:



          from django.views.generic import UpdateView
          from django.urls import reverse_lazy
          from django.contrib import messages
          from django.contrib.auth.models import Permission
          from YOUR_APP_NAME import models, forms


          class UserPermissionView(UpdateView):
          model = models.YOUR_MODEL_NAME
          template_name = 'user_permission.html' # Your template name
          form_class = forms.UserPermissionsForm
          initial = {} # We'll update the form's fields by their initial values

          def get_initial(self):
          """Update the form_class's fields by their initials"""

          base_initial = super().get_initial()
          # Here we'll check if the user has the permission of 'change_user'
          user_has_permission = self.request.user.user_permissions.filter(
          codename='change_user'
          ).first()
          base_initial['change_user'] = True if user_has_permission else False
          return base_initial

          def form_valid(self, form):
          """
          Here we'll update the user's permission based on the form choice:
          If we choose: Yes => Add 'change_user' permission to the user
          No => Remove 'change_user' permission from the user
          """
          change_user = form.cleaned_data['change_user']
          permission = Permission.objects.get(codename='change_user')
          if change_user == 'True':
          self.request.user.user_permissions.add(permission)
          # Use django's messaging framework
          # We'll render the results into the template later
          messages.success(
          self.request,
          'Updated: User [{}] Can change user'.format(self.request.user.username)
          )
          else:
          self.request.user.user_permissions.remove(permission)
          messages.success(
          self.request,
          'Updated: User [{}] Cannot change user'.format(self.request.user.username)
          )
          return super().form_valid(form)

          def get_success_url(self):
          """
          Don't forget to add your success URL,
          basically use the same url's name as this class view
          """
          # Note here, we'll access to the URL based on the user pk number
          return reverse_lazy('user_permissions', kwargs={'pk': self.request.user.pk})


          urls.py:



          from django.urls import path
          from YOUR_APP_NAME import views


          urlpatterns = [
          path(
          'client/<int:pk>/', # Access the view by adding the User pk number
          views.UserPermissionView.as_view(),
          name='user_permissions'
          ),
          ... # The rest of your paths
          ]


          And finally the template:



          user_permissions.html:



          {% if messages %}
          {% for message in messages %}
          {{ message }}
          {% endfor %}
          <br><br>
          {% endif %}

          <div>User: {{ user.username }}</div>
          <form method="POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type='submit'>Submit</button>
          </form>


          And here are some screenshots of the flow of this solution:



          First



          second



          third



          And of course, you can check if the add/remove actions of the permission under the Django Admin Panel.






          share|improve this answer


























          • It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

            – Buky
            Jan 4 at 20:22








          • 1





            try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

            – Chiheb Nexus
            Jan 4 at 22:48











          • I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

            – Buky
            Jan 7 at 18:26













          • Still i didn't get your point. Sorry

            – Chiheb Nexus
            Jan 7 at 20:57














          0












          0








          0







          You can resolve your question using Django UpdateView with a ModelForm like this example (See the comments in order to understand what's going on):



          forms.py:



          from django import forms
          from YOUR_APP_NAME import models

          class UserPermissionsForm(forms.ModelForm):
          change_user = forms.ChoiceField(
          widget=forms.RadioSelect,
          choices=[(True, 'Yes'), (False, 'no')],
          required=True # It's required ?
          )

          class Meta:
          model = models.YOUR_MODEL_NAME
          fields = ('change_user',) # I'll use only one field


          views.py:



          from django.views.generic import UpdateView
          from django.urls import reverse_lazy
          from django.contrib import messages
          from django.contrib.auth.models import Permission
          from YOUR_APP_NAME import models, forms


          class UserPermissionView(UpdateView):
          model = models.YOUR_MODEL_NAME
          template_name = 'user_permission.html' # Your template name
          form_class = forms.UserPermissionsForm
          initial = {} # We'll update the form's fields by their initial values

          def get_initial(self):
          """Update the form_class's fields by their initials"""

          base_initial = super().get_initial()
          # Here we'll check if the user has the permission of 'change_user'
          user_has_permission = self.request.user.user_permissions.filter(
          codename='change_user'
          ).first()
          base_initial['change_user'] = True if user_has_permission else False
          return base_initial

          def form_valid(self, form):
          """
          Here we'll update the user's permission based on the form choice:
          If we choose: Yes => Add 'change_user' permission to the user
          No => Remove 'change_user' permission from the user
          """
          change_user = form.cleaned_data['change_user']
          permission = Permission.objects.get(codename='change_user')
          if change_user == 'True':
          self.request.user.user_permissions.add(permission)
          # Use django's messaging framework
          # We'll render the results into the template later
          messages.success(
          self.request,
          'Updated: User [{}] Can change user'.format(self.request.user.username)
          )
          else:
          self.request.user.user_permissions.remove(permission)
          messages.success(
          self.request,
          'Updated: User [{}] Cannot change user'.format(self.request.user.username)
          )
          return super().form_valid(form)

          def get_success_url(self):
          """
          Don't forget to add your success URL,
          basically use the same url's name as this class view
          """
          # Note here, we'll access to the URL based on the user pk number
          return reverse_lazy('user_permissions', kwargs={'pk': self.request.user.pk})


          urls.py:



          from django.urls import path
          from YOUR_APP_NAME import views


          urlpatterns = [
          path(
          'client/<int:pk>/', # Access the view by adding the User pk number
          views.UserPermissionView.as_view(),
          name='user_permissions'
          ),
          ... # The rest of your paths
          ]


          And finally the template:



          user_permissions.html:



          {% if messages %}
          {% for message in messages %}
          {{ message }}
          {% endfor %}
          <br><br>
          {% endif %}

          <div>User: {{ user.username }}</div>
          <form method="POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type='submit'>Submit</button>
          </form>


          And here are some screenshots of the flow of this solution:



          First



          second



          third



          And of course, you can check if the add/remove actions of the permission under the Django Admin Panel.






          share|improve this answer















          You can resolve your question using Django UpdateView with a ModelForm like this example (See the comments in order to understand what's going on):



          forms.py:



          from django import forms
          from YOUR_APP_NAME import models

          class UserPermissionsForm(forms.ModelForm):
          change_user = forms.ChoiceField(
          widget=forms.RadioSelect,
          choices=[(True, 'Yes'), (False, 'no')],
          required=True # It's required ?
          )

          class Meta:
          model = models.YOUR_MODEL_NAME
          fields = ('change_user',) # I'll use only one field


          views.py:



          from django.views.generic import UpdateView
          from django.urls import reverse_lazy
          from django.contrib import messages
          from django.contrib.auth.models import Permission
          from YOUR_APP_NAME import models, forms


          class UserPermissionView(UpdateView):
          model = models.YOUR_MODEL_NAME
          template_name = 'user_permission.html' # Your template name
          form_class = forms.UserPermissionsForm
          initial = {} # We'll update the form's fields by their initial values

          def get_initial(self):
          """Update the form_class's fields by their initials"""

          base_initial = super().get_initial()
          # Here we'll check if the user has the permission of 'change_user'
          user_has_permission = self.request.user.user_permissions.filter(
          codename='change_user'
          ).first()
          base_initial['change_user'] = True if user_has_permission else False
          return base_initial

          def form_valid(self, form):
          """
          Here we'll update the user's permission based on the form choice:
          If we choose: Yes => Add 'change_user' permission to the user
          No => Remove 'change_user' permission from the user
          """
          change_user = form.cleaned_data['change_user']
          permission = Permission.objects.get(codename='change_user')
          if change_user == 'True':
          self.request.user.user_permissions.add(permission)
          # Use django's messaging framework
          # We'll render the results into the template later
          messages.success(
          self.request,
          'Updated: User [{}] Can change user'.format(self.request.user.username)
          )
          else:
          self.request.user.user_permissions.remove(permission)
          messages.success(
          self.request,
          'Updated: User [{}] Cannot change user'.format(self.request.user.username)
          )
          return super().form_valid(form)

          def get_success_url(self):
          """
          Don't forget to add your success URL,
          basically use the same url's name as this class view
          """
          # Note here, we'll access to the URL based on the user pk number
          return reverse_lazy('user_permissions', kwargs={'pk': self.request.user.pk})


          urls.py:



          from django.urls import path
          from YOUR_APP_NAME import views


          urlpatterns = [
          path(
          'client/<int:pk>/', # Access the view by adding the User pk number
          views.UserPermissionView.as_view(),
          name='user_permissions'
          ),
          ... # The rest of your paths
          ]


          And finally the template:



          user_permissions.html:



          {% if messages %}
          {% for message in messages %}
          {{ message }}
          {% endfor %}
          <br><br>
          {% endif %}

          <div>User: {{ user.username }}</div>
          <form method="POST">
          {% csrf_token %}
          {{ form.as_p }}
          <button type='submit'>Submit</button>
          </form>


          And here are some screenshots of the flow of this solution:



          First



          second



          third



          And of course, you can check if the add/remove actions of the permission under the Django Admin Panel.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 2:18

























          answered Jan 4 at 0:06









          Chiheb NexusChiheb Nexus

          5,36931829




          5,36931829













          • It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

            – Buky
            Jan 4 at 20:22








          • 1





            try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

            – Chiheb Nexus
            Jan 4 at 22:48











          • I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

            – Buky
            Jan 7 at 18:26













          • Still i didn't get your point. Sorry

            – Chiheb Nexus
            Jan 7 at 20:57



















          • It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

            – Buky
            Jan 4 at 20:22








          • 1





            try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

            – Chiheb Nexus
            Jan 4 at 22:48











          • I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

            – Buky
            Jan 7 at 18:26













          • Still i didn't get your point. Sorry

            – Chiheb Nexus
            Jan 7 at 20:57

















          It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

          – Buky
          Jan 4 at 20:22







          It's very close of what I want to do. But when I use fields = ('change_user',) (like you) I get the fallowing error django.core.exceptions.FieldError: Unknown field(s) (change_user) specified for User because User don't directly have a change_user value... That my problem when I try ModelForm way.

          – Buky
          Jan 4 at 20:22






          1




          1





          try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

          – Chiheb Nexus
          Jan 4 at 22:48





          try with __all__ and then tell me do use django's User model directly or do you use a foreignkey/OneToOneField to User model ?

          – Chiheb Nexus
          Jan 4 at 22:48













          I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

          – Buky
          Jan 7 at 18:26







          I directly use the model Django User model. I can call any permission in true the relation OneToMany (defined by the django framework for permissions) to apply a widget on them... And that make no sense to create a ModelForm with use fields and widgets. I think I need to handle all the process (a bit like you did) in a Form.

          – Buky
          Jan 7 at 18:26















          Still i didn't get your point. Sorry

          – Chiheb Nexus
          Jan 7 at 20:57





          Still i didn't get your point. Sorry

          – Chiheb Nexus
          Jan 7 at 20:57




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54029943%2fcreate-a-form-to-activate-user-permission%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas