how to remove --------- from django Select widgets - django

How do I remove the ----- in my django ModelForm widgts?
documentation say to use empty_label but it is for SelectDateWidget
my form
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
exclude = ('copy', 'created', 'researcher', 'keywords', 'application_area', 'predominant_area')
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Titulo da oportunidade'
}),
'conclusion_date':forms.TextInput(attrs={
'class': 'form-control',
'type':'text',
'placeholder':'Data de conclusão'
}),
'category': forms.RadioSelect(attrs={
'class':'form-control'
}),
'result':forms.Select(attrs={
'class':'form-control'
}),
}

You can add default value for your select input then it will show default value initially.
For further reference:
https://docs.djangoproject.com/en/2.0/topics/forms/
https://docs.djangoproject.com/en/2.0/ref/forms/fields/

Related

showing date from db in html date in django

How can i show date from db in django html template with input type date.
As You can see if we use input type 'date'. we can see the below widget showing in html. But if i want to it to show date from DB in below picture. Is there anyway i can do?
Showing like this, so user can see the current date from DB and change if needed.
forms.py
class ProfileUpdateForm(ModelForm):
#birthdate = forms.DateField(
# input_formats=['%dd-%mm-%yyyy'],
# widget=forms.DateInput(format='%dd-%mm-%yyyy', attrs={'type': "date"})
# )
class Meta:
model = User
fields = [
'email',
'full_name',
'address',
'city',
'state',
'postcode',
'phone_number',
'birthdate',
]
widgets = {
'full_name': Textarea(attrs={'cols': 35, 'rows': 1}),
'address': Textarea(attrs={'cols': 80, 'rows': 3}),
'city': Textarea(attrs={'cols': 35, 'rows': 1}),
'birthdate': forms.DateInput(format='%d %b %Y', attrs={'type':'date'}),
}

How to acsess the session variable in forms.py outside of Formclass in django

I am new to django
I need to create dropdown in form and the dropdown needs to update with values from the database based on some lookup . The look up will change based on the request
Here is the code
from django import forms
from .models import Configuration
from django.db.models import Q
from configuration.models import Configuration
def getschema():
x=[]
#change the hardcoded 8 here
allschema = Configuration.objects.filter(project_id = request.session['project_id'])
for schema in allschema:
print(schema.schema_name)
x.append((schema.schema_name,schema.schema_name))
return x
class TestCaseForm(forms.Form):
TestcaseName = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "Test Case Name",
"name" : "testcasename",
}))
TestcaseDescription = forms.CharField(
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "Test Case Description",
"name" : "testcasedesc",
}))
SourceSchema= forms.CharField(label='Select Source Schema', widget=forms.Select(choices=getschema(),attrs={"name": "srcschema"}))
TargetSchema= forms.CharField(label='Select Target Schema', widget=forms.Select(choices=getschema(),attrs={"name": "srcschema"}))
SourceQuery = forms.CharField(widget=forms.Textarea(
attrs={
"rows":4, "cols":50,
"class": "form-control",
"placeholder": "Source query",
"name": "sourcequery",
}))
TargetQuery = forms.CharField(widget=forms.Textarea(
attrs={
"rows":4, "cols":50,
"class": "form-control",
"placeholder": "Target query",
"name": "targetquery",
}))
def __init__(self,*args,**kwargs):
self.request = kwargs.pop('request',None)
super(TestCaseForm,self).__init__(*args,**kwargs)
def clean(self):
print(self.request.user.id)
My question is how to use the session object inside my getschema() method
If the choices depend on the request, you should initialise them in your form's __init__() method, not in the class attribute. Also you don't need to do that with the widget, if you make them a ModelChoiceField instead of a CharField:
class TestCaseForm(forms.Form):
# remove SourceSchema since the queryset cannot be determined when the class is initialised
def __init__(self, *args, **kwargs)
request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
self.fields['SourceSchema']= forms.ModelChoiceField(
queryset=Configuration.objects.filter(
project_id = request.session['project_id']
)
)
Note that by default this will use the __str__() method of your Configuration model to represent the objects in the drop-down. If you want to have a different representation, then you should subclass ModelChoiceField and use that in your form:
class ConfigurationChoiceField(forms.ModelChoiceField):
def label_from_instance(self, configuration):
return configuration.schema_name
You can create a new variable for the session object and pass it to the getschema()

Django: dynamic choice field for formsets

So I have a form
class DownloadForm(forms.Form):
title = forms.CharField()
device_family = forms.ChoiceField(label="Device Family",
widget=forms.Select(attrs={'class': 'form-control',
'data-toggle': 'select'}),
choices=LOG_ENTRY_TYPES, required=True
)
and in view.py I do
LOG_ENTRY_TYPES = (
('', 'All'),
('auth', 'Auth'),
('error', 'Error'),
('info', 'Info'),
('proxy', 'Proxy'),
)
DownloadFormSet = formset_factory(DownloadForm)
formsets = DownloadFormSet(initial=[
{'title': 'Django is now open source', 'device_family': LOG_ENTRY_TYPES},
{'title': 'Django source 2', 'device_family': LOG_ENTRY_TYPES},
{'title': 'Django source 3', 'device_family': LOG_ENTRY_TYPES}
])
This creates the device_family field but the LOG_ENTRY_TYPES choices are not generated. So how can I pass the LOG_ENTRY_TYPES choices to the device_family choices field so that the drop down shows the choices.

optional int(request.POST.get('timeout') throws error when empty

This field timeout = int(request.POST.get('timeout')) throws an error saying
invalid literal for int() with base 10: ''
this is my model field: timeout = models.IntegerField(default=10)
The forms submits just fine if I submit number because the form interprets it as a string but my form handler will convert it into integer. But it fails if I leave the field blank. Seems like it can't process an empty string.
What can I do ?
forms.py:
class TestCaseSuiteForm(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Name'}), label='')
documentation = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Documentation'}), label='')
setup = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Setup'}), label='')
teardown = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter teardown'}), label='')
force_tags = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Force Tags'}), label='')
timeout = forms.IntegerField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Timeout (optional)'}),
required=False, label='')
class Meta:
model = TestCase
fields = [
'name',
'documentation',
'force_tags',
'setup',
'teardown',
'timeout',
]
my view:
def index(request):
if request.method == 'POST':
form_tc = TestCaseForm(request.POST)
form_ts = TestCaseSuiteForm(request.POST)
if form_tc.is_valid() or form_ts.is_valid():
form_tc.save()
form_ts.save()
return redirect('/list')
In case you're wondering ... I've got two forms using one submit button.
Having gone to the trouble of defining a form and validating it, you are supposed to use that validated data, rather than resorting to the raw post data. Not only will the validated data use defaults as defined in the form where necessary, it will also convert types etc.
if form_tc.is_valid() and form_ts.is_valid():
TestCase.objects.create(
name=form.cleaned_data['name'],
documentation=cleaned_data['documentation'],
...
)
Note, you need to use the unprefixed field names as the keys here.
But this still isn't really getting you what you want. You haven't defined all your model fields as form fields, so you won't get defaults for the fields you haven't defined. Instead you should be using a model form.
class TestCaseSuiteForm(forms.ModelForm):
class Meta:
model = TestCase
fields = ['name', 'documentation', ...]
and now in your view you simply save the form to create the objects:
if form_tc.is_valid() and form_ts.is_valid():
form_tc.save()
form_ts.save()
Now your model defaults will be used appropriately.
Set a default using:
timeout = int(request.POST.get('timeout', 0))

Django Forms - Can't raise validation error in tests

I'm struggling to get my tests to throw a form validation error in Django. This is using standard/default input types.
# forms.py
class NewUserForm(forms.Form):
first_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'First Name'})),
last_name = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Last Name'})),
email = forms.EmailField(),
mobile = floppyforms.CharField(
required=False,
widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Mobile number', 'autocomplete': 'false'})),
postcode = floppyforms.CharField(widget=floppyforms.TextInput(attrs={'class': 'form-control input-lg', 'placeholder': 'Postcode'})),
super_balance = floppyforms.CharField(widget=floppyforms.RangeInput(attrs={'class': 'bar', 'type': 'range', 'id': 'rangeinput',
'value': '492500', 'min': '75000', 'max': '1000000',
'step': '5000', }))
# tests.py
class NewUserFormTest(TestCase):
def setUp(self):
self.valid_data = {
'first_name': 'herp',
'last_name': 'derp',
'email': 'herp#derp.com',
'mobile': '0412345678',
'postcode': '00000',
'relationship_status': 'S',
'super_balance': '100000',
'current_super_provider': '49'
}
...
def test_invalid_fields(self):
form = NewUserForm({})
self.assertFalse(form.is_valid()) # correct
data = self.valid_data
data['email'] = 24234 # this field should fail
form = NewUserForm(data)
form.is_valid() # returns True
When I pass a blank dictionary to the initial form. form.errors displays {'super_balance': ['This field is required.']}. This is more confusing because the documentation states that unless explicitly declared then all fields are assumed to be required.
I'm using 1.8.5
Cheers in advance
You need to remove the trailing commas from all the fields in your form.
Instead of
class NewUserForm(forms.Form):
...
email = forms.EmailField(),
...
it should be
class NewUserForm(forms.Form):
...
email = forms.EmailField()
...
At the moment, NewUserForm.email is a tuple, not a field, so any values for that field in the data dictionary are ignored. The only field without the trailing comma is super_balance, which is why it is the only error that appears when you pass a blank dictionary to the form.