Refresh Values on Django Template using repeated AJAX calls - django

I have a django webapp where I want to update a field with random values after every 10 seconds. Here's the code structure:
views.py
temp_values = [1, 2, 3, 3, 4, 5, 5, 6, 6, 7]
def get_temp():
return temp_values[random.randint(0, 6)]
def ajax_data():
data = {'temp': get_temp()}
json_data = json.dumps(data)
return Response(json_data, mimetypes='application/json')
class IndexPageView(TemplateView):
template_name = 'main/index.html'
class ControlPageView(TemplateView):
template_name = 'main/control.html'
def index(self, request):
return render(request, self.template_name, {})
def get(self, request):
form = ControlForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = ControlForm(request.POST)
set_temp = 'bs'
if form.is_valid():
set_temp = form.cleaned_data['set_temp']
write_to_register(2, set_temp)
args = {'form': form, 'text': set_temp}
return render(request, self.template_name, args)
control.html
<div class="container">
<div class="section">
<div class="col grid_1_of_3">
<h3>Temperature</h3>
<input type="checkbox"> On/Off <br>
<label>Current: </label><input type="text" class="curr_temp" placeholder="34" disabled="disabled"><br>
<form action="" method="POST">
{% csrf_token %}
<script src="http://code.jquery.com/jquery-3.0.0.js"></script>
<script language="javascript" type="text/javascript">
function updateValue() {
$.ajax({
url:"/ajax_data",
});
$(".curr_temp").attr("placeholder", v);
}
$(document).ready(function(){
var v = setInterval(updateValue,2000);
});
</script>
{{ form.as_p }}
<button type="submit">Set</button>
</form>
<img src="{% static 'img/graph.png' %}" alt="graph"/>
</div>
urls.py
import random
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from django.conf.urls.static import static
from .utils import read_specific_response
import random
from main.views import IndexPageView, ChangeLanguageView, ControlPageView, ViewPageView
# pressure = read_specific_reponse(12)
# RPM = read_specific_reponse(29)
urlpatterns = [
path('admin/', admin.site.urls),
path('', IndexPageView.as_view(), name='index'),
path('i18n/', include('django.conf.urls.i18n')),
path('language/', ChangeLanguageView.as_view(), name='change_language'),
path('control/', ControlPageView.as_view(), name='control'),
path('view/', ViewPageView.as_view(), name='view'),
path('accounts/', include('accounts.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
There is a current temp field & a set temp field (for which I have created a form which posts request on submit button click).
However console keeps throwing 404 url not found error. Please let me know where I am I going wrong

You have to add your ajax_data view in your urls.py file
urlpatterns = [
path('admin/', admin.site.urls),
path('', IndexPageView.as_view(), name='index'),
path('i18n/', include('django.conf.urls.i18n')),
path('language/', ChangeLanguageView.as_view(), name='change_language'),
path('control/', ControlPageView.as_view(), name='control'),
path('view/', ViewPageView.as_view(), name='view'),
path('ajax_data', ajax_data, name='ajax_data'),
path('accounts/', include('accounts.urls')),
]

Related

Page not found at /register/... Raised by: my_blog.views.post_detail... Django

I'm working on Django blog, and I'm working on register form. I got error Page not found at /register/ like you can see on image. But it say that error was raised by post_detail - Raised by: my_blog.views.post_detail
This is register.html
{% extends "base.html" %}
{% load static %}
{% block content %}
{% load crispy_forms_tags %}
<!--Register-->
<div class="container py-5">
<h1>Register</h1>
<form method="POST">
{% csrf_token %}
{{ register_form|crispy }}
<button class="btn btn-primary" type="submit">Register</button>
</form>
<p class="text-center">If you already have an account, login instead.</p>
</div>
{% endblock %}
Views.py
def register_request(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
messages.success(request, "Registration successful." )
return redirect("main:homepage")
messages.error(request, "Unsuccessful registration. Invalid information.")
form = NewUserForm()
return render (request=request, template_name="register.html", context={"register_form":form})
def post_detail(request, slug):
latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9]
post = get_object_or_404(Post, slug=slug)
context = {'post': post, 'latest_posts': latest_posts}
return render(request, 'post_detail.html', context)
blog/urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.home, name='home'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
]
forms.py
class NewUserForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(NewUserForm, self).save(commit=False)
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
I got this error and I don't understand why I get this error. Any ideas?
Thanks in advance!
"register" is a valid slug so the post_detail url is matching the incoming path as it's before your register url in urlpatterns.
The first option is to change post_detail to include a prefix so that it doesn't match your other urls
urlpatterns = [
path('', views.home, name='home'),
path('post/<slug:slug>/', views.post_detail, name='post_detail'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
]
Or you could put post_detail last so that other urls are matched first
urlpatterns = [
path('', views.home, name='home'),
path('category/<slug:slug>/', views.category_detail, name='category_detail'),
path('register/', views.register_request, name='register'),
path('<slug:slug>/', views.post_detail, name='post_detail'),
]

I'm getting a NoReverseMatch error in my home page

I'm getting a NoReverseMatch error in my home page. It is from the html that I injected from my announcement app. It says that the reverse of the link is cannot be found. When I removed that line It shows the card but the text with template tag.
_announcement_home.html:
<div class="container">
<div class="card announcement-card" style="width: 18rem;">
<h5 class="card-header">Announcement</h5>
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>
</div>
<br>
</div>
index.html:
{% extends 'base.html' %}
{% block content %}
<div class="w3-container w3-teal">
<h1>BANNER HERE</h1>
<p>Dito yung banner</p>
</div>
{% include 'announcement/_announcement_home.html' %}
{% endblock %}
urls.py:
from django.urls import path
from . import views
app_name = 'announcement'
urlpatterns = [
path('create/', views.AnnouncementCreateView.as_view(), name='create'),
path('', views.AnnouncementListView.as_view(), name='list'),
path('posts/<int:pk>/', views.AnnouncementDetailView.as_view(), name='single'),
path('delete/<int:pk>/', views.AnnouncementDeleteView.as_view(), name='destroy'),
path('edit/<int:pk>/', views.AnnouncementUpdateView.as_view(), name='edit')
]
main urls.py:
"""urcipro URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from home import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.Home.as_view(), name='home'),
path('bod/', views.BOD.as_view(), name='bod'),
path('announcement/', include('announcement.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy, reverse
from django.contrib import messages
from . import forms
from . import models
# Create your views here.
class AnnouncementListView(LoginRequiredMixin, generic.ListView):
model = models.Announcement
class AnnouncementDetailView(LoginRequiredMixin, generic.DetailView ):
model = models.Announcement
class AnnouncementUpdateView(LoginRequiredMixin, generic.UpdateView):
model = models.Announcement
form_class = forms.AnnouncementForm
class AnnouncementCreateView(LoginRequiredMixin, generic.CreateView ):
model = models.Announcement
form_class = forms.AnnouncementForm
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
class AnnouncementDeleteView(LoginRequiredMixin, generic.DeleteView ):
model = models.Announcement
def get_success_url(self):
return reverse('home')
def delete(self, *args, **kwargs):
messages.success(self.request, "Post Deleted")
return super().delete(*args, **kwargs)
home app views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
class Home(TemplateView):
template_name = 'index.html'
class BOD(TemplateView):
template_name = 'bod.html'
This is what I see when I remove the a tag:
Error traceback:
It looks like the context has announcement to display this information, and then you used self in the url tag which isn't defined.
So change the url param to announcement.pk which we can assume will exist because that's the object in use with this block.
<div class="card-body">
<h5 class="card-title">{{announcement.title}}</h5>
<p class="card-text">{{announcement.text}}</p>
<span class="announcement-date">{{announcement.date}}</span>
{% if user.is_authenticated %}
Change
{% endif %}
</div>

Input redirect me on the wrong view

Hello i'm a beginner at django and i got this problem. (i don't know if the code i put is enough)
When i decide to create a new comment, if i click on "create" instead of redirect me to "usercomments" and send the data to the database, it log me out and send me where log out is supposed to send me. i can't find a similar problem, i don't even know what kind of error it is, help
Thanks :)
Templates of "create comment" :
<div class="create-comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'usercomments:create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
Urls.py :
from django.conf.urls import url
from . import views
app_name = 'usercomments'
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
Views of create comment :
#login_required(login_url="/userprofile/login/")
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
# save article to db
instance = form.save(commit=False)
instance.author = request.user
instance.save()
return redirect('usercomments:list')
else:
form = forms.CreateComment()
return render(request, 'usercomments/comments_create.html', { 'form': form })
Views of log out :
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/') <--- Where i get redirected when i press "create"
else:
pass
Urls of logout :
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

Log out when sending a form

I've created an app where you can make comment (which sends a form to a database and saves it) if you're login on only, but when I press the button "Create" instead of redirecting me to the page where it show all the comments, it logs me out and bring me back to the "log out" view (which is / )
the create Template:
{% extends 'base.html' %}
{% block content %}
<div class="create_comment">
<h2>Write a comment</h2>
<form class="site-form" action="{% url 'create' %}" method="post">
{% csrf_token %}
{{form}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
The Views of Create:
#login_required(login_url='/userprofile/login/')
def comments_create(request):
if request.method == 'POST':
form = forms.CreateComment(request.POST)
if form.is_valid():
form.save()
return redirect('/usercomments')
else:
form = forms.CreateComment()
return render(request,'usercomments/comments_create.html', {'form':form})
Log out view:
def logout_view(request):
if request.method == 'POST':
logout(request)
return redirect('/')
else:
pass
usercomments Urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.comments_list, name="list"),
url(r'^create/$', views.comments_create, name="create"),
url(r'^(?P<slug>[\w-]+)/$',views.comments_detail, name="detail"),
]
userprofile urls.py:
from django.conf.urls import url
from . import views
app_name = 'userprofile'
urlpatterns = [
url(r'^signup/$', views.signup_view, name="signup"),
url(r'^login/$', views.login_view, name="login"),
url(r'^logout/$',views.logout_view, name="logout"),
]

Request is not getting into views, but its shows the corret url

Form is loaded in html page but when i click submit button,it shows nothing(No HttpResponse which i used in views). But it show url(http://localhost:8000/datainsert )as i described in urls.py. Please point out what's wrong in my code.
forms.py
from django import forms
from .models import Test
class TestForm(forms.ModelForm):
class Meta:
model = Test
fields = '__all__'
views.py
def datainsert(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('Saved')
return HttpResponse('Not saved')
urls.py
from django.conf.urls import url
from . import views
from .views import index, datainsert, testing
urlpatterns = [
url(r'^', views.index, name='index'),
url(r'^datainsert', views.datainsert, name='datainsert'),
]
index.html
<html>
<head>
<title>My Web</title>
</head>
<body>
<form action="{% url 'myapp:datainsert' %}" method="POST">
{% csrf_token %}
{{form}}
<button type="submit">Submit</button>
</form>
</body>
</html>
You didn't terminate your empty URL.
url(r'^$', views.index, name='index')
Currently it matches every possible path.