【问题标题】:Django: Allow Users With Permission to Edit Project PageDjango:允许用户编辑项目页面
【发布时间】:2021-06-19 07:48:59
【问题描述】:

我有一个模型:uProjects 将用户和项目关联起来,如果该用户具有管理员状态,即 ifAdmin。我正在尝试创建一种方法来允许用户编辑项目,如果该用户具有该项目的 ifAdmin=True 。我目前使用的方法是使用 wrap 函数,但我遇到了一个问题,因为即使我用一个对项目“x”具有 ifAdmin=True 的用户登录,然后我转到项目“x”页面并尝试编辑项目,我仍然得到 HttpResponseRedirect('/')。

型号:

class uProjects(models.Model):
   
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    ifAccepted = models.BooleanField(null = True, blank=False, default=False)
    #ifLeader = models.BooleanField(null = False, blank=False)
    ifAdmin = models.BooleanField(null = True, blank=False, default=False)
    title = models.CharField(max_length=100, null=False, blank=False)
    def __str__(self):
        return self.user.username + ',' + self.project.name

views.py

def admin_check(function):
  @wraps(function)
  def wrap(request, *args, **kwargs):
        user = request.user
        name = kwargs.get('name')  
        if uProjects.objects.filter(title=name, user=user, ifAdmin=True).exists():
             return function(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/')

  return wrap

@admin_check
def update(request):
    if request.method == "POST":
        pr_form = ProjectUpdateForm(request.POST,
                                    request.FILES,
                                    instance=request.project.name)
   
        if pr_form.is_valid():
            pr_form.save()
            messages.success(request, f'This project has been updated.')
            return redirect('project')
        
    else:
        pr_form = ProjectUpdateForm(instance=request.user.profile)
    context = {
        'pr_form': pr_form
    }
    return render(request, 'projects/updateproject.html', context)

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/',v.register, name='register'),
    path('profile/<int:id>/',v.profile, name='profile1'),
    path('profile/',v.profile1, name='profile'),
    path('home/',v.home, name='home'),
    path('noti/',n.Notifications, name='noti'),
    path('invite/',n.invite, name='invite'),
    path('accept/<str:name1>/<int:id>/', n.accept, name='accept'),
    path('project/<str:name>/request/<int:id>', n.request, name= 'request'),
    path('allow/<str:name1>/<int:id>/', n.allow, name = 'allow'),
    path('', include('main.urls')),
    path('', include("django.contrib.auth.urls")),
    path('', include('projects.urls')),
    path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='registration/logout.html'), name='logout'),
    #url(r'^updateprofile', v.updateprofile),
    path('updateprofile/', v.updateprofile, name='updateprofile'),
    path('createproject/', p.createProject, name='createproject'),
    path('project/<str:name>/', p.project, name='project'),
    path('editproject/', p.update, name="editproject"),
    path('agree/', include('Notifications.urls')),
]   

projects.models.py

class Project(models.Model):
    name = models.CharField(max_length=30)
    #owner = models.ForeignKey(User, on_delete=models.CASCADE, null = True)
    bPic = models.ImageField(default='defaultproban.jpg', upload_to='project_banner')
    logo = models.ImageField(default='defaultlogo.jpg', upload_to='project_logo')
    dep_choice1 = (
        ('Behavioral Sciences and Leadership', ('Behavioral Sciences and Leadership')),
        ('Chemistry and Life Science', ('Chemistry and Life Science')),
        ('Civil and Mechanical Engineering', ('Civil and Mechanical Engineering')),
        ('Electrical Engineering and Comptuer Science', ('Electrical Engineering and Comptuer Science')),
        ('English and Philosophy', ('English and Philosophy')),
        ('Foreign Languages', ('Foreign Languages')),
        ('Geography and Environmental Engineering', ('Geography and Environmental Engineering')),
        ('History', ('History')),
        ('Law', ('Law')),
        ('Mathematical Sciences', ('Mathematical Sciences')),
        ('Physics and Nuclear Engineering', ('Physics and Nuclear Engineering')),
        ('Social Sciences', ('Social Sciences')),
        ('Systems Engineering', ('Systems Engineering')),
        ('Independent', ('Independent')),
    )
    department = models.CharField(
        max_length=50,
        choices=dep_choice1,
        default='Independent',
    )
    description = models.CharField(max_length=50, null = True)
    purpose=models.TextField()
    tag_choice = (
        ('Data Analysis' , ('Data Analysis')),
        ('3D Printing' , ('3D Printing')),
        ('Robotics' , ('Robotics')),
        ('Coding' , ('Coding')),
        ('Frauds' , ('Frauds, AKA Law majors')),
    )

    projectTag = models.CharField(
        max_length=32,
        choices=tag_choice,
        default='Frauds',
    )

    look = (
        ('motivated cadets with niche expertise.', ('Expert Cadets')),
        ('cadets who want to learn and help.', ('Any cadet who wants to help')),
        ('an engineering cadet.', ('Engineering Cadet')),
        ('a cadet with a scientific background.', ('Scientific background')),
        ('cadets with programming experience.', ('Coding Background')),
       
    )
    
    lookingFor = models.CharField(
        max_length=75,
        choices=look,
        default='an engineering cadet,',
    )

    recruit = (
        ('Yes', ('Yes')),
        ('No', ('No')),
    )

    recruiting = models.CharField(
        max_length=50,
        choices=recruit,
        default='Yes',
    )
    class Meta:
        verbose_name_plural= "projects"

    def __str__(self):
        return self.name```

This code doesn't work with the provided code because when I am logged in with a user who has ifAdmin = True for a uProject, and I try to edit the project page associated with that uProject, I am returned the HttpResponseRedirect('/')

【问题讨论】:

    标签: python django permissions


    【解决方案1】:

    如果我没记错 django 的工作原理,请尝试一下:

    # urls.py
    urlpatterns = [
        ...
        path('editproject/<str:name>', p.update, name="editproject"),
        ...
    ]
    

    在这个name = kwargs.get('name') 中,我们总是有None 并且django 试图找到标题为None 的uProjects,它在db 中不存在。

    【讨论】:

    • 感谢您的意见。如果我尝试这样做,我的困境是我收到一个错误:“NoReverseMatch at /project/Investment Algorithms/Reverse for 'editproject' 没有找到任何参数。尝试了 1 个模式:['editproject/(?P[^/]+)$']" 你知道我该如何解决这个问题吗?
    • 首先,我首先将path('', include('main.urls')) 等模式转移到文件末尾。二、尝试打开editproject/somethingname网址,而不是editproject
    • 当我尝试打开editproject/[a project that the user I'm logged in with has ifAdmin = True] 时,我得到一个指向主页的HttpResponseRedirect,因为不知何故用户没有通过测试。这让我回到了最初的问题。
    • 设置断点并检查name变量中包含的内容,然后像uProjects.objects.filter(title=name, user=user, ifAdmin=True)一样查询并检查返回的内容,然后您可以回答自己的问题
    • 好点。所以,我尝试了这个,由于某种原因,错误是该字段 'id' 需要一个数字,但得到了我为我的用户名输入的字符串。这是为什么呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2011-07-09
    • 2019-12-31
    • 2023-03-13
    • 1970-01-01
    • 2015-01-01
    相关资源
    最近更新 更多