Where is django admin.py




















For example, if the choices available to a superuser should be different than those available to regular staff, you could proceed as follows:. Any choices attribute set on the formfield will be limited to the form field only. If the corresponding field on the model has choices set, the choices provided to the form must be a valid subset of those choices, otherwise the form submission will fail with a ValidationError when the model itself is validated before saving.

Returns the Changelist class to be used for listing. ChangeList is used. By inheriting this class you can change the behavior of the listing. Returns a ModelForm class for use in the Formset on the changelist page. To use a custom form, for example:. However, ModelAdmin ignores this value, overriding it with the ModelAdmin. The easiest solution is to omit the Meta. To use a custom formset, for example:. Since the lookups in the query string can be manipulated by the user, they must be sanitized to prevent unauthorized data exposure.

Override this method to customize the lookups permitted for your ModelAdmin subclass. Should return True if viewing obj is permitted, False otherwise. If obj is None , should return True or False to indicate whether viewing of objects of this type is permitted in general e.

Should return True if adding an object is permitted, False otherwise. Should return True if editing obj is permitted, False otherwise. If obj is None , should return True or False to indicate whether editing of objects of this type is permitted in general e. Should return True if deleting obj is permitted, False otherwise. If obj is None , should return True or False to indicate whether deleting objects of this type is permitted in general e.

Uses User. One use case for overriding this method is to show objects owned by the logged-in user:. Sends a message to the user using the django. See the custom ModelAdmin example. Keyword arguments allow you to change the message level, add extra CSS tags, or fail silently if the contrib.

These keyword arguments match those for django. Returns an instance of the paginator to use for this view. By default, instantiates an instance of paginator.

You can override it to change the default behavior after the object has been created. You can override it to change the default behavior after the object has been changed. You can override it to change the default behavior after the object has been deleted.

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. When prompted, type your username lowercase, no spaces , email address, and password. Don't worry that you can't see the password you're typing in — that's how it's supposed to be. Type it in and press enter to continue. The output should look like this where the username and email should be your own ones :.

Return to your browser. Log in with the superuser's credentials you chose; you should see the Django admin dashboard. Go to Posts and experiment a little bit with it. Add five or six blog posts. Don't worry about the content —- it's only visible to you on your local computer -- you can copy-paste some text from this tutorial to save time. Use the --keep-pot option to prevent django from deleting the temporary. This is useful for debugging errors which may prevent the final language files from being created.

Deprecated since version 1. See the FastCGI deployment documentation for details. Protocol to use. Possible values: prefork or threaded default prefork. Number of requests a child handles before it is killed and a new child is forked 0 means no limit.

Umask to use when daemonizing. The value is interpeted as an octal number default value is Starts a lightweight development Web server on the local machine. By default, the server runs on port on the IP address You can pass in an IP address and port number explicitly. If you run this script as a user with normal privileges recommended , you might not have access to start a port on a low port number. Low port numbers are reserved for the superuser root.

It has not gone through security audits or performance tests. The development server automatically reloads Python code for each request, as needed. When you start the server, and each time you change Python code while the server is running, the server will validate all of your installed models. See the validate command below. Just execute django-admin. Note that the default IP address, To make your development server viewable to other machines on the network, use its own IP address e.

You can provide an IPv6 address surrounded by brackets e. This will automatically enable IPv6 support. If the staticfiles contrib app is enabled default in new projects the runserver command will be overridden with its own runserver command.

Use the --noreload option to disable the use of the auto-reloader. This means any Python code changes you make while the server is running will not take effect if the particular Python modules have already been loaded into memory. The development server is multithreaded by default. Use the --nothreading option to disable the use of threading in the development server.

Use the --ipv6 or shorter -6 option to tell Django to use IPv6 for the development server. This changes the default IP address from Port on IPv6 address db :. Port on IPv4 address of host localhost :. Port on IPv6 address of host localhost :. Django will use IPython or bpython if either is installed. If you would like to specify either IPython or bpython as your interpreter if you have both installed you can specify an alternative interpreter interface with the -i or --interface options like so:.

The --interface option was added in Django 1. The --no-startup option was added in Django 1. The --database option can be used to specify the database for which to print the SQL.

Refer to the description of sqlcustom for an explanation of how to specify initial data. Prints the SQL statements that would be executed for the flush command. Sequences are indexes used by some database engines to track the next available number for automatically incremented fields. Use this command to generate SQL which will fix cases where a sequence is out of sync with its automatically incremented field data.

Creates a Django app directory structure for the given app name in the current directory or the given destination. By default the directory created contains a models. See the source for more details. If only the app name is given, the app directory will be created in the current working directory. If the optional destination is provided, Django will use that existing directory rather than creating a new one.

With the --template option, you can use a custom app template by providing either the path to a directory with the app template file, or a path to a compressed file. For example, this would look for an app template in the given directory when creating the myapp app:. Django will also accept URLs http , https , ftp to compressed archives with the app template files, downloading and extracting them on the fly.

When Django copies the app template files, it also renders certain files through the template engine: the files whose extensions match the --extension option py by default and the files whose names are passed with the --name option. The template context used is:. For example, if one of the Python files contains a docstring explaining a particular feature related to template rendering, it might result in an incorrect example. Creates a Django project directory structure for the given project name in the current directory or the given destination.

By default, the new directory contains manage. See the template source for details. If the optional destination is provided, Django will use that existing directory as the project directory, and create manage. As with the startapp command, the --template option lets you specify a directory, file path or URL of a custom project template.

See the startapp documentation for details of supported project template formats. For example, this would look for a project template in the given directory when creating the myproject project:.

Django will also accept URLs http , https , ftp to compressed archives with the project template files, downloading and extracting them on the fly. When Django copies the project template files, it also renders certain files through the template engine: the files whose extensions match the --extension option py by default and the files whose names are passed with the --name option. Please also see the rendering warning as mentioned for startapp.

When you start a new project, run this command to install the default apps. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process. If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

See the documentation for loaddata for details on the specification of fixture data files. The --database option can be used to specify the database to synchronize. Runs tests for all installed models. See Testing in Django for more information.

The --failfast option can be used to stop running tests and report the failure immediately after a test fails. The --testrunner option can be used to control the test runner class that is used to execute tests.

The --liveserver option can be used to override the default address where the live server used with LiveServerTestCase is expected to run from. The default value is localhost Runs a Django development server as in runserver using data from the given fixture s. Note that this server does not automatically detect changes to your Python source code as runserver does.

It does, however, detect changes to templates. Use --addrport to specify a different port, or IP address and port, from the default of This value follows exactly the same format and serves exactly the same function as the argument to the runserver command.

To run the test server on port with fixture1 and fixture2 :.



0コメント

  • 1000 / 1000