Home > Blockchain >  Edit data in the database that was recorded without a form
Edit data in the database that was recorded without a form

Time:11-09

In my project, there is a form and a table with checkboxes, based on the data entered in the form and the checkboxes, I fill 2 databases and redirect the user to a page where information from one table is displayed, it all worked very well until I got to editing the records, I decided I do it with UpdateView, passing in template_name the same template as before adding records:

here is the add function and the edit class:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'mailsinfo/add_campaign.html'
    form_class = CampaignsForm
def add_campaign(request):
    if request.method == 'POST':
        addCampaignDataToDB(request.POST)
    data = list(Emails.objects.values())
    data = MailsTableWithoutPass(data)
    form = CampaignsForm()
    data_ = {
        'form': form,
        'data': data
    }
    return render(request, 'mailsinfo/add_campaign.html', data_)

But when calling the url to change my data table is empty and there are no selected checkboxes there, all processing of the form works fine

Here is the template I use, and the function that writes the data into the tables:

<div>
    <div >
        <div >
            <form method="post" id="newCampaign">

                    {% csrf_token %}
                    {{ form.name }}<br>
                    {{ form.subject }}<br>
                    {{ form.body }}<br>
                    {{ form.user_guid }}<br>

            </form>
        </div>
        <div >
            <table
            id="table"
            data-height="480"

            >
                <thead>
                    <tr name="mails-info">

                        <th data-field="state" data-checkbox="true"></th>
                        <th data-field="id">ID</th>
                        <th data-field="email">Email</th>
                        <th data-field="source">Source</th>
                        <th data-field="created_at">Created at</th>
                        <th data-field="modified_at">Modified at</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>

        <script>
            var $table = $('#table')

            $(function() {
                var data =   {{data|safe}}
                $table.bootstrapTable({data: data})
            })
        </script>


<button id="button2"  type="submit" style="margin-left: 2%">Save campaign</button>

</div>
<script>
             var table = $('#table')
             var button = $('#button2')

             $(function() {
                button.click(function () {
                    ids = []
                    for( i in table.bootstrapTable('getSelections')){
                        ids.push(table.bootstrapTable('getSelections')[i].id)
                    }
                    console.log(ids)
                    var form = $('#newCampaign')[0];
                    var formData = new FormData(form);
                    formData.append("IDs", ids);
                    $.ajax({
                          type: "POST",
                          enctype: 'multipart/form-data',
                          url: '',
                          data: formData,
                          processData: false,
                          contentType: false,
                          dataType: 'text/json',
                          success: function(){ alert("All ok") },
                          error: function() {
                                window.location.replace('..');
                           }

                    });
                })
             })
        </script>
def addCampaignDataToDB(req):
    mails_id = req
    print(mails_id)
    formCampaigns = CampaignsForm(req)
    IDs = req['IDs']
    if IDs != '':
        IDs_list = IDs.split(',')
        user_guid = req['user_guid'][0]
        for i in IDs_list:
            CampaignEmail.objects.create(email_guid=int(i), campaigne_guid=int(user_guid))

    if formCampaigns.is_valid():
        formCampaigns.save()

Is there any method when calling this url:

path('editCampaign/<int:pk>', views.CampaignEditor.as_view(), name='editCampaign')

, in addition to the recorded form, to receive a table of data with checkboxes available for editing?

I apologize in advance if I did not provide any information or explained something unclearly

CodePudding user response:

You aren't passing any additonal data to the update form. The update view is separate and doesn't inherit data from the add-campaign view, so if you need additional context, you can:

class CampaignEditor(UpdateView):
    model = Campaigns
    template_name = 'mailsinfo/add_campaign.html'
    form_class = CampaignsForm
    def get_extra_context(self):
        //call the super context from the parent class
        context = super().get_context_data(*args, **kwargs)
        data = list(Emails.objects.values()) #you may want to further filter for update purposes
        data = MailsTableWithoutPass(data)
        context['data'] = data
        return context

I'm not sure how much of the form is being created by javascript - it may be worth remembering that django templates are done serverside, so if you need to populate fields that are created client-side by JS, you'll need to put their values somewhere as JS variables that you can refer to later,eg,

<script>
    {% for field in form %}
       {{field.name}} = "{{field.value}}"
    {% endfor %}
<script>
    
  • Related