I'm creating a simple model form that is only available to staff. It has a user selection dropdown list populated by models.py user = models.ForeignKey(User, on_delete=models.CASCADE)
.
On submit I need my view to look up the selected user from the form and return the data in the models for that user (from the built-in Django database). How would I go about doing this?
I have searched here and the recommended articles, but they all appear to be for accessing a model as the logged-in user. Here is a screenshot of the form and my code:
models.py
class GetData(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
forms.py
class DataRequestForm(forms.ModelForm):
class Meta:
model = GetData
fields = ['user']
Views.py
@login_required
def data_form(request):
if request.user.is_staff == True:
if request.method == 'POST':
form = DataRequestForm(request.POST)
if form.is_valid():
user = request.POST["user"]
print("Form is Valid")
print(user)
# How to access that user's model data here?
CodePudding user response:
You should first get user by id then get model details using that retrieved user.
views.py
@login_required
def data_form(request):
if request.user.is_staff == True:
if request.method == 'POST':
form = DataRequestForm(request.POST)
if form.is_valid():
user = request.POST["user"]
print("Form is Valid")
print(user)
# getting user data by id.
get_user = get_object_or_404(User, id=user)
get_another_model_data = SecondModel.objects.filter(user=get_user)
# perform or save the data here