Arash Hatami
Arash Hatami

Reputation: 5551

add row to database django

i have a project for managing students i can read or edit rows of my database , but i can't add new data to it and i don't have any idea ..... some help :(

html :

<form action="/school_manager/students/add/" method="post">
        {% csrf_token %}
        <label for="add_first_name">First Name</label><br/>
        <input type="text" class="form-control" name="add_first_name" id="add_first_name" />
<input type="submit" class="btn btn-primary btn-lg" value="Add"/>

there is a html form with a simple text field to add a 'first_name' for editing the database

it's my view.py and worked for me for edit a row's field :

def update_student_detail(request, student_id):
    list = get_object_or_404 ( student, pk=student_id)
    if request.method == 'POST' :
        list.First_Name = request.POST.get('update_first_name')
    list.save()
    return HttpResponseRedirect('/school_manager/students/' + student_id)

now , what is the way to add data to database ????

thanks

Upvotes: 0

Views: 2892

Answers (2)

Mushahid Khan
Mushahid Khan

Reputation: 2834

if want to check existing row before creating new one

You Should Use get_or_create(). It returns tuple

e.g:

created_obj = Something.objects.get_or_create(name='ABC',Address="XYZ")

Upvotes: 4

mitcon_mario
mitcon_mario

Reputation: 106

Try this:

new_student = student(First_Name = request.POST.get('add_first_name'))
new_student.save()

Upvotes: 1

Related Questions