I my model users can create rifles and this rifle is obviously associated with a User.
class Gun(ImageModel):
user = models.ForeignKey(User)
...
...
...
I have another model which is dependent on this and need to make use of the users rifles, but when the user adds a record I only want to display his rifles.
mt model looks as follows
class Trophies(ImageModel):
used_his = models.ForeignKey(Gun)
my form looks as follows
from django.forms import ModelForm
from django import forms
from models import Trophies
from gunsafe.models import Gun
from django.contrib.auth.models import User
class TrophiesForm(request.user, ModelForm):
used_his = forms.ModelMultipleChoiceField(queryset=Gun.objects.filter(user__id=1))
def __init__(self, user, *args, **kwargs):
super(TrophiesForm, self).__init__(*args, **kwargs)
self.fields['used_his'].queryset = User.objects.filter(pk = user)
I was wondering how I can get the current logged in users ID instead of the user__id=1
Here is the view.
def edit(request, trophy_id, template_name='trophies/edit.html'):
trophy = Trophies.objects.get(pk=trophy_id)
if request.method == 'POST':
form = TrophiesForm(request.POST, request.FILES, instance=trophy)
if form.is_valid():
newform = form.save(commit=False)
newform.user = request.user
newform.save()
...
...