How to render multiple update forms in Django - python

here is my problem.
I have a list of objects that I display in a table and all works just fine except that I would like to edit them inside a modal and submit them using AJAX.
I though that it was a simple idea to render, for each row, a form with the inputs pre-filled and then submit the selected form with AJAX.
I wonder if there is a relatively simplified way to render the UpdateForm without writing manually all the input fields.
Something like this:
<table>
{% for transaction in transactions %}
<tr>
<td>{{ transaction.date|date:"d.m.Y" }}</td>
<td>{{ transaction.amount }}</td>
<td>
Edit
<div class="modal" id="edit{{ transaction.id }}">
{{ transaction_form }}
</div>
</td>
<tr>
{% endfor %}
</table>
But how can I pass the form from the view?
The way I'm currently doing it is that when the user click on edit the page refresh and the modal is displayed with the form prefilled but it is (a) slow to open and (b) I don't think it is a nice way to do it.
This is my current code
views.py
class ProjectDetailView(DetailView):
model = Project
template_name = "template.html"
context_object_name = "project"
def get_transactions(self):
transactions = Transaction.objects.filter(project=self.get_object())
return transactions
def get_transaction_form(self):
form = TransactionForm()
if self.request.POST:
form = TransactionForm(self.request.POST)
elif 'edit_entry' in self.request.GET:
form = TransactionForm(instance=self.get_entry())
return form
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['transactions'] = self.get_transactions()
context['transaction_form'] = self.get_transaction_form()
return context
template.html
<table>
{% for transaction in transactions %}
<tr>
<td>{{ transaction.date|date:"d.m.Y" }}</td>
<td>{{ transaction.amount }}</td>
<td>
Edit
</td>
<tr>
{% endfor %}
</table>
<div class="modal" id="edit-modal">
{{ transaction_form }}
</div>
<script>
{% if 'edit_entry' in request.GET %}
$('#edit-modal').modal('show')
{% endif %}
</script>
Thank you for any feedback

This solution needs you work with Javascript to do that,
when the user clicks 'Edit' for an object on your page,
you send AJAX request (using Fetch API or Jquery) to your view,
The view will return HTML of the form and you put this HTML in the modal's body
Show the modal with an action button to submit the form.
As the user clicks submit, your code submits the form through Ajax, you can use Formdata or AjaxForm for that, the view which return an JSON or HTML which indicates if the data is saved successfully or not.
The problem I'm not a Class-Based View guy so I can't give you specifics from Django side.

Related

Generate data when button/link is clicked Django

I'm very new to Django and web apps. I have an HTML page that allows users to search database for player names. An HTML table is returned. Each entry is a player's performance in relation to a game they played. Each game has 10 players associated with it
search_db.html
<h1>Search Results for: {{searched}}</h1>
<table>
{% for player in match %}
<tr>
<td>
<a href=search_player_db/{{player.match_id}}>{{player.match_id}}</a>
</td>
<td>{{ player.name}}</td>
<td>{{ player.role}}</td>
<td>{{ player.win_or_loss}}</td>
</tr>
{% endfor %}
</table>
{{IM TRYING TO GENERATE DATA HERE}}
The match id is a link that brings the user to a page with additional details related to the match
match_details.html
{%block stats%}
<body>
<h1>Winning team</h1>
{%for player in winners %}
<li>
{{player.name}}
{{player.role}}
</li>
{%endfor%}
<h1>Losing team</h1>
{%for player in losers %}
<li>
{{player.name}}
{{player.role}}
</li>
{%endfor%}
</body>
{%endblock%}
Instead of being redirected to a new page when clicking the link, I'd like to load the content from match_details.html into the page below the table on search_db.html through the button/link in search_db.html. That way the user can click through search results
views.py
def search_playerdb(request):
if request.method == "POST":
searched = request.POST['searched']
players = PlayerInfo.objects.filter(player_name__contains=searched)
context={
'searched': searched,
'players': players}
return render(request, 'searchdb.html', context)
else:
return render(request, 'searchdb.html', {})
def display_match(request, matchid):
match = PlayerInfo.objects.filter(match_id=matchid)
winners = match.filter(win_or_loss=True)
losers = match.filter(win_or_loss=False)
context = {
'match': match,
'winners': winners,
'losers': losers,}
return render(request, 'match_details.html', context)
In order to do this you'll need to use Javascript to make an AJAX call. In case you're unaware, an AJAX call allows a web page to send or receive data without having to refresh the page.
This can be done using pure javascript - Example https://www.w3schools.com/xml/ajax_intro.asp
Or you could use a library to abstract some of the complexity away. One example of this would be JQuery https://www.w3schools.com/jquery/ajax_ajax.asp
In either case, you will be calling a new URL on your site.

Not able to delete an account on a login page made using flask

I'm trying to make a simple login page using python flask and MySQL. The webpage itself is being made using html, bootstrap 4 and css. I followed a tutorial to make the login page but now I want to add a way to delete an account.
This is a profile page which is visible after you login(it shows your username, password and email). The database table(called accounts) has a primary key id. The part in /// is the code I'm trying to add for creating a delete button. Please help me fix my delete account button.
#app.route('/pythonlogin/profile', methods = ['GET'])
def profile():
# Check if user is loggedin
if 'loggedin' in session:
# We need all the account info for the user so we can display it on the profile page
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],))
account = cursor.fetchone()
# Show the profile page with account info
return render_template('profile.html', account=account)
# User is not loggedin redirect to login page
///if request.method == 'GET':
id = session['id']
mycursor = mysql.cursor()
sql = ('DELETE from accounts WHERE id = 4;')
# return redirect(url_for('logout)')
mycursor.execute(sql)
mysql.connection.commit()///
return redirect(url_for('login'))
The following is the html part called profile.html.
{% extends 'layout.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h2>Profile Page</h2>
<div>
<p>Your account details are below:</p>
<table>
<tr>
<td>Username:</td>
<td>{{ account['username'] }}</td>
</tr>
<tr>
<td>Password:</td>
<td>{{ account['password'] }}</td>
</tr>
<tr>
<td>Email:</td>
<td>{{ account['email'] }}</td>
</tr>
<tr>
<form action="{{ url_for('logout') }}">
<td>
<button type="submit" class="btn btn-danger">Delete Account</button>
</td>
</form>
</tr>
</table>
</div>
{% endblock %}
In the provided code I can see some mistakes (logical)
If use logged in, code after return render_template('profile.html', account=account)
will not be executed
And another problem is that you are creating the URL to logout instead of the profile page <form action="{{ url_for('logout') }}">
And better to do the form with POST method.

Drop down lists not populating in DB in Django Forms on click of submit button

I have a table inside form. It looks like below:
{% extends "base.html" %}
{% block title %}Title{% endblock title %}
{% block content %}
<form actions="" method="post">
{% csrf_token %}
<table>
<table border = "1" cellpadding = "10" cellspacing = "10" bordercolor = "green">
<tr>
<th>numbers</th>
<th>Extension</th>
<th>Vendor</th>
</tr>
{% for number in numbers %}
<tr>
<td>{{ number }}</td>
<td class = "select">Select Extension
<select name="extensions">
{% for obj in sipextensionsets %}
<option value={{obj.sip_extension}}>{{ obj.sip_extension }}</option>
{% endfor %}
</select>
</td>
<td>vendor</td>
</tr>
{% endfor %}
</table>
<input type="submit" value="save"/>
</form>
{% endblock content %}
My forms.py is below:
from django import forms
from .models import column
class didsForm(forms.ModelForm):
class Meta:
model = column
fields = ('extension')
My views.py is below
def saveintodb(request):
try:
instance = coloumn.objects.get(pk=1)
except:
instance = coloumn(pk=1)
instance.save()
if request.method == 'POST':
dids_form = didsForm(data=request.POST['extensions'], instance=instance)
if dids_form.is_valid():
dids_form.save()
messages.success(request, "Settings updated. Please apply settings.")
else:
messages.error(request, "Error: Invalid settings.")
else:
dids_form = didsForm(instance=instance)
return render(request, 'dids/index.html', {'dids_form': dids_form})
In the table, there is a drop down (select tag). I want to save the data into database when user selects something from dropdown and clicks on save button. I know I have mistaken somewhere in views.
You're doing a few things wrong here, unfortunately.
The main problem is that you're passing request.POST['extensions'] as the data argument to your form on POST; but that argument is expecting the whole POST, not a single field.
Linked to that is that you have not used the same name for the field in the model and the field in the form. Although you say in your comment that this is intentional, there doesn't seem to be a reason for it, and it's breaking things. Give them the same name.
Thirdly, you aren't letting Django populate the form, or show any errors when it's not valid. You shouldn't be explicitly passing sipextenionset (although you actually don't seem to be passing that at all, so I'm not sure where it's coming from), and you certainly shouldn't be explicitly iterating. You should let Django display the field:
<td>{{ number }}</td>
<td class="select"><label for="id_extension">Select Extension</label>
{{ form.extension }}
</td>
Finally, I can't at all understand what you are doing with that outer for loop through numbers; you will end up with several values for extension, which is not expected by your form, your model, or your view.

flask-wtf same form on same page using for loop

I'm brand new to programming. I came up with a project to help me learn and I'm stuck already. I'm using Flask, Flask-SQLAlchemy and Flask-wtf.
I'm trying to create a club attendance system that lists members and checks them off if they are present and logs the amount they paid (either $15 for 1 lesson, or $25 for the week). I have a table that I populate from my database that looks like this:
I want to click on submit to mark the person as present but this ticks the checkbox for everyone in the list and sets the amount paid to the same for everyone.
I have tried lots of things. I have seen similar issues here and people suggesting using FieldList and FormField - I tried this with no luck. Here is my Form code:
class MemberForm(Form):
form_id = HiddenField()
member_id = DecimalField('id')
member_name = StringField('name')
attend_date = StringField('date', default=todays_date())
is_here = BooleanField('here')
has_paid = SelectField('Amount', choices=[(15, '15'), (25, '25')])
submit = SubmitField("Submit")
def __init__(self, *args, **kwargs):
super(MemberForm, self).__init__(*args, **kwargs)
read_only(self.member_name)
My controller code:
#app.route('/', methods=['GET', 'POST'])
def home():
members = Member.query.order_by(Member.name).all()
form = MemberForm()
if request.method == 'POST': # TODO form validation and database stuff
print('got this far')
print(form.data)
return render_template('index.html', title='Tong Long',
today=todays_date(), members=members,
form=form)
and the jinja2 template part:
<table width="483" border="1">
<tbody>
<tr>
<th width="271"><strong>Member</strong></th>
<th width="152"><strong>Grade</strong></th>
<th><strong>Last Seen</strong></th>
<th width="38"><strong>Paid?</strong></th>
<th><strong>Is Here?</strong></th>
<th>Submit</th>
</tr>
{% for member in members %}
<form action="" method="post" name="{{ member.id }}">
<tr>
<td>{{form.member_name(value=member.name)}}</td>
{% for g in member.grade %}
<td>{{ g.grade }}</td>
{% endfor %}
<td>{{ form.attend_date }}</td>
<td>{{ form.has_paid }}</td>
<td>{{form.is_here}}</td>
<td>
{{ form.submit }}
</td>
</tr>
</form>
{% endfor %}
</tbody>
</table>
Viewing the rendered HTML I can see that all the fields have the same id.
I'm starting to think this can't be done with WTForms. Will I need to use javascript perhaps (something I know nothing about). Or manually create the forms rather than using WTF? Any help appreciated!
This is very late, but perhaps it is helpful to somebody.
What calabash is doing, is create one single form and then display it multiple times in the template.
However, to achieve the desired outcome (independend forms with independend submit buttons), multiple forms need to be created within the route function. They can be passed as a list to the template and then looped over. (A simpler solution would be one form with one submit button and dynamically created "lines" for each member. See FieldList...)
Logic:
def home():
members = Member.query.order_by(Member.name).all()
forms = []
for member in members:
form = MemberForm(prefix=member.name)
form.member_name.data = member.name
forms.append(form)
# validation:
for form in forms:
if form.submit.data and form.validate_on_submit():
# do_something here for each form, e.g. write to database
return render_template('index.html', title='Tong Long',
today=todays_date(),
forms=forms,
members=members)
The different forms need to have individual prefixes. They need to be validated individually and it needs to be checked which submit-button was used.
Note: It is perhaps not a good idea to use a form field for the name, as that information is already known from the members database entry and it might not be intended to change it here. A simple text label would make more sense in that case.
The table rows in the template could look like this:
{% for form in forms %}
<form action="" method="post">
{{ form.hidden_tag() }}
<tr>
<td>{{ form.member_name }}</td>
<td>{{ members[loop.index0].grade }}</td>
<td>{{ form.attend_date }}</td>
<td>{{ form.has_paid }}</td>
<td>{{ form.is_here }}</td>
<td>{{ form.submit }}</td>
</tr>
</form>
{% endfor %}

Change existing model data with form

I am trying to implement a view that displays a form to capture data and a table with the captured data of a user. The table has a form with two buttons per row, either submitting "change" or "delete" together with the object id of the object in the given table row, using POST.
My Django view looks like this:
def captureData(request):
form = MyForm(request.POST or None)
if request.method == "POST":
if 'delete' in request.POST:
# User hits "Delete" button in displayed objects table.
try:
del_object = MyObject.objects.filter(user = request.user).get(id = request.POST['delete'])
del_object.delete()
except:
# Do something ...
return redirect('captureData')
elif 'change' in request.POST:
# User hits "Change" button in displayed objects table.
ch_object = MyObject.objects.filter(user = request.user).get(id = request.POST['change'])
form = MyForm(instance = ch_object)
if form.is_valid():
form.save()
return redirect('captureData')
else:
# New data to be added to the database.
if form.is_valid():
new_object = form.save(commit = False)
new_object.user = request.user
new_object.save()
return redirect('captureData')
objects = Object.objects.filter(user = request.user)
context = {'form': form, 'objects': objects}
return render(request, 'myTemplate.html', context)
This is how the myTemplate.html looks like:
{% extends "base.html" %}
{% block content %}
<h3>Data capturing</h3>
<p>
<!-- First form, responsible for capturing data -->
<form method="POST" action=""> {% csrf_token %}
{{form}}
<input type ='submit' value='Save'/>
</form>
</p>
<h3>Captured data</h3>
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
{% for object in objects %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{object.name}}</td>
<td>{{object.address}}</td>
<td>{{object.city}}</td>
<!-- Second form (per row), responsible for submitting a "delete" or "change" -->
<form action="" method="POST">{% csrf_token %}
<td>
<button type="submit" value="{{object.id}}" name="change" id="object{{object.id}}">Change</button>
</td>
<td>
<button type="submit" value="{{object.id}}" name="delete" id="object{{object.id}}">Delete</button>
</td>
</form>
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
The "delete" part works fine. The problem is the "change" part. It successfully populates the form with the selected objects data, but when I hit the capture from submit button it runs into the else: clause resulting in a new data row or an error, if the data already exists. The reason for this is obvious: The new POST data does not contain the "change" marker anymore.
How can I separate the elif: part from the else: part?

Categories