I want to show registered users/company name list to template in django. i am new in working with django forms.
I had registered successfully company by using template now i want to show all the company name which has been registered.
my models.py
class Company(models.Model):
company_id=models.IntegerField(default=0,primary_key=True)
company_name=models.CharField(max_length=255,blank=True,null=True)
company_email=models.EmailField(max_length=255,blank=True,null=True)
is_active=models.BooleanField(default=False)
last_login=models.DateTimeField(default=datetime.now,blank=True,null=True)
i am stuck that how can i show all information on template using forms. how can i make form for this and how can i get all companies name to show
I wrote this to get all companies name
def allcompanies(request):
context = RequestContext(request)
if request.method =='GET':
all_company=comoanyForm(request.GET)
data=Company.objects.all()
print "print all data",data
else:
pass
return render_to_response(
'allcompany.html',
{ },
context_instance=RequestContext(request))
i get values in data but did not showing on template.
You should not be using render_to_response - it is likely to be depreciated in the future.
You should be using render.
from django.shortcuts import render
return render(request, 'allcompany.html', {'data': data,})
then within your template you should have something like:
{% for company in data %}
{{company.company_name}}
{% endfor %}
You should do the django tutorial (or refer to it) if you haven't already, these are simple concepts.
Related
I'm currently just learning Django and I'm doing electronic grade book. I have tried everything, have read all the documentation, but nothing helps. It seems I miss a simple logic somewhere. I need to make two pages:
The first one "teacher_interface" is a simple inteface for the teacher with just one drop-down list, teacher chooses the necessary class (i.e 1C, 2B, 4C) and the button "Students", which should somehow take the chosen class from drop-down list input and redirect to the second page "class_students".
The second "class_students" is alike the "teacher_interface", but with the table of students of the chosen class.
I have the One-to-many relation between classes Student and Class:
Firstly, I tried redirecting from "teacher_interface" to "class_students", using in template:
{% url "name" %}
Parts of code: 1) models.py https://dpaste.org/eqxm 2) urls.py https://dpaste.org/eUEO 3) views.py https://dpaste.org/ap8D#L 4) template teacher_interface.html https://dpaste.org/v4m9 5) template class_students.html https://dpaste.org/0gXK
But it shows me: Reverse for 'class_students' with no arguments not found. 1 pattern(s) tried: ['school/teacher/(?P<class_id>[0-9]+)/class/$']
I tried everything, but nothing helped, this and the similar: Django - getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %} I understood maybe this two options of redirect will not work in my case:
{% url 'class_students' class.id %}
{% url 'class_students' class_id %}
I also don't know if it's possible to do on the same page.
So I decided to redirect using redirect from django.shortcuts. I changed my teacher_interface view, so that it took the id of the chosen by the teacher class if request method is POST and redirected. I also made this change in my template "teacher_interface.html":
from
action="{% url 'class_students' %}"
to
action=""
Changed view:
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
class_id = None
if request.method == "POST":
class_id = Class.objects.get("id")
return redirect("class_students", class_id)
context = {
"class_queryset": class_queryset,
"class_id": class_id,
}
return render(request, "teacher_interface.html", context)
But when I choose the class and click the "Students" button, it shows me: Cannot resolve keyword 'i' into field. Choices are: class_number, curriculum, discipline, group, id, student, task, type_of_class, type_of_class_id. Id is certainly is a key, but it tries to resolve only "i".
I tried/read everything here, but nothing works.
I even wrote the default like this:
class_id = Class.objects.get("id", "default")
I am sure I just don't understand properly how to get teacher's choice, pass it to another or the same function and redirect, saving this information. I will be really grateful for you help, even if you just advise what I can read to figure it out.
Ok, you are missing some basic conpects.
on your views.py
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
context = {
"class_queryset": class_queryset,
}
return render(request, "teacher_interface.html", context)
this is correct, you will pass you query to your template
on your template change some things to look like this:
<form method="POST" >{% csrf_token %}
<select name="input1">
{% for class in class_queryset %}
<option value="{{ class.id }}">{{ class }}</option>
{% endfor %}
</select>
<input type="submit" value="Students"/>
</form>
then you need to change your teacher_interface view:
You need to import redirect on your views.py
def teacher_interface(request):
class_queryset = Class.objects.order_by("class_number", "group")
context = {
"class_queryset": class_queryset,
}
if request.method == 'POST':
class_id = request.POST.get('input1') # I'm not sure if this will get the {{class.id}} value, if don't, print(request.POST.get) and check how to get the value
return redirect('class_students', class_id=class_id) # will make a get request on the class_students view
return render(request, "teacher_interface.html", context)
def class_students(request, class_id):
# the parameter need to be 'class_id' because this is what you put on your urls '<int:class_id>', if possible, remove that /class.
# ADD CLASS ID AS PARAMETER, THAT WILL ENABLE YOU TO ACESS AN SPECIFIC CLASS
# Import get_object_or_404 (google it and you will find easily)
class = get_object_or_404(Class, pk=class_id) # this avoid internal server error.
# pass your class on the context
return render(request, "class_students.html")
I have a subscribe form view which displays to a subscribe page, and I also want to display that same form in the home page, I tried using {% include 'accounts/subscribe.html' %} and tried also {% extends 'accounts/subscribe.html' %}in the home page (a recommendation from a similar question but not the same). How can I please go about this ?
view that leads to the subscribe.html
def subscribe(request):
if request.method == 'POST':
subscribe_form = EmailListForm(request.POST)
if subscribe_form.is_valid():
subscribe_form = subscribe_form.save()
return render(request, 'accounts/subscribe_done.html', {'name': subscribe_form.name})
else:
subscribe_form = EmailListForm()
return render(request, 'accounts/subscribe.html', {'sub_form': subscribe_form})
AFAIK the way to do that would be to either copy the above code to the home view function or extract a method that gets a request and returns the desired form object. Either way, you pass a form object to the home template just as you would on the subscribe page.
If you want to render the same form to another page (view), you can just add that form to the context of the view, like you do on the subscribe page. The homepage view would look like:
def home_page_view(request):
if request.method == 'POST':
subscribe_form = EmailListForm(request.POST)
if subscribe_form.is_valid():
subscribe_form = subscribe_form.save()
return render(request, 'accounts/subscribe_done.html', {'name': subscribe_form.name})
else:
context = {
'section': 'home',
'posts': Post.published.all().order_by('-publish')[:5],
'subscribe_form': EmailListForm()
}
return render(request, 'pages/page/home.html', context=context)
Does using the {% extends 'xyz.html' %} work? I usually use that to extend html templates.
I know this question was asked before, but none worked for me. I have this code that I want it to be executed when a button is clicked and a message is passed
import time
from sinchsms import SinchSMS
number = '+yourmobilenumber'
message = 'I love SMS!'
client = SinchSMS(your_app_key, your_app_secret)
print("Sending '%s' to %s" % (message, number))
response = client.send_message(number, message)
message_id = response['messageId']
response = client.check_status(message_id)
while response['status'] != 'Successful':
print(response['status'])
time.sleep(1)
response = client.check_status(message_id)
print(response['status'])
Basically, what I need is to add an input in a template "HTML File", this input get passed to the message variable in the code above, same with the number. I can easily do that with instances, but how can the below get executed when a button is clicked from the form in the template?
I'm kinda newbie in Django and still finding my way
Here is the tutorial that explains how to make the python file, but execute it from the shell, not a django application.
I hope I was clear describing my problem and any help would be appreciated!
All you need is a form with a message field. In a view, you want to show that form and when the user press submit, you want to execute your script.
Here is some pseudo-code:
urls.py
url('^my-page/' my_views.my_view, name='my-page'),
forms.py
SmsForm(forms.Form):
message = fields.CharField(...)
my_views.py
def my_view(request):
form = SmsForm(data=request.POST or None)
if request.method == 'POST':
if form.is_valid():
send_sms(form.cleaned_data['message']) # do this last
messages.success(request, "Success")
return HttpResponseRedirect(request.path)
else:
messages.warning(request, "Failure")
return render(request, 'my_template.html', {'form': form})
Check the Django documentation about urls, views, forms and messages and proceed step by step:
get the page to load
get the form to load
get the form submission to work and simply show "Success" or "Failure"
finally, write the send_sms function (you've almost done it)
Lets start from the dust cloud.
What you are asking is mostly about how the web pages work. You need to know how to pass parameters using HTML. There are lots of ways to do it. But with django there is a pattern.
You need a url, and a view to catch any requests. Then you need to create a template and a form inside it. With this form you could create some requests to send data to your view.
To create you need to edit urls.py inside your project add an url:
urls.py
from django.conf.urls import url
from my_app.views import my_view
urlpatterns = [
...
url(r'^my_url$', my_view, name='my_view')
...
]
For more about urls please look at URL dispatcher page at documentation.
Then create your view inside your app which is my_app in my example. Edit my_app/views.py
my_app/views.py
from django.http import HttpResponse
def my_view(request):
return HttpResponse('IT WORKS!')
This way you get a working view which could be accessed with path /my_url. If you run ./manage.py runserver you could access your view from http://localhost:8000/my_url.
To create a form you need to create a template. By default django searches app directories for templates. Create a templates directory in your app, in our case my_app/templates and create an HTML file inside. For example my_app/templates/my_form.html. But i advice to create one more directory inside templates directory. my_app/templates/my_app/my_form.html. This will prevent template conflicts. You can check Templates page at documentation for more.
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="/my_url" method="POST">
{% csrf_token %}
<input type="text" name="number">
<input type="text" name="message">
<input type="submit" value="Run My Code">
</form>
</body>
</html>
This is the one of the ways of creating your form. But I do not recommend it. I will make it prettier. But first lets "Make it work", edit your views.py:
csrf_token is a django builtin template tag, to put CSRF token into your form. By default django requires CSRF tokens at every post
request.
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
def my_view(request):
if request.method == 'GET':
return render('my_app/my_form.html')
elif request.method == 'POST':
# get post parameters or None as default value
number = request.POST.get('number', None)
message = request.POST.get('message', None)
# check if parameters are None or not
if number is None or message is None:
return HttpResponse('Number and Message should be passed')
# your code goes here
...
return HttpResponse('Your code result')
Till this point the purpose of this answer was "Making it work". Lets convert it nice and clean. First of all we would create Form. Forms are like models, which helps you create forms as objects. It also handles form validations. Forms are saved inside forms directory generally. Create my_app/forms.py and edit it:
my_app/forms.py
from django import forms
class MyForm(forms.Form):
number = forms.CharField(max_length=15, required=True)
message = forms.CharField(max_length=160, required=True)
Put your form inside your template:
my_app/templates/my_app/my_form.html
<html>
<body>
<form action="{% url 'my_view' %}" method="POST">
{% csrf_token %}
{{ form }}
</form>
</body>
</html>
Besides the form, the action of the HTML form tag is also changed.
url template tag is used to get url form url name specified in urls.py.
Instead of url tag, {{ request.path }} could have been used.
Create a form instance and pass it to the template rendering:
my_app/views.py
from django.http import HttpResponse
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'GET':
form = MyForm()
return render('my_app/my_form.html', {'form': form})
elif request.method == 'POST':
form = MyForm(request.POST)
# check if for is not valid
if not form.is_valid():
# return same template with the form
# form will show errors on it.
return render('my_app/my_form.html', {'form': form})
# your code goes here
...
return HttpResponse('Your code result')
You can use class based vies to write your view, but it's not necessary. I hope it helps.
You can create a view that takes up query parameters from the url and use it for further implementation. Then you can create a link/button in the html template which can redirect you to that url. For example:
in urls.py:
url(r'^run_a/(?P<msg>\w{0,25})/(?P<num>\w{0,25})/$', yourcode, name='get_msg'),
in template:
submit
in views.py:
def get_msg(request,msg,num):
message=msg
number=num
#rest of the code
Hope this helps :)
I've written a validation that checks to make sure a certain number of images are uploaded before the user can move on to another view. I know that the validation works, because I have successfully redirected them back to the upload page if they don't have enough images and to the preview page if they do.
CODE
#login_required
def preview_website(request, slug):
student = Student.objects.get(slug=slug)
if student.studentimage_set.filter(image_type="portrait").exists() and
student.studentimage_set.filter(image_type="interest1").exists() and
student.studentimage_set.filter(image_type="interest2").exists() and
student.studentimage_set.filter(image_type="interest3").exists():
return render(request, 'students/preview_website.html', {
'student': student,
})
else:
return redirect('upload_student_image', slug=student.slug)
The issue I'm having now is the notification of the error. I would like to let them know that they need to add more images in order to move forward. Is there a way, through views.py, to print a notification at the top of the template? (I know it is more standard to use validation in the forms or models, but this is a special case.)
I've tried the following, but I get an error page with no clean way back to the image upload page:
else:
raise ValidationError("Please make sure you have uploaded 4 images!")
I also tried the following, but I didn't see anything printed on the template page:
else:
msg = "Please make sure you have uploaded 4 images!"
I've already read through: 17105947, but the solution didn't work for me.
Any ideas? I'm pretty new to programming and Django, so I hope this is just a small oversight on my part and a relatively easy fix!
You can add the error message in your template behind an if scope.
In your view:
#login_required
def preview_website(request, slug):
student = Student.objects.get(slug=slug)
if student.studentimage_set.filter(image_type="portrait").exists() and
student.studentimage_set.filter(image_type="interest1").exists() and
student.studentimage_set.filter(image_type="interest2").exists() and
student.studentimage_set.filter(image_type="interest3").exists():
return render(request, 'students/preview_website.html', {
'student': student})
else:
error_message = "Please make sure you have uploaded 4 images!"
return render(request, 'students/preview_website.html', {
'student': student, 'error_message': error_message})
Add this to the top of your template
{% if error_message %}
<p>{{ error_message }}</p>
{% endif %}
You can do it by doing
length(request.FILES)
in view and if length is less than what you want you can return to upload html
return render_to_response('upload.html',{'error':error},context_instance=RequestContext(request))
In html page use following style you can show error
{% if error %}
{{ error }}
{% endif%}
this is probably a question for absolute beginners since i'm fairly new to progrmaming. I've searched for couple of hours for an adequate solution, i don't know what else to do.
Following problem. I want to have a view that displays. e.g. the 5 latest entries & 5 newest to my database (just an example)
#views.py
import core.models as coremodels
class LandingView(TemplateView):
template_name = "base/index.html"
def index_filtered(request):
last_ones = coremodels.Startup.objects.all().order_by('-id')[:5]
first_ones = coremodels.Startup.objects.all().order_by('id')[:5]
return render_to_response("base/index.html",
{'last_ones': last_ones, 'first_ones' : first_ones})
Index.html shows the HTML content but not the content of the loop
#index.html
<div class="col-md-6">
<p> Chosen Items negative:</p>
{% for startup in last_ones %}
<li><p>{{ startup.title }}</p></li>
{% endfor %}
</div>
<div class="col-md-6">
<p> Chosen Items positive:</p>
{% for startup in first_ones %}
<li><p>{{ startup.title }}</p></li>
{% endfor %}
Here my problem:
How can I get the for loop to render the specific content?
I think Django show render_to_response in template comes very close to my problem, but i don't see a valid solution there.
Thank you for your help.
Chris
--
I edited my code and problem description based on the solutions provided in this thread
the call render_to_response("base/showlatest.html"... renders base/showlatest.html, not index.html.
The view responsible for rendering index.html should pass all data (last_ones and first_ones) to it.
Once you have included the template into index.html
{% include /base/showlatest.html %}
Change the view above (or create a new one or modify the existing, changing urls.py accordingly) to pass the data to it
return render_to_response("index.html",
{'last_ones': last_ones, 'first_ones' : first_ones})
The concept is that the view renders a certain template (index.html), which becomes the html page returned to the client browser.
That one is the template that should receive a certain context (data), so that it can include other reusable pieces (e.g. showlatest.html) and render them correctly.
The include command just copies the content of the specified template (showlatest.html) within the present one (index.html), as if it were typed in and part of it.
So you need to call render_to_response and pass it your data (last_ones and first_ones) in every view that is responsible for rendering a template that includes showlatest.html
Sorry for the twisted wording, some things are easier done than explained.
:)
UPDATE
Your last edit clarified you are using CBV's (Class Based Views).
Then your view should be something along the line:
class LandingView(TemplateView):
template_name = "base/index.html"
def get_context_data(self, **kwargs):
context = super(LandingView, self).get_context_data(**kwargs)
context['last_ones'] = coremodels.Startup.objects.all().order_by('-id')[:5]
context['first_ones'] = coremodels.Startup.objects.all().order_by('id')[:5]
return context
Note: personally I would avoid relying on the id set by the DB to order the records.
Instead, if you can alter the model, add a field to mark when it was created. For example
class Startup(models.Model):
...
created_on = models.DateTimeField(auto_now_add=True, editable=False)
then in your view the query can become
def get_context_data(self, **kwargs):
context = super(LandingView, self).get_context_data(**kwargs)
qs = coremodels.Startup.objects.all().order_by('created_on')
context['first_ones'] = qs[:5]
context['last_ones'] = qs[-5:]
return context