How do I filter form's field queryset? After a little search I found that this way it's done. But I am getting an error here.
class TbPeopleEntranceRightForm(forms.ModelForm):
def __init__(self, user=None, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
print(self.user)
self.fields['user'].queryset = self.user
class Meta:
model = TbPeopleEntranceRight
fields = ['user', 'area', 'room']
'TbUser' object has no attribute 'all'
self.fields['user'].queryset = self.user
here self.fields["user"].queryset expects a queryset where you are providing a user instance.
You might want to do something like this.
class TbPeopleEntranceRightForm(forms.ModelForm):
def __init__(self, user=None, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
print(self.user)
self.fields['user'].queryset = YourUserModel.objects.filter(id=self.user.id)
class Meta:
model = TbPeopleEntranceRight
fields = ['user', 'area', 'room']
Related
I have the below code structure. I want to get the request.user information inside StaffForm.
How do I pass the user info to that class
class UserProfileAdmin(admin.ModelAdmin):
class UserProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
pass
class StaffForm(UserProfileForm):
def __init__(self, *args, **kwargs):
pass
class Meta:
model = models.UserProfile
fields = ()
class SuperUserForm(UserProfileForm):
def __init__(self, *args, **kwargs):
pass
class Meta:
model = models.UserProfile
fields = ()
search_fields = [
'email',
'name'
]
def get_form(self, request, obj=None, **kwargs):
if request.user.is_superuser:
return self.SuperUserForm
else request.user.is_staff:
return self.StaffForm
class Book(models.Model):
description = models.CharField(max_length=10)
pdf = models.FileField(upload_to='books/pdfs/')
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.description
def delete(self, *args, **kwargs):
self.pdf.delete()
super().delete(*args, **kwargs)
#forms.py
class BookForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(BookForm, self).__init__(*args, **kwargs)
class Meta:
model = Book
fields = ('description', 'pdf', 'user')
When i run an application it shows all the users, I want to restrict to only current user who is logged in.
I can't figure out why my validators doesn't work at all.
Form is not invalid
Model doesn't raise ValidationError when being saved
For input: "123456sdad"
I have a model which has broker_ico field:
REGEX_ICO = r"\d{6,8}"
broker_ico = models.CharField(max_length=100, verbose_name='IČO',
validators=[RegexValidator(REGEX_ICO)])
I've overwritten save method:
def save(self, **kwargs):
print('full clean')
self.full_clean()
super().save(**kwargs)
Moreover the form is a ModelForm:
class BusinessCaseDocumentForm(ModelForm):
class Meta:
model = BusinessCaseDocument
exclude = ['id','business_case']
def __init__(self, *args, **kwargs):
super(BusinessCaseDocumentForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
fs_helpers.add_widget_attribute('class', 'form-control', field)
UpdateView:
class BusinessCaseDocumentUpdateView(SuccessMessageMixin, UpdateView):
model = BusinessCaseDocument
form_class = BusinessCaseDocumentForm
template_name = "business_cases/businesscase_documents/create.html"
success_message = "Podklad k obchodnému prípadu bol upravený"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['businesscase'] = self.object.business_case # TODO self.businesscase set
return context
def get_success_url(self):
return reverse("business_cases:list")
Can you see where is the problem?
I have a form where I am trying to limit the choices which appear in the field 'question' (In this case, I only want questions which the user has created). This method has worked with other forms, but it doesn't work this time - probably because it is a ModelFormset rather than just a ModelForm
The exact error is - 'NoneType' object has no attribute 'username', which I suspect means that the 'user' object is not being passed to AnswerForm's constructor. Problem is, I have no idea why it's not being passed
#views.py
def add_answer(request):
a_form = modelformset_factory(Answer, form=AnswerForm(user=request.user), fields='__all__', min_num=2, max_num=4, validate_min=True)
if request.method == "POST":
form = a_form(request.POST)
if form.is_valid():
#Do something
return render(request, 'site/addanswer.html', {'a_form': a_form})
#forms.py
class AnswerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(AnswerForm, self).__init__(*args, **kwargs)
self.fields['question'] = forms.ModelChoiceField(queryset=Question.objects.filter(user__username=self.user.username))
class Meta:
model = Answer
fields = ('question', 'answer', 'correct')
#models.py
class Question(models.Model):
user = models.ManyToManyField(User)
test = models.ForeignKey(Test, on_delete=models.CASCADE)
question = models.TextField(max_length=1000)
def __str__(self):
return "{0}".format(self.question)
class Answer(models.Model):
question = models.ForeignKey(Question)
answer = models.TextField(max_length=1000)
correct = models.BooleanField()
def __str__(self):
return "{0}".format(self.answer)
Maybe self.user get overwritten by super. Also there is no need to query user.username.
#forms.py
class AnswerForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(AnswerForm, self).__init__(*args, **kwargs)
self.fields['question'] = forms.ModelChoiceField(queryset=Question.objects.filter(user=user))
class Meta:
model = Answer
fields = ('question', 'answer', 'correct')
I have this class which I need to inherit.
class AuthenticationForm(forms.Form):
username = forms.CharField(label=_("Username"), max_length=30)
password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
def __init__(self, request=None, *args, **kwargs):
super(AuthenticationForm, self).__init__(*args, **kwargs)
Coul you tell me how I could inherit this and remove the username variable from the super class?
class LoginForm(AuthenticationForm):
email = forms.EmailField(
required=True, label=_("Email")
)
def __init__(self, request, *args, **kwargs):
#del super(LoginForm, self).username
super(LoginForm, self).__init__(
request, *args, **kwargs
)
Thanks
Since this is Django, you can just remove it from the fields dict:
class LoginForm(…):
def __init__(…):
super(LoginForm, self).__init__(…)
self.fields.pop('username')