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 form page



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.










share|improve this question
























  • 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










  • 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















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 form page



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.










share|improve this question
























  • 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










  • 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













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 form page



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.










share|improve this question















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 form page



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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 6:34

























asked Nov 7 at 6:09









Q.Nguyen

346




346












  • 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










  • 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












  • 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












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.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    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
































    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.






    share|improve this answer

























      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.






      share|improve this answer























        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.






        share|improve this answer












        I know that however I want the field room to be read-only and select widget doesn't have that attribute.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 7 at 6:33









        Q.Nguyen

        346




        346






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            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




















































































            Popular posts from this blog

            横浜市

            Rostock

            Europa