AJAX code doesnt working with Django project - python

enter code hereIm making sort of a game where users can create or join a room with code and play a game...For now i only want to show all the users that are in the one room and i dont want the page to refresh when someone new enters. I asked few guys on reddit and they said i should use AJAX so i watched some tutorials but it doesn show anything.
here is my code:
from asyncio.windows_events import NULL
from hashlib import new
from django.shortcuts import render, redirect
from .models import Room, User
from django.contrib import messages
from random import randint
from django.http import JsonResponse
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
def index(request):
return render(request, 'index.html')
def checkroom(request):
if request.method == "POST":
Uspeo = False
username = ''
code = 0
# join with code
if 'dugme1' in request.POST:
username = request.POST["username"]
no1 = request.POST["no1"]
no2 = request.POST["no2"]
no3 = request.POST["no3"]
no4 = request.POST["no4"]
no5 = request.POST["no5"]
no6 = request.POST["no6"]
number = no1+no2+no3+no4+no5+no6
if len(username) == 0:
messages.info(request, 'Enter your name!')
return redirect('/')
else:
if Room.objects.filter(Room_code=number).exists():
user = User.objects.create(username=username, code=number)
user.save()
return redirect('/room/?code=' + number + '&username=' + username)
else:
messages.info(request, 'Code not found!')
return redirect('/')
#make room
elif 'dugme' in request.POST:
code = random_with_N_digits(6)
while Uspeo != True:
if Room.objects.filter(Room_code=code).exists():
Uspeo = False
code = random_with_N_digits(6)
return redirect('/')
else:
Uspeo = True
new_code = Room.objects.create(Room_code = code)
new_code.save()
return redirect('/makeroom/?code=' + str(code))
else: pass
def makeroom(request):
code = request.GET.get("code")
formatted_code = code[:3] + " " + code[3:]
if request.method == 'POST':
username = request.POST['username2']
user = User.objects.create(username=username, code=code)
user.save()
return redirect("/room/?code="+code+"&username="+ username)
return render(request, "makeroom.html",{'code':formatted_code})
def room(request):
code = request.GET.get("code")
username = request.GET.get("username")
#users = User.objects.filter(code=code)
return render(request, "room.html")
def get_users(request):
if request.method == 'GET':
code = request.GET.get('code')
users = User.objects.filter(code=code)
user_list = [{'username': user['username']} for user in users]
return JsonResponse(user_list, safe=False)```
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Make Room</title>
</head>
<body>
<h1>Users in Room</h1>
<ul id="display">
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
</ul>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function refreshUsers() {
$.ajax({
url: '/get_users/', // Replace with your Django view URL that returns the list of users
data: {'code': '{{ code }}'}, // Pass the room code as a parameter to the view
dataType: 'json',
success: function(data) {
$('#display').empty();
for (var i = 0; i < data.length; i++) {
$('#display').append('<li>' + data[i].username + '</li>');
}
},
error: function(xhr, status, error) {
console.log(error);
}
});
}
setInterval(refreshUsers, 5000); // Refresh the list of users every 5 seconds
</script>
</body>
</html>`
you can check out video where i demonstrate how my project work on reddit: [link ][1]
I tried asking ChatGPT and watching tutorials but nothing works. I expect to show all the users in one room but it shows nothin(there is no errors)
[1]: https://www.reddit.com/r/django/comments/11382fb/i_need_help/

Related

Using ajax jquery for search form

I'm working on a Django project where I want to use ajax jquery to complete my search in my search form.
Tried everything, but it does not seem to work.
Pls, where have I missed it?
used this tutorial
views.py
import json
def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
query = form.cleaned_data['query']
catid = form.cleaned_data['catid']
if catid == 0:
products = Product.objects.filter(name__icontains=query)
else:
products = Product.objects.filter(name__icontains=query, category_id=catid)
category = Category.objects.all()
context = {
'products': products,
'category': category,
'query': query,
}
return render(request, 'shop/product/search.html', context)
return HttpResponseRedirect('/')
def search_auto(request):
if request.is_ajax():
q = request.GET.get('term', '')
products = Product.objects.filter(name__icontains=q)
results = []
for pl in products:
product_json = {}
product_json = pl.name
results.append(product_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
<script>
$(function() {$("#query").autocomplete({
url: "{% url 'shop:search_auto' %}",
select: function (event, ui) {AutoCompleteSelectHandler(event, ui)},
minLength: 2,
});
});
function AutoCompleteSelectHandler(event, ui)
{var selectedObj = ui.item;}
</script>
path('search', views.search_auto, name='search_auto'),
Thanks.

Using data returned from forms in Django

Sorry for being a little new. My goal is to use the data collected from a user form to output a graph. The user inputs an initial 'price' then submits this number, it then goes into my formulas written in python and then django should display a chart in the same HTML file. I'm currently stuck on how to use data from 'POST'.
For example, if I'd like to take the cleaned_data from 'strike1' and multiply it by 4, then display it on the webpage, how would I go about doing that?
views.py
from django.shortcuts import render
from .forms import DataForm
# Create your views here.
def data(request):
if request.method == 'POST':
form = DataForm(request.POST)
if form.is_valid():
strike1 = form.cleaned_data['strike1']
strike2 = form.cleaned_data['strike2']
strike3 = form.cleaned_data['strike3']
strike4 = form.cleaned_data['strike4']
strategy = form.cleaned_data['strategy']
price = range(0,50)
premium1 = form.cleaned_data['premium1']
premium2 = form.cleaned_data['premium2']
premium3 = form.cleaned_data['premium3']
premium4 = form.cleaned_data['premium4']
contracts = form.cleaned_data['contracts']
form = DataForm()
return render(request, 'form.html', {'form': form})
forms.py
from django import forms
class DataForm(forms.Form):
strategy = forms.ChoiceField(
choices=[('Long Call', 'Long Call'), ('Long Put', 'Long Put'), ('Short Call', 'Short Call',),
('Short Put', 'Short Put'), ('Bull Call Spread', 'Bull Call Spread'),
('Bear Put Spread', 'Bear Put Spread'), ('Straddle', 'Straddle'),
('Butterfly Spread', 'Butterfly Spread'),
('Box Spread', 'Box Spread'), ('Iron Condor', 'Iron Condor')])
strike1 = forms.FloatField()
strike2 = forms.FloatField()
strike3 = forms.FloatField()
strike4 = forms.FloatField()
premium1 = forms.FloatField()
premium2 = forms.FloatField()
premium3 = forms.FloatField()
premium4 = forms.FloatField()
contracts = forms.IntegerField()
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Website</title>
</head>
<body>
<form method="'post">
{% csrf_token %}
{{ form }}
<button type="Submit">Generate</button>
</form>
</body>
</html>
I'd say the cleanest way to do it, is to build up a new "content" and render a new page in the POST processing section. For example:
from django.shortcuts import render
from .forms import DataForm
# Create your views here.
def data(request):
if request.method == 'POST':
form = DataForm(request.POST)
if form.is_valid():
# ... do you processing as it
return render(request, 'output.html', {'data': whatever})
form = DataForm()
return render(request, 'form.html', {'form': form})
You could also just let it call through to the original render function, but you'll need to include whatever information you want in the context like {"form: form} already is.
U need to create 2 views for using data.(basicly)
One for form, one for your formulas.
in urls.py
path('formpage/', views.formpage, name='form_view'),
path('result/', views.result, name='MY_calculator'),
in views.py
def formpage(request):
return render(request, '-----Template-----',)
def result(request):
x=request.GET.get('xval')
y=request.GET.get('yval')
result=x+y
return render(request, '-----Result Template----', {'result': result})
and form action for template. ("" instead of)
<form action="{% url 'MY_calculator' %}">
You can set initial values to your form and render them to the same template within the same URL.
Here is an example:
def data(request):
if request.method == 'POST':
form = DataForm(request.POST)
if form.is_valid():
strike1 = form.cleaned_data['strike1'] * 2
strike2 = form.cleaned_data['strike2'] * 3
# Set initials
# strike1 & strike2 new values will be rendered as default values
# in your form
form = DataForm(initial={'strike1': strike1, 'strike2': strike2})
return render(request, 'form.html', {'form': form})
form = DataForm()
return render(request, 'form.html', {'form': form})
Also, you must pay attention, in your template HTML you wrote "'post" instead of "post".

Django FutureFqType matching query does not exist

I'm setting up a new website using Django, and want to get an object name from
sql . But it keep output the error objects.get matching query does not exist
Where do I need to modify the code?
views
def predict1(request):
name = ''
loginstatus = False
try:
name = request.session['name']
loginstatus = True
except:
return HttpResponseRedirect('/login/?back=未來型預測')
category_id = FutureMember.objects.get(member_name=name).type
cname = FutureFqType.objects.get(type_id=category_id).type_name
return render_to_response('predicts.html', {'cname': cname,'loginstatus': loginstatus, 'name': name})
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<div><h2>根據投資人屬性測驗結果,您屬於<font color="#75CA20">{{ cname }} 您好! {{ name }}</font></h2>
<form action="/predict/" method="post">
</div>
</body>
</html>
models
class FutureFqType(models.Model):
type_id = models.CharField(primary_key=True, max_length=2)
type_name = models.CharField(max_length=20)
type_describe = models.TextField(blank=True, null=True)
type_score = models.CharField(max_length=20)
class Meta:
managed = False
db_table = 'future_fq_type'
I expect the output of {{ cname }} to be data, but the actual can't output
It comes out an error FutureFqType matching query does not exist.
new views
from django.shortcuts import get_object_or_404
def predict1(request):
loginstatus = False
try:
name = request.session["name"]
loginstatus = True
except KeyError:
return HttpResponseRedirect("/login/?back=未來型預測")
category_id = get_object_or_404(FutureMember, member_name=name).type
cname = get_object_or_404(FutureFqType, type_id=category_id).type_name
return render_to_response(
"predicts.html",
{"cname": cname, "loginstatus": loginstatus, "name": name},
)
page output
enter image description here
from django.shortcuts import HttpResponse, get_object_or_404, redirect, render
def predict1(request):
loginstatus = False
try:
name = request.session["name"]
loginstatus = True
except KeyError:
return redirect("/login/?back=未來型預測")
try:
member = FutureMember.objects.get(member_name=name)
except FutureMember.DoesNotExist:
msg = f"<h1>FutureMember not found with member_name=`{name}`</h1>"
return HttpResponse(msg)
try:
fqtype = FutureFqType.objects.get(type_id=member.type)
except FutureFqType.DoesNotExist:
msg = f"<h1>FutureFqType not found with type_id=`{member.type}`</h1>"
return HttpResponse(msg)
else:
cname = fqtype.type_name
data = {"cname": cname, "loginstatus": loginstatus, "name": name}
return render("predicts.html", data)

Error in Django Get request that dosen't make sense

I have a basic Django app right now which allows users to add items to a database. When the product is added, the list of items should update when a new item is added via the form, and display that Product and all the other Products already in the database. Here is the code I have so far:
This is the views.py file with my current implementation of the method that should get the products at the bottom:
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from django.http import HttpResponse, JsonResponse
def index(request):
return render(request, 'index.html')
#csrf_exempt
def createProduct(request):
if request.method == 'POST':
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
newProduct = Product(
name = name,
description = description,
price = price
)
newProduct.save()
return HttpResponse('')
def viewProduct(request):
if request.method == 'GET':
ProductList = Product.objects.all()
products=[]
for Product in ProductList:
products.append({"name": Product.name, "description": Product.description, "price": Product.price})
return JsonResponse(products)
The index.html page:
<!DOCTYPE html>
<html>
<body>
<div>
<h2 id="title">Create product</h2>
<input id="name">Name</input>
<br>
<input id="description">Description</input>
<br>
<input id="price">Price</input>
<br>
<button id="add-product">ADD PRODUCT</button>
</div>
<div id="productList">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('add-product').onclick = function(){
sendData();
getData();
}
function sendData(){
var order = {
name: document.getElementById('name').value,
description: document.getElementById('description').value,
price: document.getElementById('price').value
};
$.ajax({
type: "POST",
url: 'create/product',
data: order,
success: function(newProduct){
console.log("success"),
$('#name').val(""),
$('#description').val(""),
$('#price').val("")
}
});
};
function getData(){
$.ajax({
url: 'view/product',
dataType: 'json',
type: 'GET',
success: function(data){
$.each(data.Product, function(index, element){
$('body').append($('productList', {
text: element.name
}));
});
}
});
}
</script>
</html>
And the urls.py file:
from django.contrib import admin
from django.urls import path
from products import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('create/product', views.createProduct),
path('view/product', views.viewProduct)
]
So far, adding a product in is fine and causes no issues. However, after writing the getData() method and including it, this part dosen't work and returns the following error:
File "C:\Users\install\Documents\tutorial\products\views.py", line 29, in viewProduct
ProductList = Product.objects.all()
UnboundLocalError: local variable 'Product' referenced before assignment
I'm confused by this error as I'm not assigning Product anywhere else in this file so not sure why it's returning this error. When I do this same assignment in the Shell, it doesn't have a problem with it and returns all the objects. Can someone help me resolve this? Thanks.
The problem is here:
def viewProduct(request):
if request.method == 'GET':
ProductList = Product.objects.all()
products=[]
for Product in ProductList: # <= This is where cause the problem
products.append({"name": Product.name, "description": Product.description, "price": Product.price})
return JsonResponse(products)
You have to change for Product in ProductList to Something else like for _Product in ProductList
Try this one:
def viewProduct(request):
if request.method == 'GET':
ProductList = Product.objects.all()
products=[]
for prod in ProductList:
products.append({"name": prod.name, "description": prod.description, "price": prod.price})
return JsonResponse(products)

Unable to Render Django Template using Method

I created a function called getData in effort to cut down 4 nested "if" statement inside my userInfo method. The result was devastating. I'm being humiliated by the fact that the page didn't proceed to my successful.html template. If I move everything inside getData method back to the userInfo function, everything return to normal. Is there a trick to making it work so I can restore my shame?
views.py
def userInfo (request):
# Set maximum to avoid default of 1000 forms.
UserFormSet = formset_factory (UserForm, formset = BaseUserFormSet, extra = 2, max_num = 5)
if request.method == 'POST':
formset = UserFormSet (request.POST)
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data
getData (request, data, location) # ====> Created a function to cut down nested if statement
else:
formset = UserFormSet ()
...
def getData (request, data, location):
validUser = []
for form in data:
username = form.get ('user_name')
userID = form.get ('user_ID')
if username and userID:
n = register (username, userID, location)
if n.checkDataBase ():
validUser.append (username)
if validUser:
context = {'validUser': validUser}
return render (request, 'userform/success.html', context)
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Successfully Added</title>
</head>
<body>
<h1>User Information:</h1>
<ul>
{% for user in validUser %}
<li>{{ user }}</li>
{% endfor %}
</ul>
Add more users
</body>
</html>
Does it work if you change your getData() to:
if validUser:
context = {'validUser': validUser}
return request, 'userform/success.html', context
and your userInfo() to:
if formset.is_valid ():
location = request.POST ['site']
data = formset.cleaned_data
request, template, context = getData (request, data, location) # ====> Created a function to cut down nested if statement
return render (request, template, context)
try
return getData (request, data, location)
(add return statement).

Categories

Resources