简体   繁体   中英

Display django admin form only

I want to let the user (they're signed in) edit items using the admin form without them having access to the whole admin interface.

This would be easier and follow the DRY principle betters since the forms only need to be defined once in the admin setup. It should also avoids having to manually check if the user has permissions to edit that model since that will be taken care of by the admin system.

If i set the users as is_staff i know i can point them to the edit/add page for the particular model/item, but by manually editing the url they can find their way to the full admin interface (at least the bit they have access to). Also the admin interface doesn't have the correct theme unless I change the whole admin theme. (I think?)

Perhaps I'm missing something obvious and there's a super simple way to test if the user is able to add to/edit the model and generate a whole form (including formsets) for a model based on the relevent class in app/admin.py, but I haven't found it yet.

I look forward to being told I'm an idiot and there's an obvious and simple solution.

(edit: i've looked at django-frontendadmin, but it looks out of date and the urls situation looked a hack.)

The admin is intended for trusted users only. So opening the admin up to all users of your site is a bad idea.

You need a form from your model... These are known as modelforms .

>>> from django.forms import ModelForm
>>> from myapp.models import Article

# Create the form class.
>>> class ArticleForm(ModelForm):
...     class Meta:
...         model = Article
...
>>> form = ArticleForm()

How to work with forms is in the forms documentation .

UPDATE:

The automatic admin interface reuses django.forms. So ModelAdmin.form and a ModelForm are both forms. They are capable of the same thing. So if you want to 'Display django admin form only ... Easy and out of the box' . Than a modelform is the answer. Proof:

from django.db import models
from django.forms import ModelForm
from django.contrib import admin

class Author(models.Model):
   pass

class AuthorForm(ModelForm):
    class Meta:
        model = Author        

class AuthorAdmin(admin.ModelAdmin):
    pass
admin.site.register(Author, AuthorAdmin)

print AuthorForm.__class__ == AuthorAdmin.form.__class__ # True

The only differences I can think of are: Some fields in ModelAdmin.form use admin widgets (widgets are easy to define) and the admin has some images, js and css (media is easy to include).

Finaly a tip: Use an app that helps with styling, ordering, widgets etc like django-crispy-forms .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM