How to implement Dashboard in django admin?
If I have following Model in django. Is there a way, instead of regular Models list,I can have a search box in admin page to search for student using his name and display his particular details...
class MStudent(models.Model):
enroll_no = models.IntegerField()
Name = models.CharField(max_length=200)
photo = models.ImageField(upload_to="static",blank = True)
def __str__(self):
return self.FName+" "+ self.MName+" "+ self.LName
class MStud_Address_ph_no_email(models.Model):
enroll_no = models.ForeignKey(MStudent)
Address = models.CharField(max_length=200)
Personal_mobile= models.IntegerField()
Fathers_mobile = models.IntegerField()
def __str__(self):
return str(self.enroll_no)
From the Django admin documentation:
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.index_template , AdminSite.login_template or AdminSite.logout_template properties.
So you should create your own AdminSite and set its index_template attribute to a template of yours that implements the Dashboard you want.
To provide a search and a search results view, see adding views to admin sites.
I think you should read the django docs about admin
And in your case if you want to customize the admin look and feel or adding extra fucntionality, you need override the required admin templates like admin/index.html by creating an admin folder in your template directory
Q.Is there a way, instead of regular Models list, I can have a search box in admin page to search for student using his name and display his particular details?
1) Yes Instead of displaying regular Models list I can directly redirect to model Mstudent.using following code
urls.py
from django.http import HttpResponseRedirect
url(r'^admin/$',lambda x:HttpResponseRedirect('/admin/yourapp/yourmodel'))
2) To search for student using his name and display his particular details:
Make MStud_Address_ph_no_email as inline to MStudent in admin.py.
So all in all whenever a user logged in to django admin, He will directly see list of all students and by selecting a particular student he can see all his details.
:)
Related
I have a Django project that includes a model class with an optional self-referential ForeignKey field. A partial snippet:
class Site(models.model):
name = models.CharField(max_length=100)
parent_site = models.ForeignKey('self', null=True, blank=True)
I'm using the Django admin site to create new objects. For this class' admin form I'd like to disable the "Add another..." button next to the parent_site field (i.e. when you're creating a new site, you can't open the popup to create another new site as the parent).
I can't remove has_add_permission from the user, as they need it to be in the current add view. I don't mind removing the function from both add and change views, but limiting removal to the add view would be helpful.
I haven't been able to work out how to use the Inline field classes to achieve this, or formfield_for_foreignkey, or a custom ModelForm. Anyone got a solution more elegant than using JavaScript on a customised form template?
no css hacks add to admin class:
max_num=0
or try this in admin.py ( for older django versions):
class MODEL_ADMIN(admin.ModelAdmin):
class Media:
css = {'all': ('css/no-addanother-button.css',)}
I'm new to Django so this might be a simple question. I'm trying to build a portfolio site using Django. I'd like to have a homepage, portfolio page, portfolio detail pages, and contact page. There will be about 20 portfolio detail pages - Project A, Project B, Project C. Each project (portfolio detail page) has multiple areas where I can input text that is populated through the Django admin. How do I create custom fields in the admin for each Portfolio Detail page (headline, project name, url, description) and display them in the page template?
I'm confused as do I use the pages section in the Django admin and add custom fields for each page or do I create a custom app with these custom fields? Then let's say Project B needs an extra field for awards. How do I add that custom field for just the Project B page in the Django admin?
There is no reason why you can't add any number of fields to your project by just linking them with foreign keys.
project/models.py
from django.db import models
class Project(models.model):
name = models.CharField(max_length=100)
class ProjectField(models.model):
project = models.ForeignKey(Project)
fieldname = models.CharField(max_length=50)
value = models.TextField(max_length=2000)
With what you are describing, it sounds like you would like to edit the ProjectField values in the Project admin page. The way that the admin page handles that normally is with inlines.
As an example for the models above:
projects/admin.py
from projects import models
from django.contrib import admin
class ProjectFieldInline(admin.StackedInline):
model = models.ProjectField
extra = 0
class ProjectAdmin(admin.ModelAdmin):
inlines = [ProjectFieldInline]
admin.site.register(models.Project, ProjectAdmin)
I can't say one hundred percent that this will work for what you are asking, but I recomend giving the app above a try and seeing how close it is to what you want.
I have this model:
class Clients(models.Model):
name = models.CharField(max_length=150)
user = models.ForeignKey(auth.models.User)
def __unicode__(self):
return self.name
When I run this model in Admin Template, is displayed an component and an image with a link to add new User. I would like to know how to change the image's source of link. The default value is
/static/admin/img/admin/icon_addlink.gif
Thanks.
You'll need to override the template for the add Client form. https://docs.djangoproject.com/en/dev/ref/contrib/admin/#custom-template-options is what you're looking for, although I will say overriding django admin templates can become messy when you upgrade to a later version of django.
So I've set up my django site with the following admin.py:
import models
from django.contrib import admin
admin.site.register(models.Comment)
which uses this models.py:
from django.db import models
class Comment(models.Model):
text = models.CharField(max_length=400)
name = models.CharField(max_length=100)
date = models.DateTimeField(auto_now = True)
article = models.CharField(max_length=100)
However, when I go to the admin page, it shows the following:
Which generally is not very helpful. Clicking on each link gives me a page with that object's data, but I would like to be able to see the information for each object in this view. I've been looking at the ModelAdmin class at:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/
but have not managed to wrap my head around it. Is it a separate model class that needs to be kept in sync with my "actual" model? Is it just an interface through which my Admin site accesses the actual model? Does it do what I want (allowing useful data to be shown in the admin interface) or does it do something else?
I'm thinking that the Django Admin page should be able to replace PHPMyAdmin for doing simple tasks, like browsing the DB and manually modifying individual objects. Is that the case?
The admin turns your object into a string so just put a def __str__ or def __unicode__
(As #Mandax has reminded me the docs recommend to define __unicode__ only.)
def __unicode__(self);
return u"%s (%s): %s" % (self.article, self.date, self.name)
Just as it says in the documentation, your model's ModelAdmin describes how the admin section will represent your model. It does need to be somewhat in sync with the actual model, it doesn't make sense for you to display fields that aren't present on your model, etc. You seem interested in the changelist view, which has numerous customization options (all described in the documentation, and in the tutorial). A simple start might be:
from django.contrib import admin
class CommentAdmin(admin.ModelAdmin):
# define which columns displayed in changelist
list_display = ('text', 'name', 'date', 'article')
# add filtering by date
list_filter = ('date',)
# add search field
search_fields = ['text', 'article']
admin.site.register(Comment, CommentAdmin)
There are a lot of options for customization, as always refer to the docs! Finally, you could certainly use it in lieu of PHPMyAdmin, it's very easy to setup admin for browsing, modifying object, etc, how much use you get out of it is up to you.
I have a model called "Organization" that I've setup as a User profile and I would like to have the fields from the "Organization" model show up on the registration page. How do I go about doing this with django-registration.
# models.py
class Organization(models.Model):
user = models.ForeignKey(User, unique=True)
logo = models.ImageField(upload_to='organizations')
name = models.CharField(max_length=100, null=True, unique=True)
# more fields below etc.
# settings.py
AUTH_PROFILE_MODULE = 'volunteering.organization'
The easiest way to do this would be [tested on django-registration 0.8]:
Somewhere in your project, say forms.py in your organization app
from registration.forms import RegistrationForm
from django.forms import ModelForm
from models import Organization
class OrganizationForm(forms.ModelForm):
class Meta:
model = Organization
RegistrationForm.base_fields.update(OrganizationForm.base_fields)
class CustomRegistrationForm(RegistrationForm):
def save(self, profile_callback=None):
user = super(CustomRegistrationForm, self).save(profile_callback=None)
org, c = Organization.objects.get_or_create(user=user, \
logo=self.cleaned_data['logo'], \
name=self.cleaned_data['name'])
Then in your root urlconf [but above the regex pattern that includes registration.urls and assuming that regex is r'^accounts/'] add:
from organization.forms import CustomRegistrationForm
urlpatterns += patterns('',
(r'^accounts/register/$', 'registration.views.register', {'form_class':CustomRegistrationForm}),
)
Obviously, you can also create a custom backend, but IMHO this is way easier.
The best way would be to create in the app where you have Organization a file (say, "forms.py"), and do this:
from registration.forms import RegistrationForm
from forms import *
from models import Organization
class RegistrationFormWithOrganization(RegistrationForm):
organization_logo = field.ImageField()
organization_name = field.CharField()
def save(self, profile_callback = None):
Organization.objects.get_or_create(user = self.cleaned_data['user'],
logo = self.cleaned_data['organization_logo'],
name = self.cleaned_data['organization_name'])
super(RegistrationFormWithOrganization, self).save(self, profile_callback)
And then in your base URLs, override the existing URL to registration, and add this form as your the form to use:
form organization.forms import RegistrationFormWithOrganization
url('^/registration/register$', 'registration.views.register',
{'form_class': RegistrationFormWithOrganization}),
url('^/registration/', include('registration.urls')),
Remember that Django will use the first URL that matches the regexp, so will match your call and not django-registration's. It will also tell registration to use your form, not its own. I've skipped a lot of validation here (and, probably, the derivation of the user object... if so, go read the source code to registration to see where it comes from), but this is definitely the right track to get a few things into the page with a minimum amount of effort on your part.
Modify the code as below and try again
urlpatterns += patterns('',
(r'^accounts/register/$', 'registration.views.register', {'form_class':CustomRegistrationForm,'backend': 'registration.backends.default.DefaultBackend'}),
)
"Previously, the form used to collect data during registration was expected to implement a save() method which would create the new user account. This is no longer the case; creating the account is handled by the backend, and so any custom logic should be moved into a custom
backend, or by connecting listeners to the signals sent during the registration process."
Details:
more info can be found here