Tomek
Tomek

Reputation: 116

Django add function to button in template

I dont know how can I add function from views.py to atribute action in my template. I'd like when I click the button then my page refreshes and add comment to datebase.

Part of my template:

    <form action = '???' method = "post">
    {{ formularz.as_p}}
    <input type="submit" value="Submit" />
</form>

Part of views.py:

def ShowNewses(request):
    newses = News.objects.filter(status = 'p')
    return render_to_response('news.html', {'news_set': newses})

def ArchiveNews(request,topic,year, month, day):
    news = News.objects.filter(date__year = int(year), date__month = int(month), date__day = int(day),topic = topic)
    comments = Comments.objects.all()
    formularz = CommentsForm()
    return render_to_response('knews.html', {'news': news[0],'comments': comments, 'formularz': formularz}) 

def AddComment(request):
    L = request.META['PATH_INFO'].split('/')
    if request.POST:    
    k = CommentsForm(request.POST)
    k.save()
    return HttpResponseRedirect(reverse('ArchiveNews', kwargs = {'request' = request, 'year' = L[3], 'month' = L[4], 'day' = L[5]}))

AddComment is function which I want in my button. ArchiveNews is induced when I choose news which will be in new page.

EDIT
part of urls.py:

url(r'^news/$', ShowNewses),
url(r'^news/(?P<topic>.+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', ArchiveNews),

I updated here part of views.py. I added ShowNewses.

Upvotes: 1

Views: 6788

Answers (2)

Tomek
Tomek

Reputation: 116

I used url name. My actualy files: views.py

def ArchiveNews(request, topic, year, month, day):
    print request.POST
    news = News.objects.filter(date__year = int(year), date__month = int(month), date__day = int(day),topic = topic)
    comments = Comments.objects.all()
    formularz = CommentsForm()
    return render_to_response('knews.html', {'news': news[0], 'comments': comments, 'formularz': formularz, 'topic': topic, 'year': year, 'month': month,'day': day})   


def AddComment(request,topic,year,month,day):
    print 'foo'
    if request.POST:
        k = CommentsForm(request.POST)
        k.save()
    return HttpResponseRedirect(reverse('ArchiveNews', args = (topic,year,month,day)))

And part of my template:

<form action = {% url addcomment topic year month day %} method = "post">
        {{ formularz.as_p}}
        <input type="submit" value="Submit" />
    </form>

part of urls.py:

url(r'^news/(?P<topic>.+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', ArchiveNews),
url(r'^news/(?P<topic>.+)/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})', AddComment, name = 'addcomment'),

EDIT: I updated my files

Upvotes: 0

cberner
cberner

Reputation: 3040

You need to add AddComment to your urls.py file. Then, assuming your app is named "myapp" you would use this in your template: {% url myapp.views.AddComment %}

Upvotes: 1

Related Questions