Search code examples
djangodjango-admindjango-users

Django admin, how to restrict a user to insert records only within his country?


I have this Model

  title= country = models.CharField(max_length=25)
  country = models.ForeignKey(Country)
  city = models.ForeignKey(City)
  user = country = models.ForeignKey(User)

Using the (Add Case +)page in the default Django admin, is there anyway to customise the country and city dropdown lists options depending on the current user?
For example: if the current logged in user is from USA, then the country dropdown list will show only one option (USA), and the city dropdown list will show only the cities in USA.Then, this user would be allowed only to add cases related to his/her country.


Solution

  • To answer your question: yes of course this is possible - IF you know which country your user belongs too of course.

    You'll have to

    1/ exclude the country field from the form,

    2/ use formfield_for_foreignkey() to filter the city field's queryset

    3/ and manually populate the model's field in your ModelAdmin's save_model() method

    Note that just reading the modeladmin's doc could have answered your question - there are examples for very similar use cases.