How to hide button/form with django templates? - python

I want to hide form if user already pushed on the button. I tried to use a bit of JS code, it works well, but after refreshing page, button on form stay valid. It not a huge surprise for me)) I want hide form using Django templates, but it is not so easy as I thought.
my html :
<div class="who_come">
<p>Who come : </p>
{% for u in who_come %}
{%if u.visiter.username != request.user.username %}
<form class="form-inline" role="form" method="post" id="joinToEventForm">
{% csrf_token %}
<p align="left"><b ><button type="submit">I want join</button></b></p></b></p>
</form>
{% endif %}
{% endfor %}
<div id="who_come_links">
{% for u in who_come reversed %}
<p>{{u.visiter.username}}</p>
{% endfor %}
</div>
<script>
$('#joinToEventForm').submit(function() {
$(this).find("button[type='submit']").prop('disabled',true);
});
</script>
<script>
$('#joinToEventForm').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
$.ajax({
type:'POST',
data:{
action: 'joinEvent',
csrfmiddlewaretoken:'{{ csrf_token }}'
},
success : function (data) {
//console.log(data);
var usernames = JSON.parse(data);
var html_str = '';
for (var i=0; i < usernames.length; i++) {
html_str += '<p>' + usernames[i] + '</p>';
}
$('#who_come_links').html(html_str);
}
});
});
</script>
</div>
my model :
class WhoComeOnEvent(models.Model):
visiter = models.ForeignKey(User, related_name='WhoComeOnEvent')
which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent')
in this place :
<p>Who come : </p>
{% for u in who_come %}
{%if u.visiter.username != request.user.username %}
<form class="form-inline" role="form" method="post" id="joinToEventForm">
{% csrf_token %}
<p align="left"><b ><button type="submit">I want join</button></b></p></b></p>
</form>
{% endif %}
{% endfor %}
i tried to check who already joined to event and if user that do request same that user in database table, then hide form. But this code doesn't work. It hide form no matter if user exist in db table or not. Second part is that has no connection to current event. Suppose django template that hide form in my case will work. It will check only row in table but it will ignore current it event or it different event (not sure, but i'm afraid of it).
my view :
def p(request, pk):
user = request.user
topic = get_object_or_404(Topic, pk=pk)
post = get_object_or_404(Post, pk=pk)
comment = Comments.objects.filter(pk=pk)
who_come = WhoComeOnEvent.objects.filter(which_event=topic.id)
if request.is_ajax() and request.POST.get('action') == 'joinEvent':
who_come_obj = WhoComeOnEvent.objects.create(
visiter=user,
which_event=post.topic
)
visitors_usernames = []
for w in who_come:
visitors_usernames.append(w.visiter.username)
return HttpResponse(json.dumps(visitors_usernames))
if request.method == 'POST':
form = CustomCommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.creator = user
comment = Comments.objects.create(
body=form.cleaned_data.get('body'),
creator=user,
post=post
)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
# return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment,
# 'form': form, 'who_come': who_come})
else:
form = CustomCommentForm()
return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment,
'form': form, 'who_come': who_come})
Solution:
I found more elegant solution, just adding .distinct('visitor') to my who_come queryset.
If someone will read it question and found my solution helpful, notice, that objects still creating to the databese and it doesn't unique!

Related

The ability to like/vote posts from the post list

I have a problem. I made likes to the posts on the video from YouTube. It is possible to like a post only from post_detail view and it's works correctly! How to make it possible to like posts in the post_list (in my case it's 'feed')? Please help!
MY CODE:
utils.py
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
views.py
from .utils import is_ajax
def feed(request):
comments = Comment.objects.all()
posts = Post.objects.all().order_by('-created_at')
return render(request, 'main/feed.html', {'posts': posts,
'comments': comments})
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post, reply=None).order_by('-created_at')
is_voted = False
if post.votes.filter(id=request.user.id).exists():
is_voted = True
if request.method == 'POST':
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
content = request.POST.get('content')
reply_id = request.POST.get('comment_id')
comment_qs = None
if reply_id:
comment_qs = Comment.objects.get(id=reply_id)
comment = Comment.objects.create(
post = post,
author = request.user,
content = content,
reply = comment_qs
)
comment.save()
return redirect(post.get_absolute_url())
else:
for error in list(comment_form.errors.items()):
messages.error(request, error)
else:
comment_form = CommentForm()
return render(request, 'main/post_detail.html', {'post':post,
'comment_form':comment_form,
'comments':comments,
'is_voted':is_voted})
#login_required
def post_vote(request, slug):
post = get_object_or_404(Post, id=request.POST.get('id'), slug=slug)
is_voted = False
if post.votes.filter(id=request.user.id).exists():
post.votes.remove(request.user)
is_voted = False
else:
post.votes.add(request.user)
is_voted = True
context = {
'post': post,
'is_voted': is_voted,
}
if is_ajax(request):
html = render_to_string('main/votes.html', context, request)
return JsonResponse({'form':html})
votes.html
<form action="{% url 'main:post-vote' slug=post.slug %}" method="post">
{% csrf_token %}
{% if is_voted %}
<button type="submit" id="vote" name="post_id" value="{{ post.id }}" btn="btn btn-outline">Unvote</button>
{% else %}
<button type="submit" id="vote" name="post_id" value="{{ post.id }}" btn="btn btn-outline">Vote</button>
{% endif %}
</form>
{{post.votes_count}}
post_detail.html
<div id="vote-section">
{% include 'main/votes.html' %}
</div>
<script>
$(document).ready(function(event){
$(document).on('click','#vote', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: "{% url 'main:post-vote' slug=post.slug %}",
data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'json',
success: function(resoponse){
$('#vote-section').html(resoponse['form'])
console.log($('#vote-section').html(resoponse['form']));
},
error: function(rs, e){
console.log(rs.responseText);
}
})
});
});
</script>
feed.html
...
{% for post in posts %}
<div id="vote-section">
{% include 'main/votes.html' %}
</div>
...
{% endfor %}
<script>
$(document).ready(function(event){
$(document).on('click','#vote', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: "{% url 'main:post-vote' slug=post.slug %}",
data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'json',
success: function(resoponse){
$('#vote-section').html(resoponse['form'])
console.log($('#vote-section').html(resoponse['form']));
},
error: function(rs, e){
console.log(rs.responseText);
}
})
});
});
</script>
models.py
class Post(models.Model):
...
votes = models.ManyToManyField(get_user_model(), related_name='votes', blank=True)
#property
def votes_count(self):
return self.votes.count()
urls.py
urlpatterns = [
path('', views.feed, name='feed'),
path('post_create/', views.post_create, name='post-create'),
path('post/<slug>/', views.post_detail, name='post-detail'),
path('post/<slug>/delete', views.post_delete, name='post-delete'),
path('post/<slug>/update', views.post_update, name='post-update'),
path('post/<slug>/vote', views.post_vote, name='post-vote'),
path('comment/<slug>/delete', views.comment_delete, name='comment-delete'),
path('comment/<slug>/update', views.comment_update, name='comment-update'),
path('comment_reply/<slug>/delete', views.reply_comment_delete, name='comment-reply-delete')
]
I understand that I need to do the same as in post detail. I tried to do this, but i got errors
def post_detail(request, slug):
post = get_object_or_404(Post, slug=slug)
comments = Comment.objects.filter(post=post, reply=None).order_by('-created_at')
is_voted = False
if post.votes.filter(id=request.user.id).exists():
is_voted = True
...
Tried to do:
def feed(request, slug=None):
comments = Comment.objects.all()
posts = Post.objects.all().order_by('-created_at')
v_post = get_object_or_404(Post, slug=slug)
is_voted = False
if v_post.votes.filter(id=request.user.id).exists():
is_voted = True
return render(request, 'main/feed.html', {'posts': posts,
'comments': comments,
'is_voted': is_voted})
got
Page not found (404)
Also tried
def feed(request, slug):
comments = Comment.objects.all()
count_filter = Q(votes=request.user)
vote_case = Count('votes', filter=count_filter, output_field=BooleanField())
posts = Post.objects \
.annotate(is_voted=vote_case) \
.all().order_by('-created_at')
return render(request, 'main/feed.html', {'posts': posts,
'comments': comments})
got
TypeError at /
feed() missing 1 required positional argument: 'slug'
UPD: For the attemp above, I also did something:
set slug to None
def feed(request, slug=None):
And and moved the script to the for-loop (for post in posts)
This gave its results. Now everything works almost as it should, only there is a bug. When you click on the vote button, he votes for for the post below, and vice versa
OK - there's a fair bit to unpack here:
First, generally speaking, it looks you you want Ajax to handle the bulk of the work. The reason (or at least the initial reason) why that isn't working above is in how you replicate forms
For well constructed HTML, only one element per page should have a particular ID
Your form is generated like this
{% for post in posts %}
<div id="vote-section"> #This will repeat for every post
{% include 'main/votes.html' %}
</div>
What this means is that every form will have the same id, vote-section, so
success: function(resoponse){
$('#vote-section').html(resoponse['form'])
won't know where to write.
Similarly, in the forms on list, every button has id="vote"
This isn't an issue on the details page, because there's only one form and one vote/unvote button. On the list page, with multiple forms, it is.
So what to do about it?
First off, add a class to your button.
votes.html
<button type="submit" id="vote" class="vote-button" name="post_id" value="{{ post.id }}" btn="btn btn-outline">Unvote</button>
Next tweak your feed html so it uses IDs correctly. We'll use {{[forloop.counter][1]}} to generate unique IDs.
We'll also move the ajax into the loop, as the slug for each post is different in the url: generation section. We add the new div ID into the selector and the success function to make it unique.
feed.html
{% for post in posts %}
<div id="vote-section{{forloop.counter}}">
{% include 'main/votes.html' %}
</div>
...
<script>
$(document).ready(function(event){
$(document).on('click','#vote-section{{forloop.counter}} .vote-button', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
//this needs to be in the for post in posts loop to get post.slug
url: "{% url 'main:post-vote' slug=post.slug %}",
data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'json',
success: function(resoponse){
$('#vote-section{{forloop.counter').html(resoponse['form'])
console.log($('#vote-section{{forloop.counter}}').html(resoponse['form']));
},
error: function(rs, e){
console.log(rs.responseText);
}
})
});
});
</script>
{% endfor %}
Now there are probably ways to make this more efficient, but hopefully it should get you over the hump to where it works.

How to direct a page from a form Django

I am working on a dictionary app, i am allowing a user to enter a word through a form. When the word is entered in the form and a submit button is pressed i want the form to be maintained on the same page however when the user enter the word and presses submit the form disappears leaving only the submit button and the search results
Here is the dictionary/form code
class NameForm(forms.Form):
your_name = forms.CharField(max_length=100, label=False)
the dictionary/view code
def index(request):
if request.method == 'POST':
form = NameForm(request.POST)
if form.is_valid():
word = form.cleaned_data['your_name']
print(word)
if Dictionary.get_verb(word):
verb = Dictionary.get_verb(word)
else:
verb = False
print(verb)
if Dictionary.get_noun(word):
noun = Dictionary.get_noun(word)
else:
noun = False
print(noun)
synonyms = Dictionary.get_synonyms(word)
print(synonyms)
form = NameForm()
context = {
'verb':verb,
'noun':noun,
'synonyms':synonyms,
}
return render(request,'index.html' ,context)
else:
form = NameForm()
context = {
'form': form,
}
return render(request, 'index.html', context)
and the index.html
form action="" method="post">
{% csrf_token %}
{{form}}
<br>
<input type="submit" value="Submit">
</form>
<hr>
{% if noun %}
<h2>Noun</h2>
{% for noun_word in noun %}
<p>{{noun_word}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
<br>
<hr>
{% if verb %}
<h2>Verb</h2>
{% for verb_info in verb %}
<p>{{verb_info}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
<h2>Synonyms</h2>
{% if synonyms %}
{% for synonym_info in synonyms %}
<p>{{synonym_info}}</p>
{% endfor %}
{% else %}
<!-- print nothing-->
{% endif %}
I have created a dictionary class to interact with the Dictionary API. But my challenge is how do i go about it so that when the form is submitted it will return the form and the button together with the results below. Thank you!!
you are missing the form in context when the form is valid, that's why it is disappearing.
form = NameForm()
context = {
'verb': verb,
'noun': noun,
'synonyms': synonyms,
'form': form ## missing this (add)
}
return render(request,'index.html' ,context)
You can add render in forms.py or you can set the action in your template
<form class="postForm" action="{% url 'name of your url' %}" method="POST">

Editing view for combined form and inline_formset

I have been trying to create an editing view that allows me manage both parent and child models using an inline formset based in the documentation here
From what I can appreciate the formset doesn't validate. I did try and change it so that instead of validating the entire formset it iterated through each individual form in the formset and validated them individually. This did allow me to add items to the formset but not delete them.
At the moment the code results in "didn't return an HttpResponse object. It returned None instead" value error as the redirect is in the If valid statement and so if that does not result in true there is no other redirect to fall back on.
Models
class Shoppinglist(models.Model):
name = models.CharField(max_length=50)
description = models.TextField(max_length=2000)
created = models.DateField(auto_now_add=True)
created_by = models.ForeignKey(User, related_name='lists', on_delete=models.CASCADE)
last_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Item(models.Model):
name = models.CharField(max_length=80, unique=True)
amount = models.IntegerField(default=1)
shoppinglist = models.ForeignKey(Shoppinglist, on_delete=models.CASCADE)
def __str__(self):
return self.name
URL
urlpatterns = [
url(r'^shoppinglists/(?P<pk>\d+)/edit/$', views.shoppinglist_edit, name='shoppinglist_edit'),
]
View
def shoppinglist_edit(request, pk):
try:
shoppinglist = Shoppinglist.objects.get(pk=pk)
except ShoppingList.DoesNotExist:
raise Http404
ItemInlineFormset = inlineformset_factory(Shoppinglist, Item, extra=1, fields=('name', 'amount'))
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
Template
{% block content %}
<form method="post">
{% csrf_token %}
<label>List Name</label>
{{ listform.name }}
{% if listform.first_name.errors %}
{% for error in listform.first_name.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
<label>Description</label>
{{ listform.description }}
{% if listform.description.errors %}
{% for error in listform.description.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
{{ formset.management_form }}
{% for form in formset %}
<div class="item-formset">
{{ form.amount }}
{% if form.amount.errors %}
{% for error in form.amount.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
{{ form.name }}
{% if form.name.errors %}
{% for error in form.name.errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
</div>
{% endfor %}
{% if formset.non_form_errors %}
{% for error in formset.non_form_errors %}
{{ error|escape }}
{% endfor %}
{% endif %}
<div class="row spacer">
<button type="submit" class="btn btn-block btn-primary">Create</button>
</div>
</form>
{% endblock %}
{% block extra_js %}
<script>
$('.item-formset').formset({
addText: 'add item',
deleteText: 'remove'
});
</script>
{% endblock %}
Please note I am using this jquery plugin in the template.
https://github.com/elo80ka/django-dynamic-formset
it is probably either your form or formset is invalid, and you dont use else statement to handle that.
so in your views.py:
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
# either your form or formset is invalid, so this code will render it again.
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
or you can simplify it with this:
if request.method == "POST":
form = ShoppinglistForm(request.POST, instance=shoppinglist)
formset = ItemInlineFormset(request.POST, instance=shoppinglist)
if formset.is_valid() and form.is_valid():
form.save()
formset.save()
return redirect('packlist_list', pk=pk)
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
# notice the indentation
context = {
'shoppinglist' : shoppinglist,
'listform': form,
'formset': formset,
}
return render(request, 'edit_list_with_items.html', context)
Mentioned error coming because you write this return render(request, 'edit_list_with_items.html', context) inside else block.
instead of this:
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
'
}
return render(request, 'edit_list_with_items.html', context)
Do this:
else:
form = ShoppinglistForm(instance=shoppinglist)
formset = ItemInlineFormset(instance=shoppinglist)
context = {
}
return render(request, 'edit_list_with_items.html', context)

How to retrieve value from checkbox defined in django template

I have created a menu with three options(home,change password and logout). In home I am displaying all the books stored in the database. Now I want to filter the contents based on categories of the books using checkbox. By default all the books are shown upon filtering the category only the books of that category should be shown.But for me it is showing all the books even after clicking on all the checkbox (checkbox contains the categories).I think there is some problem in my template file.
urls.py,
url(r'^welcome_user/$',views.welcome_user, name='welcome_user'),
Models.py,
class Add_cat(models.Model):
category = models.CharField("Name",max_length=25,unique=True)
def __unicode__(self):
return u'{0}'.format(self.category)
class Add_prod(models.Model):
book = models.CharField("Book Name",max_length=40)
author = models.CharField("Author",max_length=30)
price = models.PositiveIntegerField("Price")
image = models.ImageField(upload_to='images',null=True)
cat = models.ForeignKey(Add_cat,on_delete=models.CASCADE)
Template file,
{% block content %}
{% load staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
<div class="box">
<div class="sideNav">
<form action="{% url 'welcome_user' %}">
<p id=id3>Categories</p>
<hr>
{% for i in products %}
<input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}<br>
{% endfor %}
<button type="submit">Submit</button>
</form>
</div>
<div>
{% for i in products %}
<div style="display:inline-block;margin:30px">
<img src="{{i.image.url}}" alt="No Image" width=196px height=196px>
<p id=id4>Rs.{{i.price}}</p>
</div>
{% endfor %}
</div>
</div>
</body>
{% endblock %}
Views.py,
#login_required
def welcome_user(request):
if 'cat_name' in request.GET:
filter_category = request.GET.getlist('cat_name')
my_products = Add_prod.objects.filter(cat__in=filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
To check whether checbox value is in sent form you should go with following condition
if 'cat_name' in request.GET:
#checkbox has been checked
else:
#it is not checked
Remember that in operator return boolean so you can also do
filter_category = 'cat_name' in request.GET
To get value you just need to get values of 'cat_name' key like:
value = request.GET['cat_name']
after checking whether it is in GET parameters or not
I think all you need to do is add __in to your filter:
#login_required
def welcome_user(request):
filter_category = request.GET.getlist('cat_name')
categories = Add_cat.objects.all()
if filter_category: # I couldn’t decipher the structure of an `Add_cat`, so I left off the `in` check since it would not work for lists
print filter_category
my_products = Add_prod.objects.filter(cat__in=filter_category) # the template implies that this field is `cat` and not `category`
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
Checkboxes work a little bit different from other form inputs, so if you examine a post sent from a form that includes a checkbox,
if the checkbox is checked, your queryset will look like:
the value will be 'on'
So, you have to check
if request.POST.get('cb1')=='on':
"item is selected"
else:
"item is not selected"
Try this below code
Add_prod.objects.filter(cat__in=filter_category)
#login_required
def welcome_user(request):
filter_category = request.GET.getlist('cat_name')
if filter_category:
my_products = Add_prod.objects.filter(cat__in=filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
Template file
Remove quotes(') from {% url 'welcome_user' %}
<form method='get' action="{% url welcome_user %}">
UPDATE
Add quotes between views.welcome_user
urls.py
url(r'^welcome_user/$','views.welcome_user', name='welcome_user'),

Django with ajax render

I am pretty new to Django and I try to create my first application. However I faced a problem now.
I have a form (to add Alert - my mdoel) with Django validation and a div with list of all alerts. If I fill all fields correctly the alert is added and my div with alerts is refreshed using ajax. The problem is with form validation.
Without ajax I was sending bound form with errorLists for every field. I used Django form API. It was working ok but I can't refresh the errorlist if adding a form couldn't succeed.
I am getting either no render of form or render without context - all fields are blank. Of course they shouldn't be blank if I made a mistake in one field and It was working OK without ajax.
Bunch of code, First this is the view method I call:
def add_alert(request):
report = __get_or_create_empty_Report(request)
if request.method == 'POST':
form = AlertForm(request.POST)
if form.is_valid():
alert_project = ""
alert_name = ""
alert_ticket = ""
alert_date = ""
alert_type = ""
alert_comment = ""
if form.cleaned_data.has_key('alert_project'):
alert_project = form.cleaned_data['alert_project']
if form.cleaned_data.has_key('alert_name'):
alert_name = form.cleaned_data['alert_name']
if form.cleaned_data.has_key('alert_ticket'):
alert_ticket = form.cleaned_data['alert_ticket']
if form.cleaned_data.has_key('alert_date'):
alert_date = form.cleaned_data['alert_date']
if form.cleaned_data.has_key('alert_type'):
alert_type = form.cleaned_data['alert_type']
if form.cleaned_data.has_key('alert_comment'):
alert_comment = form.cleaned_data['alert_comment']
alert = Alert()
alert.alt_prj_id = get_object_or_404(Project, prj_id=alert_project)
alert.alt_name = alert_name
alert.alt_ticket = alert_ticket
alert.alt_date = alert_date
alert.alt_type = alert_type
comment = Comment()
comment.com_value = alert_comment
comment.save()
alert.alt_com_id = comment
alert.alt_rep_id = report
alert.save()
alerts = Alert.objects.filter(alt_rep_id=report.rep_id)
return render(request, 'main/theform.html', {'form': form, 'alerts': alerts, 'error_message': "Alert has been added"})
else:
form = AlertForm()
alerts = Alert.objects.filter(alt_rep_id=report.rep_id)
return render(request, 'main/theform.html', {'form': form, 'alerts': alerts})
alerts = Alert.objects.filter(alt_rep_id=report.rep_id)
return render(request, 'main/theform.html', {'form': form, 'alerts': alerts, 'error_message': "Alert has NOT been added"})
Here's the form template:
{% extends 'main/base.html' %}
{% block content %}
<div id="alerts"> </div>
{% for alert in alerts %}
<p> {{ alert.alt_name }} </p>
{% endfor %}
<form class="col-md-12" action="{% url 'main:add_alert' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{{ error_message }}
{% endblock %}
and simple script:
$(document).ready(function() {
//AJAX util
$('.add-alert-form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
$("#alerts").load(" #alerts");
}
});
});
}
I think I am doing it completly wrong but I have no idea what's the right way.
Take a look at https://docs.djangoproject.com/en/1.7/topics/forms/modelforms/
so your views would look like that:
if form.is_valid():
obj = form.save()
data = serializers.serialize('json', [obj,])
else:
data = json.dumps(dict([(k, [unicode(e) for e in v]) for k,v in form.errors.items()]))
return HttpResponse(data, mimetype='application/json')

Categories

Resources