Home > Mobile >  Update screen on button click Django
Update screen on button click Django

Time:07-29

Say I have a screen that looks like this:

Times clicked: 0
[button]

And every time I click the button, the times clicked would increment by 1. How would I go about doing this?

CodePudding user response:

You've tagged this question with django and django forms, so I'll ignore javascript based solutions and assume you want this to be persistent and universal (in that every user sees the same number).

assuming an app called count_things

start with count_things/models.py

from django.db import models

class Counter(models.Model):
    count_num = models.PositiveSmallIntegerField(default=0)
    name= models.CharField(max_length=255)

This is the model which will be instantiated in the database to store the number of clicks

run python manage.py makemigrations then python manage.py migrate to update the database with a table for this model

count_things/views.py

from django.http import HttpResponse
from django.shortcuts import render
def view_counter(request):
    counter = Counter.objects.get_or_create(name="page_counter")
     
    if request.method == "POST":
        counter.count_num = counter.count_num   1
        counter.save()
    return render(request, "count_things/count_clicker.html" {"counter":counter})

This is the view that handles adding one to the counter when a form is submitted. We're not overly fussed about form validity because there are no fields in our form.

then in your count_things/templates/count_things/count_clicker.html

 <html>
 <body>    
 <form method="POST">
      {% csrf_token %}
      <p>times clicked: {{counter.count_num}}</p>
     <input type="submit" value = "Add one to me!">
 </form>
 </body>
 </html>   

This is the form itself. It's just a submit button in a form wrapper.

count_things/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.view_counter, name='view counter'),
]

urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("count_things.urls"))
]

Add urls to suit. Here it should just be the first page of our website, with no filename or foldername,eg, http://127.0.0.1:80000

python manage.py runserver to start up your server, then visit your server url

  • Related