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')
Related
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']
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 am trying to pass a kwarg from CreateView to a ModelForm so I can dynamically adjust the fields based on values in the related Parent object. Other answers have indicated that passing a kwarg by overriding get_form_kwargs in the view and catching it with kwarg.pop in the form should work, but I get an AttributeError: 'ChildForm' has no attribute 'get' when I try. Passing the kwarg into the view context works, but doesn't give me access to the value inside the form instance.
models.py:
class Parent(models.Model):
name = models.CharField(max_length=255)
details = models.CharField(max_length=255)
detailstwo = models.CharField(max_length=255, null=True)
child_mod = models.BooleanField(default=False)
slug = models.SlugField()
creator = models.ForeignKey(User)
def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super(Parent, self).save(*args, **kwargs)
def __str__(self):
return self.name
class Child(models.Model):
parent = models.ForeignKey(Parent)
parent_mod = models.CharField(max_length=255)
child_name = models.CharField(max_length=255)
def __unicode__(self):
return self.child_name
views.py:
class ChildCreateView(CreateView):
model = Child
form_class = ChildForm
template_name = 'testapp/child_form.html'
def dispatch(self, *args, **kwargs):
return super(ChildCreateView, self).dispatch(*args, **kwargs)
def get_form_kwargs(self, **kwargs):
kwargs = super(ChildCreateView, self).get_form_kwargs()
parent = get_object_or_404(Parent, slug=self.kwargs['parent_slug'])
kwargs['parent'] = parent
return kwargs
def get_context_data(self, **kwargs):
context = super(ChildCreateView, self).get_context_data(**kwargs)
parent = get_object_or_404(Parent, slug=self.kwargs['parent_slug'])
context['parent'] = parent
return context
def form_valid(self, form):
child = form.save(commit=False)
parent_slug = form.data['parent_slug']
parent = get_object_or_404(Parent, slug=parent_slug)
child.parent = parent
return super(ChildCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('testapp:parent_view', kwargs={'slug': self.object.parent.slug})
forms.py:
class ChildForm(forms.ModelForm):
class Meta:
model = Child
fields = ['parent', 'parent_mod', 'child_name']
def __init__(self, *args, **kwargs):
self.parent_object = kwargs.pop('parent')
assert isinstance(self.parent_object, Parent)
super(ChildForm, self).__init__(self, *args, **kwargs)
self.fields["parent_slug"] = forms.CharField(widget=forms.HiddenInput())
if not self.parent_object.child_mod:
del self.fields['parent_mod']
Full Traceback is here: http://dpaste.com/2QBMRJX