Note that there are some explanatory texts on larger screens.

plurals
  1. POdjango-admin formfield_for_* change default value per/depending on instance
    text
    copied!<p>I'm trying to change the <em>default value</em> of a foreignkey-formfield to set a Value of an other model <em>depending on</em> the logged in <em>user</em>. But I'm racking my brain on it...</p> <p>This: <a href="https://stackoverflow.com/questions/2194728/changing-foreignkeys-defaults-in-admin-site">Changing ForeignKey’s defaults in admin site</a> would an option to change the empty_label, but I need the default_value.</p> <pre><code>#Now I tried the following without errors but it didn't had the desired effect: class EmployeeAdmin(admin.ModelAdmin): ... def formfield_for_foreignkey(self, db_field, request=None, **kwargs): formfields= super(EmployeeAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs) if request.user.is_superuser: return formfields if db_field.name == "company": #This is the RELEVANT LINE kwargs["initial"] = request.user.default_company return db_field.formfield(**kwargs) admin.site.register(Employee, EmployeeAdmin) ################################################################## # REMAINING Setups if someone would like to know it but i think # irrelevant concerning the problem ################################################################## from django.contrib.auth.models import User, UserManager class CompanyUser(User): ... objects = UserManager() company = models.ManyToManyField(Company) default_company= models.ForeignKey(Company, related_name='default_company') #I registered the CompanyUser instead of the standard User, # thats all up and working ... class Employee(models.Model): company = models.ForeignKey(Company) ... </code></pre> <p>Hint: kwargs["default"] ... doesn't exist.</p> <p>Thanks in advance, Nick</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload