Current user in django admin - python

I've tried numerous methods of finding the current user ID in django's administration. I've tried pulling the user ID via SessionKey and request.user (HTTPRequest) to no avail. My latest incarnation is:
def save(self, request, obj, form, change):
if getattr(obj, 'submitter', None) is None:
obj.submitter = request.user
obj.save()
super(AppAdmin, self).save()
in admin.py and
submitter = models.ForeignKey(User, null=True, blank=True, related_name="submitter")
in models.py. I found this elsewhere on stack overflow, but it doesn't seem to work. Any help is appreciated.
Thanks!

From the looks of your snippet, you are trying to save the currently logged in user to your model field in a ModelAdmin
It looks like you meant to override save_model
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
class AppAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.submitter = request.user # no need to check for it.
obj.save()

Related

How do you edit a many to many field in Django during save?

I currently have a model that looks like this
class Sector():
featured_companies = models.ManyToManyField('Company', related_name='sectors')
def save(self, **kwargs):
super(Sector, self).save(**kwargs)
for company in self.featured_companies.all():
company.is_active = True
company.save()
I know that this doesn't work because of the way Django works on save. I read in another post that adding something like this to the admin should work:
def save_model(self, request, obj, form, change):
if obj.featured_companies:
form.cleaned_data['featured_companies'] = obj.featured_companies.all()
super(SectorAdmin, self).save_model(request, obj, form, change)
However, it is still not working. How would I accomplish editing the many to many field during the save process?
You can override the save_related(…) method [Django-doc] of your ModelAdmin and set the is_active field to True with a single query:
class SectorAdmin(ModelAdmin):
# …
def save_related(self, request, form, formsets, change):
super().save_related(request, form, formsets, change)
form.instance.featured_companies.all().update(
is_active=True
)

How to override Django Admin

I have two models Restaurant and Details. The superuser assigns each restaurant a user.When that user logs into admin i want only those Details associated with that user's Restaurant to be shown,and he should be able to edit them as well.
I tried to override admin's queryset function but to no success.Any help would be appreciated. This is what i did so far
I am just a beginner in Django.
class RestaurantAdmin(admin.ModelAdmin):
model = Details
def save_model(self, request, obj, form, change):
obj.user = request.user
super(RestaurantAdmin, self).save_model(request, obj, form, change)
def queryset(self, request):
print(request.user)
qs = super(ResaturantAdmin, self).queryset(request)
# If super-user, show all comments
if request.user.is_superuser:
return qs
return qs.filter(owner=request.user)
admin.site.register(Restaurant)
admin.site.register(Details,RestaurantAdmin)
The method you need to override is called get_queryset, not queryset.

Django Admin class to auto-populate user field

I am trying to populate the field 'owner' in the my NoteForm. I read in documentation that I need to use the Admin for that.But i still get this error : note_note.owner_id may not be NULL. Need help. Code:
forms.py:
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title','body')
models.py:
class Note(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
cr_date = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, blank=False)
admin.py
class NoteAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj = form.save(commit=False)
obj.owner = request.user
obj.save()
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
instance.user = request.user
instance.save()
else:
fromset.save_m2m()
admin.site.register(Note, Noteadmin)
views.py:
def create(request):
if request.POST:
form = NoteForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponceRedirect('/notes/all')
else:
form = NoteForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_note.html', args)
I do not understand the point of Admin over here. From the code, what I understood is you creating a simple django form for your site and getting the error on form submission. If that's case, the solution is quiet easy. This error is generated because you are try to save a record in your Note model without any reference to User. As there's a db constraint on the foreign key field, it raises the error. Solution is easy, just add owner to the list of fields in the form or modify the save method to assign an owner to the note. If you'll use the first option, the user will be able to see and select the owner. And if you want to pre-populate that particular field, pass initial value to the form.

Auto Inserting Logged In Users Username in Django

In the Django Administrative Interface I'd like to Automatically Insert a logged in users username along with a blog post when the publish it, currently I have it displaying every user in a drop down to select from but obviously this is not great so I'd like it to automatically input this.
Here is my code:
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
published_date = models.DateTimeField('date published')
author = models.ForeignKey(User, db_column="published_who")
def __unicode__(self):
return self.title
admin.py
from blog.models import Post
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.save()
admin.site.register(Post, PostAdmin)
Many Thanks!
As I understand issue you need to exclude author from admin form:
class PostAdmin(admin.ModelAdmin):
exclude = ['author']
What you should use is in the Django docs: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey
You can overwrite the default behaviour of a ForeignKeyField in the admin with this.
Something along the lines of:
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == "author":
kwargs["initial"] = request.user
return super(PostAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
*This is untested
EDIT:
I didn't know whether you wanted to entirely disable the dropdown. With this method you wont. Instead you will have a default value of request.user but still be able to select another user.
If you want to make it a drop down with only one selection (weird behaviour :P) you could add:
kwargs["queryset"] = Post.objects.filter(author=request.user)

Auto-populating created_by and actionDate field with Django admin site

I have a model like this:
class Tour(models.Model):
Name=models.CharField(max_length=100)
Count=models.SmallIntegerField()
ActionDate=models.DateTimeField(editable=False)
ActionUser=models.ForeignKey(User,editable=False)
StatusType=models.ForeignKey(StatusType)
now I wanna auto populate current user in my Tour,so I used this code in admin.py:
def save_model(self, request, obj, form, change):
instance = form.save(commit=False)
instance.ActionUser = request.user
instance.save()
form.save_m2m()
return instance
admin.site.register(Tour,TourAdmin)
it work great and it auto polulate current User in my Tour Table,but now I can't save current date in ActionDate field,I added this code to save_model but it cause error:
self.ActionDate=datetime.datetime.today()
then I tryed to override save in my Tour Model :
def save(self,*args,**kwargs):
self.ActionDate=datetime.datetime.today()
super(Tour, self).save(*args,**kwargs)
but this cause error,too.
what should I do to auto populate both ActionUser and ActionDate?
tnx in advance
Why don't you use auto_now in the field definition?

Categories

Resources