Hello and thank you in advance.
I know this is total noob question, and I have searched in the various forum and read and re-read the documentation, so please be gentle.
I have a view:
#views.py
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect
from acme.acmetest.models import Player
from acme.acmetest.models import PickForm
def playerAdd(request, id=None):
form = PickForm(request.POST or None,
instance=id and Player.objects.get(id=id))
# Save new/edited pick
if request.method == 'POST' and form.is_valid():
form.save()
return HttpResponseRedirect('/draft/')
#return render_to_response('makepick.html', {'form':form})
return render(request, 'makepick.html', {'form':form})
def draftShow(request):
draft_list = ['1', 'hello', 'test', 'foo', 'bar']
#draft_list = Player.objects.all()
#return render_to_response('makepick.html', {'draft_list' :draft_list}, context_instance=RequestContext(request))
return render_to_response('makepick.html', {'draft_list' :draft_list})
I am trying to get it to render to a template .html page:
#makepick.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML lang="en">
<head>
<title>Pick</title>
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Draft Player"
</form><br /><br />
Your picks so far:<br />
{% for draft in draft_list %}
{{ draft.playernumber }}
{% endfor %}
</body>
</HTML>
Where playernumber is field in the model class "Player" in models.py.
#urls.py
from django.conf.urls.defaults import patterns, include, url
from acme.acmetest import views
urlpatterns = patterns('',
('^$', 'acme.acmetest.views.playerAdd'),
)
Thank you for your help!
dp
Well, it looks like your template is rendering fine. So you'll have to see if draft_list actually contained anything and what playernumber is for each object that was grabbed.
In the root directory of your project, run:
python manage.py shell
Now that you're in the shell, to test whether there are actually any Player objects in your database and see what the playernumber property of each object returns:
from acme.acmetest.models import Player
draft_list = Player.objects.all()
for draft in draft_list:
print draft.playernumber
Make sure that makepick.hmtl is in your apps templates directory, or in your TEMPLATE_DIR.
You can check in your view to verify that Player.objects.all() is actually returning something. Make sure playernumber is an actual property of the Player object.
Related
So my Django form is not rendering in the html.
all I'm able to see is the Get Rank text.
I'm not sure if it's because I don't have a model or maybe it's something wrong with my html?
If you need to see anything else let me know not sure what's wrong, I also tried just doing it all inside of the home function but then it doesn't render the html at all.
Side question - Also I only plan on grabbing the users name, and the tag outside their name ("JohnDoeNA#1") so I probably use a get method correct?
EDIT: Fixed the button not working now only thing not rendering is the form. (Mis-spelling)
Updated Code to be correct.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def index(response):
return render(response, "main/base.html")
def home(response):
form = SearchUser()
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-ee8fcdce-05c5-4ad4-b909-8efa722b1134')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': form,
'userid': userid,
# 'mmr': apidata['rank']
})
forms.py:
from django import forms
class SearchUser(forms.Form):
name = forms.CharField(label="Name", max_length=200)
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("home/", views.home, name="home")
]
home.html:
{% extends 'main/base.html'%}
{% block content %}
<h2>Valorant Ranked Checker</h2>
<form method="post" action="/home/">
{{form}}
<button type="submit", name="search">
Get rank
</button>
</form>
<p><strong>{{userid}} - {{mmr}}</strong></p>
{% endblock %}
base.html:
<!DOCTYPE html>
<head>
<title>Blue's Valorant Ranked Checker</title>
</head>
<body>
<div id="content", name="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
You have two main issues here:
You were rendering your base template as your root directory (base.html) and therefore Django's template inheritance wasn't working correctly. You'll want to render the child template (the one that includes extends) if you want template inheritance to work properly.
You need to pass your Django form (SearchUser) to the render function of the view
I recommend making these changes:
====================
Remove reference to the index view in your urls.py as we don't need it. Instead, use your home child template as your root view:
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path("", views.home, name="home")
]
====================
Remove the no longer needed index function from views.py. You'll also want to pass reference to your form (SearchForm) inside of Django's render shortcut function.
views.py:
from urllib import response
from django.shortcuts import render
from django.http import HttpResponse
import requests
from .forms import SearchUser
import json
# Create your views here.
def home(response):
data = requests.get(
'https://americas.api.riotgames.com/riot/account/v1/accounts/by-riot-id/ReallyBlue/NA1?api_key=RGAPI-APIKEY')
userid = data.json()['puuid']
return render(response, "main/home.html", {
'form': SearchUser(), # include reference to your form
'userid': userid,
# 'mmr': apidata['rank']
})
def search(response):
form = SearchUser()
return render(response, "main/home.html", {"form": form})
Your view function that renders the form and the form template must match. form also must be in your context.
Put the form in the home.html and change the home view like so:
def home(response):
form = SearchUser()
return render(response, "main/home.html", {'form': form})
I am trying to make a simple form in Django that accepts some file upload fields and a few float fields. However, when I run this in my browser, the is_valid() never gets triggered even when all forms are filled in. I have looked through the Django docs and have tried to recreate the examples as much as possible, but I can't figure out what is wrong. I know that the is_valid() is not true because the page does not redirect to another page when submit is pressed. Also, if I go into the admin page, no instances of MyModel are made.
Here is my code.
models.py:
from django.db import models
# Create your models here.
class MyModel(models.Model):
file1 = models.FileField()
file2 = models.FileField()
x = models.FloatField()
y = models.FloatField()
z = models.FloatField()
def __str__(self):
return self.file1
forms.py:
from django import forms
from django.forms import ModelForm
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = '__all__'
views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from .forms import MyForm
# Create your views here.
def index_view(request):
if request.method == 'POST':
form = MyForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect('some_page')
else:
form = DocumentsForm()
return render(request, 'index.html', {'form':form})
index.html:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Home Page!</h1>
<form method="POST" action="/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Submit">
</form>
</body>
</html>
My guess is it has to do with the fact that you haven't included enctype="multipart/form-data" in your <form> declaration in the HTML. It should look like this:
<form action="/" method="post" enctype="multipart/form-data" class="">
The multipart/form-data is necessary when uploading a file through forms.
Since you are sending both data and files, you need to specify the encoding of the form to:
<form enctype="multipart/form-data" method="POST" action="/">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="Submit">
</form>
I am building a registration form. Whenever a user fills the form and clicks the register button I want them to see the preview of their submissions. I am having problems with the arguments. Here goes my code:
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class Register(models.Model):
regChoice = (
('Self', 'Self'),
('Group', 'Group'),
('Corporate', 'Corporate'),
('Others', 'Others'),
)
name = models.CharField(max_length=50)
email = models.EmailField(max_length=254,null=True)
phoneNumber = PhoneNumberField(null=True)
idCard = models.ImageField(null=True)
regType = models.CharField(max_length=25, choices=regChoice,null=True)
ticketNo = models.IntegerField(default=1)
def __str__(self):
return self.name
forms.py
from django import forms
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import *
class RegisterForm(ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your full name...'}))
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your email...'}))
phoneNumber = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Your phone number...'}))
class Meta:
model = Register
fields = '__all__'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='home'),
path('preview.html/<str:pk>', views.preview, name="preview")
]
views.py
from django.shortcuts import render, redirect
from .models import *
from .forms import *
# Create your views here.
def index(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'event/index.html', context)
def preview(request, pk):
reg = Register.objects.get(id=pk)
prev = RegisterForm(instance=reg)
if request.method == 'POST':
form = RegisterForm(request.POST, instance=reg)
if form.is_valid():
form.save()
return redirect('/')
context = {'reg':reg, 'prev':prev}
return render(request, 'event/preview.html', context)
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Registration</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="{% static 'js/script.js' %}"></script>
</head>
<body>
<div class="mobile-screen">
<div class="header">
</div>
<div class="logo"></div>
<form id="login-form" method="POST" action="{% url 'preview' form.id %}" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.email}}
{{form.phoneNumber}}
<legend style="color: aliceblue;">Upload ID card: </legend>{{form.idCard}}
<div style="text-align: center; color: aliceblue;">Registration Type: {{form.regType}}</div>
{{form.ticketNo}}
<input class="btn btn-sm btn-primary" type="submit" value="Register" name="Register">
</form>
</div>
</body>
</html>
preview.html
Hello {{prev.name}},
your email is {{prev.email}}
your phone number is {{prev.phoneNumber}}
your idCard photo is {{prev.idCard.url}}
your registration type is {{prev.regType}}
your number of tickets is {{prev.ticketNo}}
The error I am having is:
NoReverseMatch at /
Reverse for 'preview' with arguments '('',)' not found. 1 pattern(s) tried: ['preview\.html/(?P[^/]+)$']
When someone reaches your index page and enters the form we need to
Submit the form as a POST request to index view
Save the form thereby creating a model in the DB
Redirect the user to preview view using the above id
To do that the code needs to be somewhat like this, I have not tested it, but you should get the idea.
from django.shortcuts import redirect
def index(request):
form = RegisterForm()
if request.method == 'POST':
form = RegisterForm(request.POST, request.FILES)
if form.is_valid():
instance = form.save()
return redirect('preview', pk=instance.id)
context = {'form':form}
return render(request, 'event/index.html', context)
Inside your index.html change
action="{% url 'preview' form.id %}"
to
action=""
as we want it to post to the INDEX view as that is where out POST handling logic is.
The index view then redirects to preview using the newly generated object.
Also as mentioned by #Snir in the other answer, having .html in URLS is not a standard practice. It would be better to simple make it something like:
path('preview/<str:pk>', views.preview, name="preview")
The URL patterns are regexes, so you'll have to escape special regex characters, like the dot. Try (add r) or remove the dot:
path(r'preview.html/<str:pk>', views.preview,
name="preview")
I'm newbie and trying to do something pretty basic after reading the Django Doc Project Documentation, but can't seem to figure it out. I'm getting a user's name with a POST and trying to GET it and display it on the same page. I'm getting an error: hello() missing 1 required positional argument: 'greeting_id'
I'm using Django 2 and wondering if it could be something with the routing? I'm not exactly sure as I'm very new to MVC and Django.
Any help in the right direction would be greatly appreciated.
Here's my code so far:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Greeting
# create hello view
def hello(request, greeting_id):
if request.method == 'POST':
if request.POST['firstname']:
greeting = models.Greeting()
greeting.firstname = request.POST['firstname']
greeting.save()
obj = models.Greeting.objects.get(pk=greeting_id)
context = {
'object': obj
}
return render(request, 'greetings/home.html', context)
return render(request, 'greetings/home.html')
Models.py
from django.db import models
# Create your models here.
class Greeting(models.Model):
firstname = models.CharField(max_length=100)
# returns post object in admin interface
def __str__(self):
return self.firstname
urls.py
from django.contrib import admin
from django.urls import path
from greetings import views #import greetings views into the url file
urlpatterns = [
path('admin/', admin.site.urls),
path('hello/', views.hello, name='hello'),
]
home.html
{% block content %}
<h2>Let's Say Hello!</h2>
<br/>
<br/>
<div>
<form method="POST" action="{% url 'hello' %}">
{% csrf_token %}
Enter your first name:
<br />
<input type="text" name="firstname" />
<br />
<br />
<input type="submit">
</form>
{{ object.firstname }}
</div>
{% endblock %}
Your view "hello" requires an parameter "greeting_id"
def hello(request, greeting_id):
These parameters are passed from the url routing to the view, for the view to work your url would have to look like this
path('hello/<int:greeting_id>/', views.hello, name='hello'),
Where is greeting_id supposed to be coming from?
Just quick info I'm a beginner in python and django.
Here is an issue:
I'm trying to create simple blog app with django, I've created all whats needed and I'm able to render one of my main pages however when I try to access posts page(to be able to view current posts) I receive the following error:
Request Method: GET
Request URL: http://localhost:8000/posts/
Django Version: 2.0.2
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post' not found. 'post' is not a valid view function or pattern name.
I'm not sure why I receive this error as I have posts view function written and accessible, here are my files:
my_blog/urls.py
"""Defines URL patterns for my_blog."""
from django.conf.urls import url
from . import views
#needed app name
app_name='my_blog'
urlpatterns=[
#Homepage
url(r'^$',views.home,name='home'),
# Show all posts.
url(r'^posts/$', views.posts, name='posts'),
models.py
from django.db import models
# Create your models here.
class BlogPost(models.Model):
"""Post that can be viewed"""
title=models.CharField(max_length=200)
text=models.TextField()
date_added=models.DateTimeField(auto_now_add=True)
def __str__(self):
"""Return a string representation of the model."""
if len(self.text)<50:
return self.text
else:
return self.text[:50] + "..."
views.py
from django.shortcuts import render
from .models import BlogPost
from django.http import HttpResponseRedirect
# Create your views here.
def home(request):
"""The home page for Learning Log"""
return render(request,'my_blog/home.html')
def posts (request):
"""Show all posts."""
posts=BlogPost.objects.order_by('date_added')
context={'posts':posts}
return render(request, 'my_blog/posts.html', context)
HTML pages:
home.html
{%extends "my_blog/base.html"%}
{%block content%}
<html>
<p align="center">Welcome to my Blog</p>
</body>
</html>
{%endblock content%}
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Blog</title>
</head>
<body bgcolor="#85C1E9">
<p>
Home -
Posts
</p>
{%block content%}{%endblock content%}
</body>
</html>
posts.html
{%extends "my_blog/base.html"%}
{%block content%}
<p>Posts</p>
<ul>
{%for post in posts%}
<li>{{post}} </li>
{%empty%}
<li>No posts have been added yet.</li>
{%endfor%}
</ul>
{%endblock content%}
Thanks in advance for assistance
In your template you have:
{% url 'my_blog:post' post.id %}
This gives an error because you have not yet defined a URL pattern in my_blog/urls.py with name="post".
The view name that you are looking up in your template does not match the name defined in your urls.py. You need to make
urls.py
url(r'^posts/$', views.posts, name='posts'),
and
posts.html
<li>{{post}} </li>
match by either adding an s in posts,html or remove the s in urls.py
Edit
Looking a little deeper... You need to define your detail view (post with a parameter) in views.py. And add a corresponding entry in urls.py Then undo the change I recommended earlier.
You should also consider renaming your views from posts and post to something like post_list and post_detail