Rectangle 27 0

To do it you need to override has_add_permission method in your Admin class:

class AmountOfBooksAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        return False

    # to disable editing for specific or all fields
    # you can use readonly_fields attribute
    # (to see data you need to remove editable=False from fields in model):
    readonly_fields = ('book', 'amount')

If I do this I still can change Model and I would like to have just view functionality.

when I add has_change_permision then I can not see that table any more. has_add_permission and has_change_permission work the same way as appropriate permission for users.

@WebOrCode you right, with has_change_permission you cant view data... editable in model didnt help?

python - How to remove Add button in Django admin, for specific Model?...

python django django-models django-admin
Rectangle 27 0

Beside its (a bit awkward) hacking style, you could aslo override the template tag directly. Normally overriding template is more recommended.

# put this in some app such as customize/templatetags/admin_modify.py and place the app
# before the 'django.contrib.admin' in the INSTALLED_APPS in settings

from django.contrib.admin.templatetags.admin_modify import *
from django.contrib.admin.templatetags.admin_modify import submit_row as original_submit_row
# or 
# original_submit_row = submit_row

@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_row(context):
    ctx = original_submit_row(context)
    ctx.update({
        'show_save_and_add_another': context.get('show_save_and_add_another', ctx['show_save_and_add_another']),
        'show_save_and_continue': context.get('show_save_and_continue', ctx['show_save_and_continue'])
        })                                                                  
    return ctx

I think this is actually the best approach. First, I tried to do what you explain in # put this in some app such as customize/templatetags/admin_modify.py ... but it didn't work. Then, I put this piece of code at the beginning of the admin.py file and it works perfect.

@ManuelAlvarez fine. Perhaps your customize/templatetags/ lacked __init__.py and was thus not a package and got ignored. I'm not quite sure whether your admin.py solution works in all circumstances, we'll see :)

what's the purpose of that import * ? I tried to delete it, and import all those functions one by one, but my custom submit_row method is not called anymore. Any ideeas why ?

@NiCU It's a quick typing to import all requisites. Importing one by one is more appropriate. Perhaps your tag does not override the original one, because your custom app places after the original app in INSTALLED_APPS?

python - In Django admin, how can I hide Save and Continue and Save an...

python django django-templates django-admin
Rectangle 27 0

You can actually retrieve the info without making a query to ContentTypes

def get_admin_url(self):
    return urlresolvers.reverse("admin:%s_%s_change" %
        (self._meta.app_label, self._meta.module_name), args=(self.pk,))

For a django model, how can I get the django admin URL to add another,...

django django-admin django-urls
Rectangle 27 0

I assume that your app is called app and question field of the Answer model is named question :-)

from django.core.urlresolvers import reverse

class QuestionAdmin(admin.ModelAdmin):
    list_display = ['question', 'date', 'view_answers']

    def view_answers(self, obj):
        url = reverse("admin:app_answer_changelist")
        return '<a href="%s?question=%d">View answers</a>' % (url, obj.pk)
    view_answers.short_description = 'View answers'
    view_answers.allow_tags = True

Look at the first line of my code. There is an import of reverse.

Sorry for that. You are awesome thanks for your instant response :)

python - Need to add view list anchor tag for another model in django ...

python django django-admin
Rectangle 27 0

You asked about your design itself so I'll address this first. If you want to keep an history of your stock then having a distinct table (model) makes sense but then you'd need a timestamp field and a unique constraint on (book, timestamp). Now if you just want to keep the stock current the relationship between book and amount is really one to one so the amount field really belongs to the book table. In this case you just have to add "amount" to the book's ModelAdmin "readonly_fields" attribute and your problem is solved.

python - How to remove Add button in Django admin, for specific Model?...

python django django-models django-admin
Rectangle 27 0

It is easy, just overload has_add_permission method in your Admin class like so:

class MyAdmin(admin.ModelAdmin):
    def has_add_permission(self, request):
        return False

python - How to remove Add button in Django admin, for specific Model?...

python django django-models django-admin
Rectangle 27 0

Beside its (a bit awkward) hacking style, you could aslo override the template tag directly. Normally overriding template is more recommended.

# put this in some app such as customize/templatetags/admin_modify.py and place the app
# before the 'django.contrib.admin' in the INSTALLED_APPS in settings

from django.contrib.admin.templatetags.admin_modify import *
from django.contrib.admin.templatetags.admin_modify import submit_row as original_submit_row
# or 
# original_submit_row = submit_row

@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_row(context):
    ctx = original_submit_row(context)
    ctx.update({
        'show_save_and_add_another': context.get('show_save_and_add_another', ctx['show_save_and_add_another']),
        'show_save_and_continue': context.get('show_save_and_continue', ctx['show_save_and_continue'])
        })                                                                  
    return ctx

I think this is actually the best approach. First, I tried to do what you explain in # put this in some app such as customize/templatetags/admin_modify.py ... but it didn't work. Then, I put this piece of code at the beginning of the admin.py file and it works perfect.

@ManuelAlvarez fine. Perhaps your customize/templatetags/ lacked __init__.py and was thus not a package and got ignored. I'm not quite sure whether your admin.py solution works in all circumstances, we'll see :)

what's the purpose of that import * ? I tried to delete it, and import all those functions one by one, but my custom submit_row method is not called anymore. Any ideeas why ?

@NiCU It's a quick typing to import all requisites. Importing one by one is more appropriate. Perhaps your tag does not override the original one, because your custom app places after the original app in INSTALLED_APPS?

python - In Django admin, how can I hide Save and Continue and Save an...

python django django-templates django-admin
Rectangle 27 0

If you want to hide these buttons plainly for cosmetic purposes you can also use CSS and it might not be the best approach since you can enable them back by inspecting the css, it certainly is simple and still granular enough to only hide them on certain model admins.

class MyModelAdmin(admin.ModelAdmin)

    ....

    class Media:
        #js = ('' )  # Can include js if needed
        css = {'all': ('my_admin/css/my_model.css', )}

my_model.css is located in the static files folder in the path above.

/* Optionally make the continue and save button look like primary */
input[name="_continue"]{
    border: 2px solid #5b80b2;
    background: #7CA0C7;
    color: white;
}

/* Hide the "Delete", "Add Another" and "Save" buttons, customize this to what you need  */
.deletelink, input[name="_addanother"], input[name="_save"]{
    display: none;
}

The classes and names may change between django versions for these buttons, I am using Django 1.6.6 now and I don't think they have changed recently. If you want this to be effective on your entire admin site, you can copy admin/base_site.html default template into your static dir and overwrite the 'extrahead' block to include this style. See base_site.html.

Hopefully the CSS approach helps :) It certainly will not cause any errors for you.

Nice workaround -- I'll accept it in a few days if nobody else is able to trace the cause of the error.

Django admin model add_view: how to remove "save and add another" butt...

django django-templates django-admin django-1.6 django-guardian
Rectangle 27 0

obj = coconut_transportation.swallow.objects.all()[34]

# list url
url = reverse("admin:coconut_transportation_swallow_changelist")

# change url
url = reverse("admin:coconut_transportation_swallow_change", args=[obj.id])

# add url
url = reverse("admin:coconut_transportation_swallow_add", args=[obj.id])

The changelist for a particular model instance is not the "list of objects"

For a django model, how can I get the django admin URL to add another,...

django django-admin django-urls
Rectangle 27 0

First the "is it plugged in?" question -- Have you manually added new_field to the users table in the database? Syncdb wouldn't have taken care of that, of course.

After that, I would try appending the fields onto the existing UserAdmin rather than rebuilding it from scratch:

from django.contrib.auth.admin import UserAdmin

UserAdmin.list_display += ('new_field',)  # don't forget the commas
UserAdmin.list_filter += ('new_field',)
UserAdmin.fieldsets += ('new_field',)

Hmm.. dunno why I didnt think of that after using list_display = UserAdmin.list_display + ('new_field',).. thanks!

For the django admin, how do I add a field to the User model and have ...

django django-admin
Rectangle 27 0

It is preferred to write your own user profile class, and attach it to the User model. Then you can use the get_profile() method to retrieve the profile from the user.

Subclassing the profile admin from an Inline Admin should also allow you to edit the profile on the user's page, which is almost what you're trying to do.

For the django admin, how do I add a field to the User model and have ...

django django-admin
Rectangle 27 0

Just figured this out, perhaps this could help you as well.

Since you don't mention that you have a separate profile, if you want to simply add a column to the existing User admin, you can do the following in admin.py:

First you create a custom admin by subclassing UserAdmin:

class CustomUserAdmin(UserAdmin):
    list_display = UserAdmin.list_display + ('is_complete',)

    def is_complete(self, obj):
        # Example here, you can use any expression.
        return SomeOtherClass.objects.get(my_field=obj).is_complete()

    # Not required, but this gives you a nice boolean field:
    is_complete.boolean = True

Then unregister the existing UserAdmin and register your own:

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

For the django admin, how do I add a field to the User model and have ...

django django-admin
Rectangle 27 0

I got the 'that is missing from the form' error, and discovered that it was due to my field being marked as 'editable=False' in the model.

For the django admin, how do I add a field to the User model and have ...

django django-admin
Rectangle 27 0

This isn't possible with an 'out of the box' option as far as I can tell, but this is how I'd go about doing what you want to do.

The bit of code we care about is this templatetag - this seems to override show_save_and_add_another and show_save_and_continue regardless of what you have set it to. It also creates a whole new context and copies only certain values across (not clear what the justification for this is), so you'll have to modify it to get what you need.

  • Create a templatetag that replicates the functionality of the default tag, either by reusing the existing one (see okm's example) or by duplicating it entirely. The only change here is that it should either keep your show_save_and_add_another from the original context without overwriting it, or pass through your own really_hide_save_and_add_another_damnit context variable.
  • Replace change_form.html to include and use your own templatetag, replacing submit_row with it.
  • Update change_form.html if you've gone for the option of using an extra context variable, wrapping the buttons with another conditional statement.

Then, regardless of what option you went for, update your ModelAdmin with something like (based on this from the Django docs):

class MyModelAdmin(admin.ModelAdmin):
    # ...
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_save_and_add_another'] = False
        # or
        extra_context['really_hide_save_and_add_another_damnit'] = True
        return super(MyModelAdmin, self).change_view(request, object_id,
            form_url, extra_context=extra_context)

Updated: Original response didn't take in to account the submit_row not passing along any the whole original context.

It works well and I can test my 'really_hide_save_and_add_another_damnit' new var on change_form.html but it seems that I can't do it in submit_line.html since its value is '' in all cases. I've tried to test, check, print,... the value without success. Do I need to load any aditional library at the beginning of the template?

Sorry I didn't realise the submit_row templatetag doesn't copy the whole context across - only certain items. You'll need to override this templatetag, either entirely, or using okm's option.

python - In Django admin, how can I hide Save and Continue and Save an...

python django django-templates django-admin
Rectangle 27 0

You will need to change template django admin uses for model form. Make it readonly and add a button to original template linked to another url.

Also, I recommend using django-reversion for keeping history of objects and eliminating "accidental changes" risk.

Can you give a bit more detail about how to do this? (Regarding your other comments: I don't think you can argue that having a read-only view of an object is a bad idea, no matter how else things are designed. My only goal in this question is to get that readonly view by making use of how the admin interface is already able to nicely render things.)

django admin: separate read-only view and change view - Stack Overflow

django django-admin
Rectangle 27 0

This isn't possible with an 'out of the box' option as far as I can tell, but this is how I'd go about doing what you want to do.

The bit of code we care about is this templatetag - this seems to override show_save_and_add_another and show_save_and_continue regardless of what you have set it to. It also creates a whole new context and copies only certain values across (not clear what the justification for this is), so you'll have to modify it to get what you need.

  • Create a templatetag that replicates the functionality of the default tag, either by reusing the existing one (see okm's example) or by duplicating it entirely. The only change here is that it should either keep your show_save_and_add_another from the original context without overwriting it, or pass through your own really_hide_save_and_add_another_damnit context variable.
  • Replace change_form.html to include and use your own templatetag, replacing submit_row with it.
  • Update change_form.html if you've gone for the option of using an extra context variable, wrapping the buttons with another conditional statement.

Then, regardless of what option you went for, update your ModelAdmin with something like (based on this from the Django docs):

class MyModelAdmin(admin.ModelAdmin):
    # ...
    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['show_save_and_add_another'] = False
        # or
        extra_context['really_hide_save_and_add_another_damnit'] = True
        return super(MyModelAdmin, self).change_view(request, object_id,
            form_url, extra_context=extra_context)

Updated: Original response didn't take in to account the submit_row not passing along any the whole original context.

It works well and I can test my 'really_hide_save_and_add_another_damnit' new var on change_form.html but it seems that I can't do it in submit_line.html since its value is '' in all cases. I've tried to test, check, print,... the value without success. Do I need to load any aditional library at the beginning of the template?

Sorry I didn't realise the submit_row templatetag doesn't copy the whole context across - only certain items. You'll need to override this templatetag, either entirely, or using okm's option.

python - In Django admin, how can I hide Save and Continue and Save an...

python django django-templates django-admin
Rectangle 27 0

A modelform should not prevent you from doing this.

Make sure you don't move this code. You can't put field override code inside a ModelForm.

You use a ModelForm and have the overrides in the ModelAdmin (TabularInline).

i also dont see the "+" sign to add a new record in the media table. is there a way to solve that?

That means you either don't have permissions, or there's no modeladmin in place to add that model.

i have permission and there is a modeladmin. if i set my tabularadmin to work with the modelform - then there is no + sign. If i do not use the modelform, then i have the + sign.

Django: how can i add a field in admin that has a link to another mode...

django admin modelform
Rectangle 27 0

You can retrieve this from the actual object instance, this worked for me:

from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(object.__class__)
object_admin_url = django.core.urlresolvers.reverse("admin:%s_%s_change" % (content_type.app_label, content_type.model), args=(object.pk,))

For a django model, how can I get the django admin URL to add another,...

django django-admin django-urls
Rectangle 27 0

Despite your DB look up concerns for having a UserProfile, that is really the way you should go for this problem. There are two main reasons for this:

For the django admin, how do I add a field to the User model and have ...

django django-admin
Rectangle 27 0

A very different approach can be to add the following in /static/admin/css/base.css

input[name="_addanother"],input[name="_continue"],input[name="_saveasnew"]{
    display: none;
}

python - In Django admin, how can I hide Save and Continue and Save an...

python django django-templates django-admin