Home > Blockchain >  Edit Data in Django Unable to show the data
Edit Data in Django Unable to show the data

Time:09-12

I'm using Django to build a website. Modal bootstrap is what I'm utilizing. All works good for add, and delete data. However, In the Django form, I am unable to appear the data stored in the database for the update. Appreciate your help maybe I did something wrong with my code. I am not sure if my html or modal is correct. Thank you

-->> HTML <<--

                                <!-- Table Header  -->
                                <thead>
                                    <tr>
                                        <th>User ID</th>
                                        <th>Username</th>
                                        <th>First Name</th>
                                        <th>Middle Name</th>
                                        <th>Last Name</th>
                                        <th>Role</th>
                                        <th>Created Date</th>
                                        <th>Modified Date</th>
                                        <th>Status</th>
                                        <th>Settings</th>
                                    </tr>
                                </thead>

                                <!-- Table Body  -->
                                <tbody>
                                    {% for members in member %}
            
                                    <tr>
                                        <td>{{members.id}}</td>
                                        <td>{{members.username}}</td>
                                        <td>{{members.first_name}}</td>
                                        <td>{{members.middle_name}}</td>
                                        <td>{{members.last_name}}</td>
                                        <td>{% if members.role %}{{members.get_role}}{% endif %}</td>
                                        <td>{{members.created_date}}</td>
                                        <td>{{members.modified_date}}</td>
                                        <td>
                                            {% if members.status == 1 %}
                                            <button type="button"
                                                >{{members.get_status}}</button>
                                            {% elif members.status == 2 %}
                                            <button type="button"
                                                >{{members.get_status}}</button>
                                            {% elif members.status == 3 %}
                                            <button type="button"
                                                >{{members.get_status}}</button>
                                            {% endif %}

                                           
                                          
                                        </td>
                                        <td>
                                            <a href="#" data-toggle="modal" data-target="#viewUserModal{{ members.id }}"><i class='bx bxs-folder-open'
                                                data-toggle="tooltip" title="View"></i></a>
                                            <a href="#" data-toggle="modal" data-target="#editUserModal{{ members.id }}"><i class='bx bxs-edit'
                                                    data-toggle="tooltip" title="Edit"></i></a>
                                            
                                            <a href="#" data-toggle="modal" data-target="#deleteModal{{ members.id }}"><i class='bx bx-trash'
                                                    data-toggle="tooltip" title="Delete" ></i></a>
                                                    
                                        </td>
                                    </tr>

                                    {% include 'includes/modals.html' %}  
                            
                                   {% endfor %}
                                </tbody>
                                <!-- End of Table Body  -->

                            </table>
                        </div>

-->> Edit Modal <<--

    <div  id="editUserModal{{ members.id }}" role="dialog">
    <div >
      <div >
        <div >
            <h4 >Edit User Account</h4>
            <button type="button"  data-dismiss="modal" aria-hidden="true">
                <i ></i>
            </button>
        </div>
        <div >
          <form action="" method="POST">
            {% csrf_token %}
            <div >
                <label>First Name</label>
                {{form.first_name}}
            </div>
            <div >
                <label>Middle Name</label>
                {{form.middle_name}}
            </div>
            <div >
                <label>Last Name</label>
                {{form.last_name}}
            </div>
            <div >
                <label>Email</label>
                {{form.email}}
            </div>
            <div >
                <label>Mobile Number</label>
                {{form.mobile_number}}
            </div>
            <div >
                <label>Username</label>
                {{form.username}}
            </div>
            <div >
                <label>Role</label>
                <select  id="inputGroupSelect01" name="role" value="{% if members.role %}{{members.get_role}}{% endif %}" required>
                    <option>Select Role</option>
                    <option value="2" {% if members.role == 1 %}{{members.get_role}} selected {% endif %} >Member</option>
                    <option value="2" {% if members.role == 2 %}{{members.get_role}} selected {% endif %} >Admin</option>
                    <option value="3" {% if members.role == 3 %}{{members.get_role}} selected {% endif %}>Super Admin</option>
                </select>
              </div>
              <div >
                <label>Status</label>
                <select  id="inputGroupSelect01" name="role" value="{% if members.status %}{{members.get_status}}{% endif %}" required>
                    <option>Select Status</option>
                    <option value="1" {% if members.status == 1 %}{{members.get_status}} selected {% endif %} >Active</option>
                    <option value="2" {% if members.status == 2 %}{{members.get_status}} selected {% endif %}>Deactive</option>
                </select>
              </div>
              <hr>
              <input type="button"  data-dismiss="modal" value="Cancel">
            <input type="submit"  href="{% url 'edit_user' members.id %}" value="Save">
          </form>
        </div>
      </div>
    </div>
</div>

-->> urls.py <<--

urlpatterns = [

    path('userAccounts/edit_user/<user_id>', views.edit_user, name='edit_user'),

]

-->> forms.py <<--

class UserFormAdmin(forms.ModelForm):
class Meta:
    model = User
    fields = ['first_name', 'middle_name', 'last_name', 'username', 'email', 'mobile_number', 'password']
    labels = {
        'first_name': '',
        'middle_name': '',
        'last_name': '',
        'mobile_number': '',
        'email': '',
        'username': '',
        'password': '',
        'confirm_password': '',
    }

first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones', 'class': 'form-control', }))
middle_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'A', 'class': 'form-control', }))
last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Smith', 'class': 'form-control',}))
mobile_number = forms.CharField(max_length=15, validators=[RegexValidator(
    '^\ [0-9]{1,3}\.?\s?\d{8,13}', message="Phone number must not consist of space and requires country code. eg :  639171234567")],widget=forms.TextInput(attrs={'placeholder': '09123456789', 'class': 'form-control',}),
                                error_messages={'unique': ("Mobile Number already exists.")})

email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': '[email protected]', 'class': 'form-control',}),
                        error_messages={'unique': ("Email already exists.")},)
username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Jones_Smith31', 'class': 'form-control',}),
                           error_messages={'unique': ("Username already exists.")},)
password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control',}))
#password = forms.CharField(validators=[MinLengthValidator(8),RegexValidator('^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z])$', message="Password should be a combination of Alphabets and Numbers")], widget=forms.PasswordInput(attrs={'placeholder': '********', 'style': 'width: 460px; '}))
confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': '********', 'class': 'form-control', }))

-->> views.py <<--

def sa_userAccount_admin(request):
member = User.objects.filter(role = 2)
form = UserFormAdmin(request.POST)
context = {
    'form': form,
    'member': member,
}
print(context)
return render(request, 'pages/sa_userAccount.html', context)

def edit_user(request, user_id):
member = User.objects.get(pk=user_id)
form = UserFormAdmin(request.POST or None, instance=member)
if form.is_valid():
    form.save()
    return redirect('sa_userAccount')
return render(request, 'pages/sa_userAccount.html', 
    {'members': member,
    'form':form})

CodePudding user response:

in your html try to render it like this in your html

{% for member in members %}
<td>{{member.id}}</td>
 <td>{{member.username}}</td>
<td>{{member.first_name}}</td>

Acc to your view you want to retrieve member from members

CodePudding user response:

You can do this using the following steps:

  1. get user input to update an object in HTML Modal
  2. send data using the POST method with object pk
  3. fetch object using received pk
  4. update object in views using setattr(object,field name,value) from POST data
  5. call object.save() method

These steps will update your objects in the database using the partial update technique.

  • Related