I want to retrieve data to modelForm based on user input. I am developing a transaction app, I want to retrieve account balance to the form based on the account number selected by the user. First I want to print an alert to test the existence of the account number but keep getting 500 internal server error.
Here is the code
models.py
class Account(models.Model):
ACCOUNT_TYPE = (
('Checking','Checking'),
('Savings','Savings'),
)
user = models.ForeignKey('auth.User', on_delete=models.CASCADE)
account_number = models.PositiveIntegerField(primary_key=True)
account_type = models.CharField(max_length=8, choices=ACCOUNT_TYPE, default='select')
account_balance = models.PositiveIntegerField(blank=True, default=0)
views.py
#login_required
def validate_account_number(request):
account_number = request.Get.get['account_number']
data = {
'is_exist': Account.objects.filter(
account_number=account_number).exists()
}
return JsonResponse(data)
transaction.html
<form class="form-horizontal" method=POST id="sendform">
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade active show" transfer="home">
<div class="col-md-6">
<div class="tile">
<h3 class="tile-title">Transfer Money</h3>
<div class="tile-body">
{% csrf_token %}
{% bootstrap_form form%}
{{ form.non_field_errors }}
<div class="tile-footer">
<div class="row">
<div class="col-md-8 col-md-offset-3">
<button type="submit"> <i class="fa fa-fw fa-lg
fa-check-circle"></i>Send</button> <a class="btn btn-
secondary" href="#"><i class="fa fa-fw fa-lg fa-times-circle">
</i>Cancel</a>
</div>
</div>
</div>
</div>
</div>
</div></div>
</div>
</form>
</main>
{% endblock %}
{% block javascript %}
<script>
$("#id_creditor_account").change(function(){
var account_number = $(this).val();
$.ajax({
url: '{% url 'users:validate_account_number'%}',
data:{
'account_number':account_number
},
dataType: 'json',
success: function(data){
if (data.is_exist){
alert("Account exist");
}
}
});
});
</script>
Here is the screenshot: html_transction_page
Error from console
jquery-3.2.1.min.js:4 GET http://127.0.0.1:8000/users/ajax/validate_account_number/?account_number=5645786809 500 (Internal Server Error)
send # jquery-3.2.1.min.js:4
ajax # jquery-3.2.1.min.js:4
(anonymous) # (index):265
dispatch # jquery-3.2.1.min.js:3
q.handle # jquery-3.2.1.min.js:3
ListPicker._handleMouseUp
The attribute is request.GET, not request.Get. And as Ralf says, it is a method. So either:
account_number = request.GET.get('account_number')
or
account_number = request.GET['account_number']
I think the error is in your view: the method GET.get cannot be indexed, but it can be called.
Try changing
# with brackets, capitalized 'Get'
account_number = request.Get.get['account_number']
to
# with parenthesis, all uppercase 'GET'
account_number = request.GET.get('account_number')
EDIT
Ah, right, its request.GET (all uppercase), not request.Get (capitalized).
Related
I'm trying to add data that I rendered on a page from an API endpoint, to my database when I click "Add to my records" button, as can be seen in the image below, and I'm only trying to store "Date and Country" into the database (my model table has only date and country)
enter image description here
I've seen many resources talking about how JS and AJAX are useful in this case but I'm lost with logic of it all. Is there any way someone could explain how it's supposed to be done.
models.py
from django.db import models
class CountryData(models.Model):
country = models.CharField(max_length=100)
date = models.DateTimeField()
def __str__(self):
return self.country
views.py
def all_countries(request):
first_response = requests.get("https://api.covid19api.com/summary").json()
results = len(first_response["Countries"])
my_new_list = []
data_list = []
for i in range(0, results):
my_new_list.append(first_response["Countries"][i])
# print(my_new_list)
if request.method == "POST":
if request.POST.get("country") and request.POST.get("date"):
added_record = CountryData()
added_record.country = request.POST.get("country")
# 2022-12-19T08:53:48.179Z
added_record.date = datetime.datetime.strptime(
request.POST.get("date"), "%Y-%m-%dT%I:%M:%S.%fZ"
)
added_record.save()
return render(request, "allcountries.html")
else:
return render(request, "allcountries.html", )
context = {"my_new_list": my_new_list}
return render(request, "allcountries.html", context)
urls.py
from django.urls import path, include
from .views import home, all_countries
urlpatterns = [
path("", home, name="home"),
path("allcountries", all_countries, name="all_countries")
]
allcountries.html
{% extends '_base.html' %}
{% block page_title %} Covid19 Statistics For All Countries {% endblock %}
{% block content %}
<h3 class="text-center">Covid19 Statistics For All Countries </h3>
{% for object in my_new_list %}
<div class="row justify-content-center">
<div class="col-sm-10 d-flex justify-content-center">
<div class="card text-dark text-center" style="width: 20rem;">
<div class="card-block card-body">
<form method="POST" action="">
{% csrf_token %}
<h5 class="card-header" name="country">Country: {{object.Country}}, {{object.CountryCode}}</h5>
<br>
<p class="card-text">Total Confirmed Cases: {{object.TotalConfirmed}} </p>
<p class="card-text">Total Deaths Cases: {{object.TotalDeaths}} </p>
<p class="card-text">Total Recovered Cases: {{object.TotalRecovered}} </p>
<p class="card-text" name="date">Date: {{object.Date}}</p>
<button class="btn btn-success" type="submit">ADD TO MY RECORDS </button>
</form>
</div>
</div>
<br>
</div>
</div>
{% endfor %}
{% endblock %}
You can use the following ajax snippet to send data in the backend:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$.ajax({
type: 'POST',
url: 'url', #leave blank if URL is same as the current one
data: {
'country': 'county_name',
'date': 'date_value',
},
success: function(response) {
# depending upon the response from the server you can make an alert here.
},
error: function(response){
# If some error occurred on the backend you can show error message from here
}
});
</script>
I have a view that implements a m2m relationship, and I would like to unit test it, which I did not manage yet. The view seems working with the page I defined, but any suggestion is also welcome.
The context is the following: I would like to manage users' groups in a Django app, and, of course, as I need additional fields, I built a model dedicated to user's management in my app. I defined a page with to multiple select boxes, one for the list of users, the other one with users selected to be part of the group. Inbetween are action icons to move users from one group to the others. At the stage, there is no control if a users shall not belong to more than one group, all users that do not belong to the current group are displayed (I assume it's just a question of filtering data).
My page currently looks like this (btw, if you have any suggestion to make titles displayed above the selection boxes, I would also appreciate, even if it's not the topic here.
I would like to unit test the contain of each group and, later on, the impact of adding or removing a user from group.
At this stage, I was just able to check a user in the database is displayed, but actually I have no clue if it is part of one group or another. If I add some rules, such as verifying the user is not already part of a group (or do not propose it to be added to the group in this case), I need to build more precise test, and I do not know yet how to do.
Here is my current working test code:
class TestAdmGroups(TestCase):
def setUp(self):
self.company = create_dummy_company("Société de test")
self.group1 = EventGroup.create_group({"company": self.company, "group_name": "Groupe 1", "weight": 40})
self.group2 = EventGroup.create_group({"company": self.company, "group_name": "Groupe 2", "weight": 60})
# self.group2 = EventGroup.objects.create(company=self.company, group_name="Groupe 2", weight=60)
self.user_staff = create_dummy_user(self.company, "staff", group=self.group1, admin=True)
self.usr11 = create_dummy_user(self.company, "user11", group=self.group1)
self.usr12 = create_dummy_user(self.company, "user12", group=self.group1, admin=True)
self.usr13 = create_dummy_user(self.company, "user13")
self.usr14 = create_dummy_user(self.company, "user14")
self.usr21 = create_dummy_user(self.company, "user21", group=self.group2)
self.usr22 = create_dummy_user(self.company, "user22", group=self.group2)
def test_adm_update_group(self):
self.client.force_login(self.user_staff.user)
url = reverse("polls:adm_group_detail", args=[self.company.comp_slug, self.group1.id])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "user11")
self.assertContains(response, "user14")
self.assertContains(response, "user21")
I would like to separate results, and ensure user11 is part of the right list, the other values are supposed to be part of the left one.
The view is the following:
def adm_group_detail(request, comp_slug, grp_id=0):
company = Company.get_company(comp_slug)
if grp_id > 0:
current_group = EventGroup.objects.get(id=grp_id)
group_form = GroupDetail(request.POST or None, instance=current_group)
else:
group_form = GroupDetail(request.POST or None)
group_form.fields['all_users'].queryset = UserComp.objects.\
filter(company=company).\
order_by('user__last_name', 'user__first_name')
if request.method == 'POST':
# Convert the string in a list of user IDs
usr_list = [int(elt) for elt in request.POST['group_list'].split('-') if elt != ""]
group_form.fields['users'].queryset = UserComp.objects.filter(id__in=usr_list).\
order_by('user__last_name', 'user__first_name')
group_form.fields['all_users'].queryset = UserComp.objects.exclude(id__in=usr_list)
if group_form.is_valid():
if grp_id == 0:
# Create empty group
group_data = {
"company": company,
"group_name": group_form.cleaned_data["group_name"],
"weight": group_form.cleaned_data["weight"],
}
new_group = EventGroup.create_group(group_data)
else:
# Update group
new_group = group_form.save()
# Remove all users
group_usr_list = UserComp.objects.filter(eventgroup=new_group)
for usr in group_usr_list:
new_group.users.remove(usr)
# Common part for create and update : add users according to new/updated list
for usr in usr_list:
new_group.users.add(usr)
new_group.save()
# Update form according to latest changes
group_form.fields['all_users'].queryset = UserComp.objects.\
exclude(id__in=usr_list).\
order_by('user__last_name', 'user__first_name')
group_form.fields['group_list'].initial = "-".join([str(elt.id) for elt in new_group.users.all()])
return render(request, "polls/adm_group_detail.html", locals())
I managed to make the view work with both lists being part of the same form, but I can change this if you have any suggestion.
With this view, I noticed that I could get values from one list or another the following way: response.context["group_form"]["all_users"] or response.context["group_form"]["users"] but unfortunately, it looks like it's not possible to enter one of these values as parameter of assertContains() (self.assertContains(response.context["group_form"]["users"], self.user11.user.username) does not work, as the fist parameter is supposed to be a response) nor assertInHTML(), in this case I have the following error message with the same previous parameters:
======================================================================
ERROR: test_adm_update_group (polls.tests_admin.TestAdmGroups)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 264, in test_adm_update_group
self.assertInHTML(response.context["group_form"]["users"], self.usr11.user.username)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\test\testcases.py", line 791, in assertInHTML
needle = assert_and_parse_html(self, needle, None, 'First argument is not valid HTML:')
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\test\testcases.py", line 62, in assert_and_parse_html
dom = parse_html(html)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\test\html.py", line 220, in parse_html
parser.feed(html)
File "c:\program files\python37\Lib\html\parser.py", line 110, in feed
self.rawdata = self.rawdata + data
TypeError: can only concatenate str (not "BoundField") to str
----------------------------------------------------------------------
As you can see in the screenshot, I would like to check a user is in one list or another, not only displayed on the page like I did yet.
Here is the model's definition:
class EventGroup(models.Model):
"""
Groups of users
The link with events is supported by the Event
(as groups can be reused in several Events)
"""
company = models.ForeignKey(
Company, on_delete=models.CASCADE, verbose_name="société"
)
users = models.ManyToManyField(UserComp, verbose_name="utilisateurs", blank=True)
group_name = models.CharField("nom", max_length=100)
weight = models.IntegerField("poids", default=0)
def __str__(self):
return self.group_name
class Meta:
verbose_name = "Groupe d'utilisateurs"
verbose_name_plural = "Groupes d'utilisateurs"
#classmethod
def create_group(cls, group_info):
new_group = EventGroup(company=group_info["company"], group_name=group_info["group_name"], weight=group_info["weight"])
new_group.save()
return new_group
If it can help, here is the HTML code:
{% extends './base.html' %}
{% load static %}
{% block content %}
<div class="row">
{% include "./adm_head.html" %}
<div class="col-sm-9">
<input type="hidden" id="menu_id" value="3" /> <!-- Hidden value to store the current selected menu -->
<div class="row">
<div id="admin-groups" class="col-sm-12 text-center">
<h4 class="mt-5">Détails du groupe</h4>
</div>
</div>
<div class="row">
<div class="col-sm-12 mt-30">
{% if grp_id %}
<form action="{% url 'polls:adm_group_detail' company.comp_slug grp_id %}" method="post">
{% else %}
<form action="{% url 'polls:adm_group_detail' company.comp_slug %}" method="post">
{% endif %}
{% csrf_token %}
<div class="row">
<div class="control-group {%if group_form.group_name.errors %}error{%endif%}"></div>
<div class="control-group {%if group_form.weight.errors %}error{%endif%}"></div>
{{ group_form.group_name}} {{ group_form.weight }}
<a type="button" id="disp_detail" class="collapse-group btn btn-sm" href="">
<span id="btn_grp" class="fas fa-chevron-up" data-toggle="tooltip" title="Masquer/Afficher détails"></span>
</a>
</div>
<div class="row mt-30 grp-content" id="grp_content">
<div class="col-md-5 d-flex justify-content-center">
<p>Utilisateurs</p>
{{ group_form.all_users}}
</div>
<div class="col-md-2 d-flex flex-column text-center justify-content-around">
<a type="button" id="add_all" class="update-user btn btn-sm" href="">
<span class="fa fa-fast-forward" style="color: #339af0;" data-toggle="tooltip" title="Ajouter tout"></span>
</a>
<a type="button" id="add_selected" class="update-user btn btn-sm" href="">
<span class="fa fa-step-forward" style="color: #339af0;" data-toggle="tooltip" title="Ajouter sélection"></span>
</a>
<a type="button" id="remove_selected" class="update-user btn btn-sm" href="">
<span class="fa fa-step-backward" style="color: #339af0;" data-toggle="tooltip" title="Retirer sélection"></span>
</a>
<a type="button" id="remove_all" class="update-user btn btn-sm" href="">
<span class="fa fa-fast-backward" style="color: #339af0;" data-toggle="tooltip" title="Retirer tout"></span>
</a>
</div>
<div class="col-md-5 d-flex justify-content-center">
<p>Utilisateurs sélectionnés</p><br>
{{ group_form.users }}
<div class="control-group {%if group_form.users.errors %}error{%endif%}"></div>
</div>
</div>
<div class="row">
<div class="col-sm-12 mt-30 text-center">
<button id='upd_grp' class="btn btn-success" type="submit">{% if grp_id %}Mettre à jour{% else %}Créer{% endif %}</button>
     
<a class="btn btn-secondary back_btn" href="*">Annuler</a>
</div>
</div>
<div class="row">
<div hidden>
<!-- Liste des ID du groupe -->
{{ group_form.group_list }}
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
I think I found the answer I was looking for and a way to make my tests.
The ideas was to find a way to separate each forms' contains, and it's done thanks to the right application of attributes: isolate the main form as a key of context dict, then use the fields attribute to filter and finally apply the queryset attribute to be able to manage related data accordingly.
Then, the question was : 'how to make the comparison with this specific format?'. I found the answer by filtering on this object, taking advantage that .filter() will retrieve an empty list if no value is found, whereas a .get() would have raised an error.
I will not make this answer the right one until I'm finished or I receive some comments or other ideas for better solution, but the following code for unit tests works very fine for me:
class TestAdmGroups(TestCase):
def setUp(self):
self.company = create_dummy_company("Société de test")
self.group1 = EventGroup.create_group({"company": self.company, "group_name": "Groupe 1", "weight": 40})
self.group2 = EventGroup.create_group({"company": self.company, "group_name": "Groupe 2", "weight": 60})
# self.group2 = EventGroup.objects.create(company=self.company, group_name="Groupe 2", weight=60)
self.user_staff = create_dummy_user(self.company, "staff", group=self.group1, admin=True)
self.usr11 = create_dummy_user(self.company, "user11", group=self.group1)
self.usr12 = create_dummy_user(self.company, "user12", group=self.group1, admin=True)
self.usr13 = create_dummy_user(self.company, "user13")
self.usr14 = create_dummy_user(self.company, "user14")
self.usr21 = create_dummy_user(self.company, "user21", group=self.group2)
self.usr22 = create_dummy_user(self.company, "user22", group=self.group2)
def test_adm_update_group(self):
self.client.force_login(self.user_staff.user)
url = reverse("polls:adm_group_detail", args=[self.company.comp_slug, self.group1.id])
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
group_users = response.context["group_form"].fields["users"].queryset
test_user = group_users.filter(id=self.usr11.id)
self.assertEqual(len(test_user), 1)
test_user = group_users.filter(id=self.usr14.id)
self.assertEqual(len(test_user), 0)
My application currently flows through 3 pages:
User selects question in index page
User submits answer in answer page
User is presented with result in results page.
I want to compress that down to a single page where the user submits an answer to the question and result is shown on the same page.
The following django-template code separates questions with Bootstrap accordion. How do I post the form without refreshing the whole page? I want to be able to display the result on the page, update CSS styling with Javascript etc.
<h2>{{ category.title }}</h2>
<div class="accordion" id="accordion{{category.title}}">
{% for challenge in category.challenge_set.all %}
<div class="card">
<div class="card-header" id="heading{{challenge.id}}">
<h2 class="mb-0">
<button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}">
{{ challenge.question_text }} - {{ challenge.point_value }} points
</button>
</h2>
</div>
<div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}">
<div class="card-body">
<p>{{ challenge.description }}</p>
<form action="{% url 'challenges:answer' challenge.id %}" method="post">
{% if challenge|is_answered:request %}
<label for="answered">Answer</label>
<input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly>
{% else %}
{% csrf_token %}
<label for="answer">Answer</label>
<input type="text" name="answer" id="answer">
<input type="submit" value="Submit">
{% endif %}
</form>
</div>
</div>
{% endfor %}
</div>
Here is the view:
def index(request):
context = {'challenges_by_category_list': Category.objects.all()}
return render(request, 'challenges/index.html', context)
def detail(request, challenge_id):
challenge = get_object_or_404(Challenge, pk=challenge_id)
return render(request, 'challenges/detail.html', {'challenge': challenge})
def results(request, challenge_id, result):
challenge = get_object_or_404(Challenge, pk=challenge_id)
return render(request, 'challenges/results.html', {'challenge':challenge, 'result':result})
def answer(request, challenge_id):
challenge = get_object_or_404(Challenge, pk=challenge_id)
result = "Incorrect, try again!"
if challenge.answer_text.lower() == request.POST['answer'].lower():
current_user = request.user
session = User_Challenge(user=current_user, challenge=challenge, answered=True)
session.save()
points = Profile(user=current_user, points=challenge.point_value)
points.save()
result = "Correct!"
return HttpResponseRedirect(reverse('challenges:results', args=(challenge.id, result)))
You can try this:
Add the below script in your template:
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
write a script and a function inside it to submit the form data.
<script type="text/javascript">
function submitData( challenge_id ){
// Get answer from the input element
var answer = document.getElementById("answer").value;
// add the url over here where you want to submit form & challenge_id is also taken as a parameter.
var url = "<your_url>";
$.ajax({
url: url,
data: {
'answer': answer,
},
dataType: 'JSON',
success: function(data){
// show an alert message when form is submitted and it gets a response from the view where result is provided and if url is provided then redirect the user to that url.
alert(data.result);
if (data.url){
window.open(data.url, '_self');
}
}
});
}
</script>
Change type of the submit button and add an onclick event to call the submitData() function and pass the challenge id to it. And remove the action attr from the form.
see below:
<form method="post">
{% csrf_token %}
{% if challenge|is_answered:request %}
<label for="answered">Answer</label>
<input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly>
{% else %}
<label for="answer">Answer</label>
<input type="text" name="answer" id="answer">
// over here
<button type="button" onclick="submitData({{ challenge.id }})">
Submit
</button>
{% endif %}
</form>
Return a JsonReponse to the ajax call from the views.
views.py
def answer(request, challenge_id):
answer = request.GET.get('answer', False)
url = False
if challenge.objects.filter(id=challenge_id).exists() and answer:
challenge = Challenge.objects.get(id=challenge_id)
if challenge.answer_text.lower() == answer.lower():
current_user = request.user
session = User_Challenge(user=current_user, challenge=challenge, answered=True)
session.save()
points = Profile(user=current_user, points=challenge.point_value)
points.save()
result = "Correct!"
# specify the url where you want to redirect the user after correct answer
url = ""
else:
result = "Incorrect, try again!"
data = {
'result': result,
'url': url
}
return JsonResponse(data)
I have a view
(user_list.html)
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="list_main">
<div class="container">
{% for user in user_list %}
<ul>
<li><a href="{% url 'myapp:detail' pk=user.pk %}">
<div class="jumbotron">
<h4 class="list_content">{{user.name}}</h4>
</div>
</a></li>
</ul>
{% endfor %}
<div class="bttn">
<p><a type="button" class="btn btn-primary" href="{% url 'myapp:user' %}">Add</a></p>
</div>
</div>
</div>
{% endblock %}
Here with the help of
<p><a type="button" class="btn btn-primary" href="{% url 'myapp:user' %}">Add</a></p>
I am calling (views.py --> UserView)
def UserView(request):
response = requests.get('https://randomuser.me/api')
data = response.json()
title = data['results'][0]['name']['title']
first = data['results'][0]['name']['first']
last = data['results'][0]['name']['last']
final_name = " ".join([first,last])
#############################################
final_name = ". ".join([title, final_name]) #Final name of the user
#############################################
agee = data['results'][0]['dob']['age'] # age of the user
user = UserData.objects.create( name = final_name, age= agee, gender = gender)
user.save()
return redirect('detail', pk=user.pk) #This is not working
what I want to do is whenever the button from template (user_list.html) is clicked.
I want to enter this function in my views.py file perform the operations and redirect to
(path('detail/<int:pk>/', views.UserDetailView.as_view(), name='detail'),)
My views.UserDetailView
class UserDetailView(DetailView):
model = UserData
context_object_name = 'user_detail'
template_name = 'user_detail.html'
As shown in the code in( UserView(request) ), I have tried "return redirect('detail', pk=user.pk) "
this does not work.
Also please tell me if there is more neat and efficient way available to perform operations present in
( UserView(request) ) when button is clicked in ( user_list.html ) and then redirect from "UserView" to ((path('detail//', views.UserDetailView.as_view(), name='detail'),))
You missed app name myapp when using redirect:
return redirect('myapp:detail', pk=user.pk)
New to Django/Python/stackexchange...
I have a Jquery Datatable and I'm having difficulty passing along the value of a cell (called email_id) of the table as an HTTP parm to be used when handling a new form page.
The view is initially receiving the request correctly per the debug output:
WSGIRequest: GET '/main_app/makeTask/?csrfmiddlewaretoken=gDeTwaNfGNLO7cdMk1
B9gsdpcGYpKAyL&email_id=14d2a002852e1738'
It successfully extracts email_id with request.GET.get() on the first call (then proceeds to construct the form and render it) but it gets dropped when the form is being rendered. I.e., email_msg_id is extracted correctly on the GET but not on the subsequent POST.
Here is the extraction code along with the render statement. The problem is the 'email_id' is not propagating when I render the form so it cannot be used by view when it processes the form input.
email_msg_id = request.GET.get('email_id', "GET - no email_id")
...
return render(request, 'main_app/makeTask.html', {'form': form, 'email_id': email_msg_id})
Debug message:
<WSGIRequest: GET '/main_app/makeTask.html'>
Here are relevant sections of urls.py:
url(r'^makeTask', views.make_task, name='makeTask'),
My Jquery call (which appears to be working/passing along the email_ID correctly:
$('#make_task').click( function () {
alert( table.cell('.selected',4).data()+' Converted to Task');
// alert(table.cell('.selected',0).data()+' Make Task selected:');
$.ajax({
type: "GET",
url: "/main_app/makeTask/",
data: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
'email_id' : table.cell('.selected',4).data(),
},
success: makeTaskSuccess,
dataType: 'html'
});
function makeTaskSuccess(data)
{
alert('Convert email to task ');
}
} );
Here is the view (with unrelated stuff removed):
def make_task(request):
if request.method == "GET":
email_msg_id = request.GET.get('email_id', "GET - no email_id") # from the post dictionary of the request object passed in
else:
email_msg_id = request.POST.get('email_id', "POST - no email_id")
print "EMAIL_MSG_ID: ", email_msg_id, "METHOD: ", request.method
if request.method == 'POST':
form = MakeTaskForm(request.POST or None) # Create a form instance and populate it with the data
if form.is_valid():
# process and save to db
#...
return HttpResponseRedirect(reverse('main_app.views.index'))
else:
print form.errors
return
else:
form = MakeTaskForm()
return render(request, 'main_app/makeTask.html', {'form': form, 'email_id': email_msg_id})
#return render(request, 'main_app/makeTask.html', context_dict)
UPDATE: added relevant template code:
<form id="make_task_form" method="post" action="/main_app/makeTask/", method="Post">
{% csrf_token %}
<div class="row">
<div class="col-lg-8 col-xs-12">
<div class="form-group">
<label>Due Date:  </label>
<label class="radio-inline">
<input type="radio" name="due_selection" id="optionsRadiosInline1" value="TODAY" {{ form.due_selection }} Today
</label>
</div>
</div>
<div class="col-lg-4 col-xs-12">
<p>Specific Date: <input type="text" id="datepicker" {{ form.due_date }}</p>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-xs-12">
<button type="submit" class="btn btn-info btn-med" id="btn-make-task">
Make Task
</button>
<i class="fa fa-trash-o fa-2x pull-right"></i>
</div>
</div>
</form>
From the code you posted I assume you're using GET for AJAX and POST in your form.
The form code you posted is wrong, access your form fields in your template like this (also get rid of the duplicated method attribute in <form>):
<form id="make_task_form" method="post" action="/main_app/makeTask/">
{% csrf_token %}
<div class="row">
<div class="col-lg-8 col-xs-12">
{{ form.due_selection }}
</div>
<div class="col-lg-4 col-xs-12">
{{ form.due_date }}
</div>
</div>
<div class="row">
<div class="col-lg-4 col-xs-12">
<button type="submit" class="btn btn-info btn-med" id="btn-make-task">
Make Task
</button>
<i class="fa fa-trash-o fa-2x pull-right"></i>
</div>
</div>
</form>
To use <input type="radio"> for the field due_selection you should specify the RadioSelect widget in your ModelForm class:
CHOICES = (('1', 'First',), ('2', 'Second',))
due_selection = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES)