How can I change data display in Text Input of ModelChoiceField?
up vote
0
down vote
favorite
Is there any what to change data display in readonly InputField of ModelChoiceField, but retain the primary key of the object for submitting the form?
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y')
initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room'))
initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start'))
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['room'].widget = forms.TextInput()
self.fields['start'].widget = forms.TextInput()
self.fields['room'].widget.attrs['readonly'] = True
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'], initial_args['date'], initial_args['start'])
def clean(self):
cleaned_data = super(BookingForm, self).clean()
now = timezone.localtime(timezone.now())
bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date'])
booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone())
booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone())
for booking in bookings:
if booking.check_overlap(booking_start_time, booking_end_time):
raise forms.ValidationError
if now > datetime.datetime.combine(cleaned_data['date'],
cleaned_data['start'].end, timezone.get_current_timezone()):
raise forms.ValidationError
return cleaned_data
booking_add.html
{% block content %}
<main>
<div class="reg-form">
<form class="form" method="post" action="">
{% csrf_token %}
<label for="room">Phòng</label>
{{ form.room }}
<label for="date">Ngày</label>
{{ form.date }}
<label for="start">Ca bắt đầu</label>
{{ form.start }}
<label for="end">Ca kết thúc</label>
{{ form.end }}
<button type="submit">Đăng ký</button>
</form>
</div>
</main>
{% endblock %}
The page is rendered like this:
The thing I want is that the input below label 'Phòng' which mean Room, filled with the room object method str() not the primary key of Room object and the submitting process still send the primary key.Is there any way to achieve that? Note: the first three fields need to be read only and their data are given via GET request.
python django django-forms
add a comment |
up vote
0
down vote
favorite
Is there any what to change data display in readonly InputField of ModelChoiceField, but retain the primary key of the object for submitting the form?
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y')
initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room'))
initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start'))
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['room'].widget = forms.TextInput()
self.fields['start'].widget = forms.TextInput()
self.fields['room'].widget.attrs['readonly'] = True
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'], initial_args['date'], initial_args['start'])
def clean(self):
cleaned_data = super(BookingForm, self).clean()
now = timezone.localtime(timezone.now())
bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date'])
booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone())
booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone())
for booking in bookings:
if booking.check_overlap(booking_start_time, booking_end_time):
raise forms.ValidationError
if now > datetime.datetime.combine(cleaned_data['date'],
cleaned_data['start'].end, timezone.get_current_timezone()):
raise forms.ValidationError
return cleaned_data
booking_add.html
{% block content %}
<main>
<div class="reg-form">
<form class="form" method="post" action="">
{% csrf_token %}
<label for="room">Phòng</label>
{{ form.room }}
<label for="date">Ngày</label>
{{ form.date }}
<label for="start">Ca bắt đầu</label>
{{ form.start }}
<label for="end">Ca kết thúc</label>
{{ form.end }}
<button type="submit">Đăng ký</button>
</form>
</div>
</main>
{% endblock %}
The page is rendered like this:
The thing I want is that the input below label 'Phòng' which mean Room, filled with the room object method str() not the primary key of Room object and the submitting process still send the primary key.Is there any way to achieve that? Note: the first three fields need to be read only and their data are given via GET request.
python django django-forms
You are changing the widget toTextInput
, which is why you see the primary key and not the label. Remove this lineself.fields['room'].widget = forms.TextInput()
.
– Burhan Khalid
Nov 7 at 6:19
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
Is there any what to change data display in readonly InputField of ModelChoiceField, but retain the primary key of the object for submitting the form?
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y')
initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room'))
initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start'))
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['room'].widget = forms.TextInput()
self.fields['start'].widget = forms.TextInput()
self.fields['room'].widget.attrs['readonly'] = True
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'], initial_args['date'], initial_args['start'])
def clean(self):
cleaned_data = super(BookingForm, self).clean()
now = timezone.localtime(timezone.now())
bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date'])
booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone())
booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone())
for booking in bookings:
if booking.check_overlap(booking_start_time, booking_end_time):
raise forms.ValidationError
if now > datetime.datetime.combine(cleaned_data['date'],
cleaned_data['start'].end, timezone.get_current_timezone()):
raise forms.ValidationError
return cleaned_data
booking_add.html
{% block content %}
<main>
<div class="reg-form">
<form class="form" method="post" action="">
{% csrf_token %}
<label for="room">Phòng</label>
{{ form.room }}
<label for="date">Ngày</label>
{{ form.date }}
<label for="start">Ca bắt đầu</label>
{{ form.start }}
<label for="end">Ca kết thúc</label>
{{ form.end }}
<button type="submit">Đăng ký</button>
</form>
</div>
</main>
{% endblock %}
The page is rendered like this:
The thing I want is that the input below label 'Phòng' which mean Room, filled with the room object method str() not the primary key of Room object and the submitting process still send the primary key.Is there any way to achieve that? Note: the first three fields need to be read only and their data are given via GET request.
python django django-forms
Is there any what to change data display in readonly InputField of ModelChoiceField, but retain the primary key of the object for submitting the form?
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y')
initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room'))
initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start'))
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['room'].widget = forms.TextInput()
self.fields['start'].widget = forms.TextInput()
self.fields['room'].widget.attrs['readonly'] = True
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'], initial_args['date'], initial_args['start'])
def clean(self):
cleaned_data = super(BookingForm, self).clean()
now = timezone.localtime(timezone.now())
bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date'])
booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone())
booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone())
for booking in bookings:
if booking.check_overlap(booking_start_time, booking_end_time):
raise forms.ValidationError
if now > datetime.datetime.combine(cleaned_data['date'],
cleaned_data['start'].end, timezone.get_current_timezone()):
raise forms.ValidationError
return cleaned_data
booking_add.html
{% block content %}
<main>
<div class="reg-form">
<form class="form" method="post" action="">
{% csrf_token %}
<label for="room">Phòng</label>
{{ form.room }}
<label for="date">Ngày</label>
{{ form.date }}
<label for="start">Ca bắt đầu</label>
{{ form.start }}
<label for="end">Ca kết thúc</label>
{{ form.end }}
<button type="submit">Đăng ký</button>
</form>
</div>
</main>
{% endblock %}
The page is rendered like this:
The thing I want is that the input below label 'Phòng' which mean Room, filled with the room object method str() not the primary key of Room object and the submitting process still send the primary key.Is there any way to achieve that? Note: the first three fields need to be read only and their data are given via GET request.
python django django-forms
python django django-forms
edited Nov 7 at 6:34
asked Nov 7 at 6:09
Q.Nguyen
346
346
You are changing the widget toTextInput
, which is why you see the primary key and not the label. Remove this lineself.fields['room'].widget = forms.TextInput()
.
– Burhan Khalid
Nov 7 at 6:19
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39
add a comment |
You are changing the widget toTextInput
, which is why you see the primary key and not the label. Remove this lineself.fields['room'].widget = forms.TextInput()
.
– Burhan Khalid
Nov 7 at 6:19
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39
You are changing the widget to
TextInput
, which is why you see the primary key and not the label. Remove this line self.fields['room'].widget = forms.TextInput()
.– Burhan Khalid
Nov 7 at 6:19
You are changing the widget to
TextInput
, which is why you see the primary key and not the label. Remove this line self.fields['room'].widget = forms.TextInput()
.– Burhan Khalid
Nov 7 at 6:19
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39
add a comment |
1 Answer
1
active
oldest
votes
up vote
0
down vote
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
add a comment |
up vote
0
down vote
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
add a comment |
up vote
0
down vote
up vote
0
down vote
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
answered Nov 7 at 6:33
Q.Nguyen
346
346
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53184351%2fhow-can-i-change-data-display-in-text-input-of-modelchoicefield%23new-answer', 'question_page');
}
);
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
You are changing the widget to
TextInput
, which is why you see the primary key and not the label. Remove this lineself.fields['room'].widget = forms.TextInput()
.– Burhan Khalid
Nov 7 at 6:19
I know that however I want the field room to be read-only and select widget doesn't have that attribute.
– Q.Nguyen
Nov 7 at 6:34
A select widget by default is "read only" because it does not allow any input. You can limit it to one entry and only show the room's name, or you can convert it to a label. If you change the value of the text field to the name of the room, then you'll have to change the logic in your view to lookup the primary key of the room before you create your Booking model.
– Burhan Khalid
Nov 7 at 6:39