Should i use django admin
A hook for the initial data on admin change forms. By default, fields are given initial values from GET parameters. For instance,? The objs argument is a homogeneous iterable of objects a QuerySet or a list of model instances to be deleted, and request is the HttpRequest. If there are any related objects to be deleted, the list is nested and includes those related objects.
The list is displayed in the template. Unlike the hook-type ModelAdmin methods detailed in the previous section, these five methods are in reality designed to be invoked as Django views from the admin application URL dispatching handler to render the pages that deal with model instances CRUD operations. As a result, completely overriding these methods will significantly change the behavior of the admin application.
One common reason for overriding these methods is to augment the context data that is provided to the template that renders the view. In the following example, the change view is overridden so that the rendered template is provided some extra mapping data that would not otherwise be available:.
These views return TemplateResponse instances which allow you to easily customize the response data before rendering. For more details, see the TemplateResponse documentation. This can be accomplished by using a Media inner class on your ModelAdmin :. The same rules apply as regular asset definitions on forms.
Django admin JavaScript makes use of the jQuery library. If you want to use jQuery in your own admin JavaScript without including a second copy, you can use the django. Also, your own admin forms or widgets depending on django. For example, if you require the jQuery library to be in the global namespace for example when using third-party jQuery plugins or if you need a newer version of jQuery, you will have to include your own copy. You can also add custom validation of data in the admin.
The automatic admin interface reuses django. MyArticleAdminForm can be defined anywhere as long as you import where needed. Now within your form you can add your own custom validation for any field:.
It is important you use a ModelForm here otherwise things can break. See the forms documentation on custom validation and, more specifically, the model form validation notes for more information. The admin interface has the ability to edit models on the same page as a parent model.
These are called inlines. Suppose you have these two models:. You can edit the books authored by an author on the author page. You add inlines to a model by specifying them in a ModelAdmin. Django provides two subclasses of InlineModelAdmin and they are:. InlineModelAdmin shares many of the same features as ModelAdmin , and adds some of its own the shared features are actually defined in the BaseModelAdmin superclass. The shared features are:.
The InlineModelAdmin class adds or customizes:. The name of the foreign key on the model. This defaults to BaseInlineFormSet. Using your own formset can give you many possibilities of customization.
Inlines are built around model formsets. The value for form defaults to ModelForm. When writing custom validation for InlineModelAdmin forms, be cautious of writing validation that relies on features of the parent model. If the parent model fails to validate, it may be left in an inconsistent state as described in the warning in Validation on a ModelForm.
A list or tuple containing extra CSS classes to apply to the fieldset that is rendered for the inlines. Defaults to None. This controls the number of extra forms the formset will display in addition to the initial forms.
Defaults to 3. See the formsets documentation for more information. This controls the maximum number of forms to show in the inline. See Limiting the number of editable objects for more information.
This controls the minimum number of forms to show in the inline. Specifies whether or not inline objects can be deleted in the inline. Defaults to True. Specifies whether or not inline objects that can be changed in the admin have a link to the change form. Defaults to False. See the example for ModelAdmin. Returns the number of extra inline forms to use. By default, returns the InlineModelAdmin.
Override this method to programmatically determine the number of extra inline forms. For example, this may be based on the model instance passed as the keyword argument obj :. Returns the maximum number of extra inline forms to use.
Override this method to programmatically determine the maximum number of inline forms. Returns the minimum number of inline forms to use. Override this method to programmatically determine the minimum number of inline forms. For example, this may be based on the model instance passed as the keyword argument obj. Should return True if adding an inline object is permitted, False otherwise. Should return True if editing an inline object is permitted, False otherwise. Should return True if deleting an inline object is permitted, False otherwise.
The obj argument passed to InlineModelAdmin methods is the parent object being edited or None when adding a new parent. It is sometimes possible to have more than one foreign key to the same model. Take this model for instance:. By default, admin widgets for many-to-many relations will be displayed on whichever model contains the actual reference to the ManyToManyField. However, it is also possible to replace these widgets with inlines. If you want to display many-to-many relations using an inline, you can do so by defining an InlineModelAdmin object for the relationship:.
Firstly - the MembershipInline class references Group. The through attribute is a reference to the model that manages the many-to-many relation. This model is automatically created by Django when you define a many-to-many field. Secondly, the GroupAdmin must manually exclude the members field. Django displays an admin widget for a many-to-many field on the model that defines the relation in this case, Group. This is because as far as the admin is concerned, through is just a model with two foreign key fields rather than a many-to-many relation.
In all other respects, the InlineModelAdmin is exactly the same as any other. You can customize the appearance using any of the normal ModelAdmin properties. When you specify an intermediary model using the through argument to a ManyToManyField , the admin will not display a widget by default. This is because each instance of that intermediary model requires more information than could be displayed in a single widget, and the layout required for multiple widgets will vary depending on the intermediate model.
However, we still want to be able to edit that information inline. Fortunately, we can do this with inline admin models. Suppose we have the following models:. The first step in displaying this intermediate model in the admin is to define an inline class for the Membership model:. This example uses the default InlineModelAdmin values for the Membership model, and limits the extra add forms to one. This could be customized using any of the options available to InlineModelAdmin classes.
Now create admin views for the Person and Group models:. Finally, register your Person and Group models with the admin site:. Now your admin site is set up to edit Membership objects inline from either the Person or the Group detail pages. It is possible to use an inline with generically related objects. They implement tabular and stacked visual layouts for the forms representing the inline objects, respectively, just like their non-generic counterparts. They behave just like any other inline.
In your admin. See the contenttypes documentation for more specific information. You can override many of the templates which the admin module uses to generate the various pages of an admin site.
You can even override a few of these templates for a specific app, or a specific model. If you have customized the 'loaders' option, be sure 'django.
Loader' appears before 'django. Loader' so that your custom templates will be found by the template loading system before those that are included with django. Within this admin directory, create sub-directories named after your app. Within these app subdirectories create sub-directories named after your models. Note, that the admin app will lowercase the model name when looking for the directory, so make sure you name the directory in all lowercase if you are going to run your app on a case-sensitive filesystem.
Because of the modular design of the admin templates, it is usually neither necessary nor advisable to replace an entire template. It is almost always better to override only the section of the template which you need to change.
To continue the example above, we want to add a new link next to the History tool for the Page model. The following can:. This is particularly useful to create custom and pages. These may be overridden, but in such cases you are probably better off creating your own version of the tag in question and giving it a different name.
That way you can use it selectively. If you wish to change the index, login or logout templates, you are better off creating your own AdminSite instance see below , and changing the AdminSite. The admin uses CSS variables to define colors. This allows changing colors without having to override many individual CSS rules. A dark theme is defined, and applied respecting the prefers-color-scheme media query.
A Django administrative site is represented by an instance of django. AdminSite ; by default, an instance of this class is created as django. If you want to customize the default admin site, you can override it. When constructing an instance of an AdminSite , you can provide a unique instance name using the name argument to the constructor.
This instance name is used to identify the instance, especially when reversing admin URLs. If no instance name is provided, a default instance name of admin will be used. Templates can override or extend base admin templates as described in Overriding admin templates.
Set it to None to remove the link. The text to put at the top of the admin index page a string. Defaults to a dash. See ModelAdmin. A boolean value that determines whether to show the navigation sidebar on larger screens. By default, it is set to True. A boolean value that determines whether to add a final catch-all view to the admin that redirects unauthenticated users to the login page.
Setting this to False is not recommended as the view protects against a potential model enumeration privacy issue. Subclass of AuthenticationForm that will be used by the admin site login view. Returns a dictionary of variables to put in the template context for every page in the admin site. Each entry in the list is a dict representing an application with the following keys:. Returns True if the user for the given HttpRequest has permission to view at least one page in the admin site.
Defaults to requiring both User. If keyword arguments are given — e. Raises ImproperlyConfigured if a model is abstract. The Django project recommends it only for internal data management i.
All the configuration required to include the admin application in your website was done automatically when you created the skeleton project for information about actual dependencies needed, see the Django docs here.
As a result, all you must do to add your models to the admin application is to register them. At the end of this article we'll provide a brief demonstration of how you might further configure the admin area to better display our model data. After registering the models we'll show how to create a new "superuser", login to the site, and create some books, authors, book instances, and genres.
These will be useful for testing the views and templates we'll start creating in the next tutorial. First, open admin. It currently looks like this — note that it already imports django. Register the models by copying the following text into the bottom of the file. This code imports the models and then calls admin. Note: If you accepted the challenge to create a model to represent the natural language of a book see the models tutorial article , import and register it too!
This is the simplest way of registering a model, or models, with the site. The admin site is highly customisable, and we'll talk more about the other ways of registering your models further down.
In order to log into the admin site, we need a user account with Staff status enabled. In order to view and create records we also need this user to have permissions to manage all our objects.
You can create a "superuser" account that has full access to the site and all needed permissions using manage. Call the following command, in the same directory as manage. You will be prompted to enter a username, email address, and strong password. Once this command completes a new superuser will have been added to the database.
Now restart the development server so we can test the login:. This part of the site displays all our models, grouped by installed application. You can click on a model name to go to a screen that lists all its associated records, and you can further click on those records to edit them. You can also directly click the Add link next to each model to start creating a record of that type.
Click on the Add link to the right of Books to create a new book this will display a dialog much like the one below. Enter values for the fields. Note: At this point we'd like you to spend some time adding a few books, authors, and genres e. Fantasy to your application.
Make sure that each author and genre includes a couple of different books this will make your list and detail views more interesting when we implement them later on in the article series. When you've finished adding books, click on the Home link in the top bookmark to be taken back to the main admin page.
Then click on the Books link to display the current list of books or on one of the other links to see other model lists. Now that you've added a few books, the list might look similar to the screenshot below. From this list you can delete books by selecting the checkbox next to the book you don't want, selecting the delete You can edit a book by selecting its name in the link.
The edit page for a book, shown below, is almost identical to the "Add" page. Now navigate back to the Home page using the Home link in the breadcrumb trail and then view the Author and Genre lists — you should already have quite a few created from when you added the new books, but feel free to add some more.
What you won't have is any Book Instances , because these are not created from Books although you can create a Book from a BookInstance — this is the nature of the ForeignKey field. Navigate back to the Home page and press the associated Add button to display the Add book instance screen below. Note the large, globally unique Id, which can be used to separately identify a single copy of a book in the library. Create a number of these records for each of your books. Set the status as Available for at least some records and On loan for others.
If the status is not Available , then also set a future Due back date. That's it! Even usage by site administrators is contra-indicated, although in practice most small sites get away with it since they're only talking a few people who can call on the developer personally if they get into trouble.
For your purposes, the review items and the workflow in creating the items is a critical part of your application feature set. The admin will give you ideas, but it would be a mistake to attempt to build your application upon it. I wouldn't expose the admin interface to regular users. You can use the authentication and user-management side for your purposes , but it's usually best practice to give users a separate way to manage their objects.
You also don't run as much of a risk of granting the wrong privileges to users or allowing them to grant their own. Have a read though the docs if you want a better overview about what it can do. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Should I use Django's Admin feature? Ask Question. Asked 10 years, 2 months ago. Active 1 year, 3 months ago. Viewed 4k times. Thanks for any feedback! Improve this question. Jon Lemmon Jon Lemmon 3, 2 2 gold badges 22 22 silver badges 37 37 bronze badges.
0コメント