Create an update screen with Django Updateview

Since the last time, I've been trying various things because I want to prevent the employee name and date from being edited.

I've been researching forms.py for a few hours (I haven't learned how to use it), but it didn't work.

Finally, I wondered what would happen if I did the same thing as the schedule and handed over what I did to hand over the employee name, and finally it worked.

schedule/views.py


class ScheduleUpdate(UpdateView):
    template_name = 'schedule/update.html'
    model = Schedule
    fields = ('user','date', 'shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3','shift_name_4', 'shisetsu_name_4', 'day_total_worktime')
    success_url = reverse_lazy('schedule:homeschedule')

    #def get_queryset(self):
    #    return super().get_queryset().select_related('user')
    #    return super().get_queryset().select_related('schedule')

That was all. I got it by adding the last line

schedule/update.html


{% extends 'schedule/base.html' %}

{% block header %}
{% endblock header %}

{% block content %}
<form action="" method="POST">{% csrf_token %}
    <P >Employee name: {{ user.last_name }} {{ user.first_name }}</P>
    <p>date: {{ schedule.date }}</p>
    <p>Shift 1:{{ form.shift_name_1 }}</p> 
    <p>Facility name 1:{{ form.shisetsu_name_1 }}</p>  
    <p>Shift 2:{{ form.shift_name_2 }}</p> 
    <p>Facility name 2:{{ form.shisetsu_name_2 }}</p>  
    <p>Shift 3:{{ form.shift_name_3 }}</p> 
    <p>Facility name 3:{{ form.shisetsu_name_3 }}</p>  
    <p>Shift 4:{{ form.shift_name_4 }}</p> 
    <p>Facility name 4:{{ form.shisetsu_name_4 }}</p>
    <p>Total working hours:{{ form.day_total_worktime }}</p>
    <input class="btn btn-primary" type="submit" value="update">
    <a href="{% url 'schedule:homeschedule' %}" class="btn-secondary   btn active">Return</a>
</form>
{% endblock content %}

image.png

You've implemented it!

Finally!

Next, I will try to make the total working hours possible ... I started doing it, but there was another problem!

I cannot return to the shift table from the screen I am editing from the update screen

python:schedule.views.py


class ScheduleUpdate(UpdateView):
    template_name = 'schedule/update.html'
    model = Schedule
    fields = ('shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3','shift_name_4', 'shisetsu_name_4', 'day_total_worktime')
    year = Schedule.year
    month = Schedule.month
    #success_url = reverse_lazy('schedule:monthschedule', kwargs={"year": self.object.year})
    #success_url = HttpResponseRedirect('/schedule/monthschedule/%s/%s/' % (Schedule.year,Schedule.month,))
    success_url = reverse_lazy('/schedule/monthschedule/%s/%s/' % (year,month))

    #def get_url_success(self):
    #    url = "/schedule/monthschedulefunc/" + self.year +"/"+ self.month
    #    return HttpResponseRedirect(url)

    def get_queryset(self): ###I didn't need it ...
        #return super().get_queryset().select_related('user')
        #return super().get_queryset().select_related('schedule')
        #return super().get_queryset().select_related('Shift')

Trying various things, a little over 2 hours ... I have already given up

I will recreate it with the def function! Just because it's a function doesn't mean it can be done right away (laughs)

Challenge for the time being (⌒∇⌒)

It took about 2 hours, but it was possible! Finally I also used forms.py (it's still far from understanding, but it's important to change 0 to 1)

まずは、views.py

schedule/views.py


def scheduleUpdatefunc(request,pk):
    Schedule_list = Schedule.objects.get(pk = int(pk))
    User_list = User.objects.get(username = Schedule_list.user)
    if request.method == 'POST':
        form = ScheduleUpdateForm(data=request.POST)
        year = Schedule_list.year
        month = Schedule_list.month
        if form.is_valid():
            Schedule_list.shift_name_1 = form.cleaned_data['shift_name_1']
            Schedule_list.shisetsu_name_1 = form.cleaned_data['shisetsu_name_1']
            Schedule_list.shift_name_2 = form.cleaned_data['shift_name_2']
            Schedule_list.shisetsu_name_2 = form.cleaned_data['shisetsu_name_2']
            Schedule_list.shift_name_3 = form.cleaned_data['shift_name_3']
            Schedule_list.shisetsu_name_3 = form.cleaned_data['shisetsu_name_3']
            Schedule_list.shift_name_4 = form.cleaned_data['shift_name_4']
            Schedule_list.shisetsu_name_4 = form.cleaned_data['shisetsu_name_4']
            Schedule_list.day_total_worktime = form.cleaned_data['day_total_worktime']
            Schedule_list.save()
            return HttpResponseRedirect('/schedule/monthschedule/%s/%s/' % (year,month,))

    else:
        item = {
            "shift_name_1":Schedule_list.shift_name_1,
            "shisetsu_name_1": Schedule_list.shisetsu_name_1,
            "shift_name_2": Schedule_list.shift_name_2,
            "shisetsu_name_2": Schedule_list.shisetsu_name_2,
            "shift_name_3": Schedule_list.shift_name_3,
            "shisetsu_name_3": Schedule_list.shisetsu_name_3,
            "shift_name_4": Schedule_list.shift_name_4,
            "shisetsu_name_4": Schedule_list.shisetsu_name_4,
            }
        form = ScheduleUpdateForm(initial=item)
        context = {
            'form' : form,
            'Schedule_list': Schedule_list,
            'User_list': User_list,
        }

        return render(request,'schedule/update.html', context )

The code is long, but most just connect which fields to which fields, so I was able to do it as soon as I started making it.

次に初めてトライしたforms.py

schedule/forms.py


class ScheduleUpdateForm(forms.ModelForm):
    class Meta:
        model = Schedule
        fields = ('shift_name_1', 'shisetsu_name_1', 'shift_name_2', 'shisetsu_name_2', 'shift_name_3', 'shisetsu_name_3','shift_name_4', 'shisetsu_name_4', 'day_total_worktime')
        #shift_name_1 = forms.ForeignKey(Shift, verbose_name='1 shift name', related_name='shift_name1',on_delete=models.SET_NULL,null= True)
        #shisetsu_name_1 = forms.ForeignKey(Shisetsu, verbose_name='1 facility', related_name='shisetsu_name1',on_delete=models.SET_NULL,blank=True, null=True)
        #shift_name_2 = forms.ForeignKey(Shift, verbose_name='2 shift name', related_name='shift_name2',on_delete=models.SET_NULL,blank=True, null=True)
        #shisetsu_name_2 = forms.ForeignKey(Shisetsu, verbose_name='2 facilities', related_name='shisetsu_name2',on_delete=models.SET_NULL,blank=True, null=True)
        #shift_name_3 = forms.ForeignKey(Shift, verbose_name='3 shift name', related_name='shift_name3',on_delete=models.SET_NULL,blank=True, null=True)
        #shisetsu_name_3 = forms.ForeignKey(Shisetsu, verbose_name='3 facilities', related_name='shisetsu_name3',on_delete=models.SET_NULL,blank=True, null=True)
        #shift_name_4 = forms.ForeignKey(Shift, verbose_name='4 shift name', related_name='shift_name4',on_delete=models.SET_NULL,blank=True, null=True)
        #shisetsu_name_4 = forms.ForeignKey(Shisetsu, verbose_name='4 facilities', related_name='shisetsu_name4',on_delete=models.SET_NULL,blank=True, null=True)

Since the input control was not linked well at first, there is evidence of pasting from models (laugh)

I edited the html a little

schedule/update.html


{% extends 'schedule/base.html' %}

{% block header %}
{% endblock header %}

{% block content %}
<form action="" method="POST">{% csrf_token %}
    <P >Employee name: {{ User_list.last_name }} {{ User_list.first_name }}</P>
    <p>date: {{ Schedule_list.date }}</p>
    {{ form.as_p }}
    {% csrf_token %}
    <input class="btn btn-primary" type="submit" value="update">
    <a href="{% url 'schedule:homeschedule' %}" class="btn-secondary   btn active">Return</a>
</form>
{% endblock content %}

Now you can return to the month you are editing by pressing the update button on the correction screen.

image.png

image.png

Recommended Posts

Create an update screen with Django Updateview
Create an API with Django
Create an environment with virtualenv
Create a homepage with django
Create a Django login screen
Transit to the update screen with the Django a tag
I'm trying to create an authentication / authorization process with Django
Create an authentication feature with django-allauth and CustomUser in Django
Create a Todo app with Django ① Build an environment with Docker
[Python] Create a screen for HTTP status code 403/404/500 with Django
Load Django modules with an interpreter
Create screen scroll with Pythonista + scene
Create an Excel file with Python3
Create an age group with pandas
Note: Send an email with Django
Create a file uploader with Django
django update
Create an environment for Django x Apache x mod_wsgi with Vagrant (Ubuntu 16.04)
Create an application by classifying with Pygame
Create an image processing viewer with PySimpleGUI
Browse an existing external database with Django
Quickly create an excel file with Python #python
Creating a login screen with Django allauth
Create your first app with Django startproject
[Python] Quickly create an API with Flask
Create an add-in-enabled Excel instance with xlwings
Create an English word app with python
Create an upgradeable msi file with cx_Freeze
Create an app that guesses students with python
Create an academic society program with combinatorial optimization
Recreate the django staff registration screen with class
Internationalization with django
Create a dashboard for Network devices with Django!
Create Nginx + uWSGI + Python (Django) environment with docker
A story about implementing a login screen with django
Create an image with characters in python (Japanese)
CRUD with Django
Create a one-file hello world application with django
Create an API server quickly with Python + Falcon
Create an animated GIF local server with Python + Flask
Procedure for creating an application with Django with Pycharm ~ Preparation ~
Create a Todo app with Django REST Framework + Angular
I tried to create a table only with Django
Create a Todo app with the Django REST framework
Create APIs around user authentication with Django REST Framework
Create an idol-like tweet with Keras LSTM (sentence generation)
An easy way to create an import module with jupyter
Create a Todo app with Django ③ Create a task list page
Deploy an existing app with docker + pyenv-virtualenv + uwsgi + django
Create an app that guesses students with python-GUI version
Create a random number with an arbitrary probability density
Dynamically create tables in schema with Django, dynamically generate models
Create an OpenAI Gym environment with bash on Windows 10
Create a Todo app with Django ⑤ Create a task editing function
Create a django environment with docker-compose (MariaDB + Nginx + uWSGI)
Create an environment for test automation with AirtestIDE (Tips)
Django 1.11 started with Python3.6
Development digest with Django
Create a Django schedule
Output PDF with Django
Markdown output with Django