How do I remove Label text in Django generated form? - python

I have a form that is displaying well only for the label text that I don't want and I have tried all I could to let it off my form but it won't just go...
forms.py:
class sign_up_form(forms.ModelForm):
class Meta:
model = Users
fields =['email']
widgets = {
'email': forms.EmailInput(attrs={
'id': 'email',
'class': 'form-control input-lg emailAddress',
'name': 'email',
'placeholder': 'Enter a valid email'})}
I have tried:
views.py:
from django.shortcuts import render
from mysite.forms import sign_up_form
def register(request):
sign_up = sign_up_form(auto_id=False)
context = {'sign_up_form': sign_up}
return render(request, 'mysite/register.html', context)
I need my widgets as defined above.

In ModelForms there will be default labels so you have to over-ride where you don't need labels
you can define it like this
class sign_up_form(forms.ModelForm):
email = forms.CharField(widget=forms.Textarea, label='')
class Meta:
model = Users
fields =['email']
This method will not include labels for your form, other method depends on rendering in template. You can always avoid labels from form
<label>MY LABEL</label> instead of {{ form.field.label }}

In __init__ method set your field label as empty.This will remove label text.
def __init__(self, *args, **kwargs):
super(sign_up_form, self).__init__(*args, **kwargs)
self.fields['email'].label = ""

If you're wanting to remove all labels, you can use:
class sign_up_form(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for key, field in self.fields.items():
field.label = ""

Related

Using django crispy-forms wrap to wrap multiple properties

I have a form with lots of repetition and I want to use the wrap function of django crispy forms to reduce this. This is the form as it stands:
class MyForm(ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.layout = Layout(
Row(Field(PrependedText('field1', 'Field1title', wrapper_class='col-12 stretchprepend')),
title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip',
data_bs_placement='bottom', data_html="true"),
#fields 2-29
Row(Field(PrependedText('field30', 'Field30title', wrapper_class='col-12 stretchprepend')),
title = self.base_fields['field1'].help_text, data_bs_toggle='tooltip',
data_bs_placement='bottom', data_html="true")
)
CHOICES = [tuple([x,x]) for x in range(1,8)]
help_text = {'field1': ''''help text for field 1''' #etc for other fields)
field1 = IntegerField( label='Field1title', widget=Select(choices=CHOICES), help_text=help_text['field1'])
# Repeat up to field 30
class Meta:
model = mymodel
fields = ['field1',...,'field30']
I can get wrap to generate some aspects of the form like so:
self.helper.layout('field1'...'field30')
self.helper[:].wrap(Field, wrapper_class='col-12 stretchprepend')
I cant' seem to get it to work to include all the other aspects e.g. PrependedText, title, data_bs_toggle etc Please could anyone advise?

Pass request.user parameter to modelformset_factory form

So I've a formset tied to a model and one of the fields in that is ForeignKey.
models.py
class Squad(models.Model):
rid = models.AutoField(primary_key=True)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
def __str__(self):
return self.team.tname
forms.py
class SquadForm(ModelForm):
class Meta:
model = Squad
def __init__(self, logged_user, user, *args, **kwargs):
super(SquadForm, self).__init__(*args, **kwargs)
self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None")
As you can see, the __init__ function is expecting an extra parameter logged_user which I'm hoping to pass via the views.py file. But if I do the following:
views.py
def choose_teams(request):
teamformset = modelformset_factory(Squad, extra=2, form=SquadForm(request.user))
form = teamformset(queryset=Squad.objects.none())
return render(request, 'foo.html', {'form':form})
I'm trying to pass the logged in user as a parameter on line 2 but this is resulting in the following message:
Field 'id' expected a number but got 'SquadForm'
Not sure what I'm missing here. But if I remove the parameter from line 2:
teamformset = modelformset_factory(Squad, extra=series.team_number, form=SquadForm)
it starts working (of course, I no longer expect the user in the forms.py file and remove it too) but shows all the data and not filtered one.
You can pass additional keyword arguments to your formset form by passing form_kwargs={} to your formset
class SquadForm(ModelForm):
class Meta:
model = Squad
def __init__(self, *args, logged_user, **kwargs):
super(SquadForm, self).__init__(*args, **kwargs)
self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None")
teamformset = modelformset_factory(Squad, extra=2, form=SquadForm)
form = teamformset(queryset=Squad.objects.none(), form_kwargs={'logged_user': request.user})

django add placeholder text to form field

In Django I have the below code which is creating a username and password form on an HTML Page:
<div class="control-group">
{{ form.username }}
</div>
<div class="control-group">
{{ form.password }}
</div>
I want to add "Username" and "Password" placeholder text within the field, and then when the user clicks on the field the word dissapears. What is the best way to achieve this ?
You must use the placeholder properties
class LoginForm(forms.Form):
username = forms.CharField(label='username')
password = forms.CharField(label='password')
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['placeholder'] = 'username'
self.fields['password '].widget.attrs['placeholder'] = 'password'
or
class LoginForm(forms.Form):
username = forms.CharField(label='username',widget=forms.TextInput(attrs={'placeholder':'username'}))
password = forms.CharField(label='password',widget=forms.PasswordInput(attrs={'placeholder':'password'}))
In case it might help someone, I wanted to use the help_text property of a model as the placeholder. This is the simplest way I could figure it out, based on aziminia's answer:
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for _, value in self.fields.items():
value.widget.attrs['placeholder'] = value.help_text
class Meta:
model = models.MyModel
fields = (...)
I hope you do have a forms.py file in your project. While creating your form, you can use following to set placeholder for your fields:
username = forms.CharField(label='username',
widget=forms.TextInput(attrs={'placeholder': 'username'}))
If you have ModelForm in your project you can implement as:
class MyForm(forms.ModelForm):
class Meta:
model = User
widgets = {
'username': forms.TextInput(attrs={'placeholder': 'username'}),
..........
}
In case if you want to have field name as a placeholder, you can use code below:
class LoginForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
for k,v in self.fields.items():
v.widget.attrs['placeholder'] = k.capitalize()
Otherwise please refere to this answer.

django-crispy form - hide field label

I have a cripsy django form.
What is the best way to hide the field label in the template when I use {% cripsy form %}?
I do not want the user to see MY_FIELD_1 and MY_FIELD_2.
class mYForm(forms.ModelForm):
MY_FIELD_1 = forms.BooleanField()
MY_FIELD_2 = forms.BooleanField()
def __init__(self, *args, **kwargs):
...
...
self.helper = FormHelper()
self.helper.layout = Layout(
Field('MY_FIELD_1',),
Field('MY_FIELD_2',),
)
...
If you want to remove all labels from your form when using the crispy forms FormHelper then you can use:
self.helper.form_show_labels = False
If you want to remove labels from certain fields then you can do
self.fields['some_field'].label = False
Where some_field is the name of the field whose label you want to remove.

not show field in form if user is authenticated

I do not want to show one form field if user is authenticated.
I tried if not request.user.is_authenticated():
but it's not working.
def create_event(request):
if not request.user.is_authenticated():
CreateEventForm.base_fields['owner_email'] = forms.EmailField(required=True)
event_form = CreateEventForm(request.POST or None, prefix='event')
context = {
'event_form': event_form,
}
if event_form.is_valid():
event = event_form.save(commit=False)
if request.user.is_authenticated():
event.registered_owner = request.user
else:
event.owner_email = event_form.cleaned_data.get('owner_email')
event = event_form.save()
return HttpResponseRedirect('/event-%s' %event.id)
return render(request, 'create_event.html', context)
Form in forms.py
class CreateEventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'description', 'location', 'duaration', 'private']
You should never modify base_fields; that's a class attribute, so once you add something to it, it's present for all form instances until you explicitly remove it.
Instead, move this logic into the __init__ method for the form itself.
class CreateEventForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
is_authenticated = kwargs.pop('is_authenticated', False)
super(CreateEventForm, self).__init__(*args, **kwargs)
if is_authenticated:
self.fields['owner_email'] = forms.EmailField(required=True)
Now in your view you need to pass that parameter to the form:
event_form = CreateEventForm(request.POST or None, prefix='event', is_authenticated=request.user.is_authenticated())

Categories

Resources