I am working on a studentresult website in Python and Django. Now I want to ask to the database to give me the names of the groups that are in the database. Using the standard db.sqlite3 database from django. In the Dropdown menu I get three white bars because I have three groups now. When I the Class DisplayGroups to id = Models.IntegerField(id, flat=True) change return.self.group_name to return self.id then the dropdownlist shows me the ID that the group has. But how can I show the name of the group. Tried a lot:
Changed to group in the model
Changed to groupname in the model
Changed a few of the commands in the views.py
Made a new database item Groepen and changed query to that.
views.py
from django.shortcuts import render, redirect
from .models import DisplayGroups, DisplayUsername
from django.contrib.auth.models import User, Group
def index(request):
response = redirect('/login')
return response
def home(response):
return render(response, "home/home.html")
def bekijk(request):
DisplayGroup = Group.objects.all()
print(DisplayGroup)
DisplayNames = User.objects.all()
print(DisplayNames)
return render(request, "home/bekijk.html", {"DisplayGroups": DisplayGroup,"DisplayUsername":DisplayNames})
models.py
from django.db import models
# Create your models here.
class DisplayGroups(models.Model):
group_name = models.CharField(max_length=200)
def __str__(self):
return self.group_name
class DisplayUsername(models.Model):
username = models.CharField(max_length=100)
def __str__(self):
return self.username
The html page
{% extends 'home/base.html' %}
{% block title %}Cijfers studenten{% endblock %}
{% block javascript %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
var $productvar=$("#groupdd1");
$itemvar=$("#userdd1");
$options=$itemvar.find('option');
$productvar.on('change', function()
{
$itemvar.html($options.filter('[value="'+this.value+'"]'))
}).trigger('change');
});
</script>
{% endblock %}
{% block content %}
<h1>Studentresultaten</h1>
<select id="groupdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayGroups %}
<option>{{result.group_name}}</option>
{% endfor %}
</select>
<select id="userdd1">
<option disabled="true" selected>-- Select Fruit --</option>
{% for result in DisplayUsername %}
<option>{{result.username}}</option>
{% endfor %}
</select>
{% endblock %}
The piece of jquery is for later, because I want to make a dependant dropdown menu. Hope you guys can help me. Thanks in advance!
#WilliamVanOnsem is right the model from where you are filtering is Group which do not have group_name as a field. Here's what you can do.
In views.py
DisplayGroup = DisplayGroups.objects.all()
DisplayNames = DisplayName.objects.all()
Now in HTML template you can access group_name and result.username. The User model has username field so result.username did not show an empty text
Related
I am looking to create a dropdown in a template where the values of the dropdown come from a field (reference) within my Orders model in models.py. I understand creating a dropdown where the values are set statically, but since I am looking to populate with values stored in the DB, I'm unsure of where to start.
I've created the model and attempted playing around with views.py, forms.py and templates. I am able to get each of the order numbers to display but not in a dropdown and I am struggling with how to write my template.
models.py
from django.db import models
class Orders(models.Model):
reference = models.CharField(max_length=50, blank=False)
ultimate_consignee = models.CharField(max_length=500)
ship_to = models.CharField(max_length=500)
def _str_(self):
return self.reference
forms.py
from django import forms
from .models import *
def references():
list_of_references = []
querySet = Orders.objects.all()
for orders in querySet:
list_of_references.append(orders.reference)
return list_of_references
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()])
views.py
def reference_view(request):
if request.method == "POST":
form = references(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = references()
return render(request, 'proforma_select.html', {'form': form})
proforma_select.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label"> {{ field.label }}</label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button">Add Order</button>
</form>
</div>
{% endblock %}
All I get when I render the template is each of the reference #s listed out but NOT within a dropdown. This leads me to believe my problem is mainly with the template, but I'm unsure as I am new to using Django.
Are you using Materialize CSS? If yes, then Django forms renders dropdowns differently from how Materialize expects them. So you will want to override the form widget. You can do something like so:
forms.py:
class DropDownMenuReferences(forms.Form):
reference = forms.ChoiceField(choices=[(x) for x in references()],
widget=forms.Select(choices=[(x) for x in references()], attrs={'class':
'browser-default'}))
This overrides the parameters passed into html. You can also pass any name tags in the attrs too.
The issue:
https://github.com/Dogfalo/materialize/issues/4904
Could anyone correct my code?
Background:
The user, once on the 'start.html' template, will enter their name and press submit. Then on the next template, 'game.html', there should be a paragraph tab that contains that users name.
Problem:
I must be writting something incorrectly because the user's name does not render on the 'game.html' template. Or, I could also be storing it wrong. Any suggestions or corrections would be very appreciated!
models.py - fp
from django.db import models
class Player(models.Model):
#first player name
fp_name = models.CharField(max_length=30, default='')
forms.py - I'm not sure if this is actually needed...?
from django import forms
class PlayerInfo(forms.Form):
fp_name = forms.CharField(max_length=30, label='First player name')
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, render_to_response
import os
from .forms import PlayerInfo
from .models import Player
def index(request):
return render(request, 'index.html')
def start(request):
if request.method == 'Post':
form = PlayerInfo(request.POST)
if form.is_valid():
obj = Player()
obj.fp_name = form.cleaned_data['fp_name']
return HttpResponseRedirect('/')
else:
form = PlayerInfo()
return render(request, 'start.html')
def game(request):
return render_to_response('game.html', {'obj': Player.objects.all()})
start.html - Meant to submit player one's name
{% extends 'base.html' %}
{% block botRow %}
<form method="post">
{% csrf_token %}
<label for="fp_name">First Player Name</label>
<input id="fp_name" type="text" name="fp_name" maxlength="30" required />
<input type="submit" value="Submit" />
</form>
{% endblock %}
game.html - Meant to render the player one's name
{% extends 'base.html' %}
{% block midRow %}
<p>{{ obj.fp_name }}</p>
{% endblock %}
in your game.html the obj is query set of all Users, so you should walk through the list, look on block for in the docs:
{% extends 'base.html' %}
{% block midRow %}
{% for user in obj %}
<p>{{ user.fp_name }}</p>
{% endfor %}
{% endblock %}
Using User.objects.all() you are getting a Collection of all site's users. It isn't current user. So, the collection doesn't have parameter fp_name. Use request.user to get current logged in user.
Also, there is some redundancy in your code:
Django contains User class with ability to store First Name out of the box. So, you don't need to declare it at all. https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User
There is special class of forms - ModelForm. It helps you to map model's fields to form's fields as fast as possible. (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/)
There is special class of views - CreateView. It helps you to realize basic logic of model creating. (https://docs.djangoproject.com/en/1.11/ref/class-based-views/generic-editing/#django.views.generic.edit.CreateView)
Forms intended to save your time. So, in templates it's better to use built-in rendering engine of forms, than to declare their fields manually. (https://docs.djangoproject.com/en/1.11/topics/forms/#the-template)
If game.html is permitted only for registered users it's a good idea to use #login_required decorator to restrict access to this part of the site.
I have an application with a user follower system which I have been able to achieve but I try to retrieve individual user followers and following but I could not get it. Below is my code
View.py
def following(request):
query = Contact.objects.filter(request.user.following)
context = {
'query': query
}
template = 'following.html'
return render(request, template, context)
Models.py
class Contact(models.Model):
user_from = models.ForeignKey(User,related_name='rel_from_set')
user_to = models.ForeignKey(User,related_name='rel_to_set')
created = models.DateTimeField(auto_now_add=True,db_index=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return '{} follows {}'.format(self.user_from,self.user_to)
User.add_to_class('following',models.ManyToManyField('self', through=Contact,related_name='followers', symmetrical=False))
Template
{% load staticfiles %}
{% block content %}
<h2>following</h2>
<div id="action-list">
<h1>{{ results.get_full_name }}</h1>
</div>
{% endblock %}
Additional code would be added on request.
This could be solved two ways. First: your filter is not correct:
def following(request):
query = Contact.objects.filter(user_from=request.user)
context = {
'query': query
}
template = 'following.html'
return render(request, template, context)
Another solution with the reverse relation using the related_name
def following(request):
query = request.user.rel_from_set.all()
context = {
'query': query
}
template = 'following.html'
return render(request, template, context)
Works similar, of course, for the user_to field of Contact.
EDIT: Your template doesn't use the proper context variables you have defined in view following. So you'll need to tweak it a bit:
{% load staticfiles %}
{% block content %}
<h2>following</h2>
<div id="action-list">
{% for result in query %}
<h1>{{ result }}</h1>
{% endfor %}
</div>
{% endblock %}
I'm trying to create a drop-down list of member IDs for users to choose from. I created a form called SelectForm in forms.py:
from .models import Member
from django import forms
class MemberForm(forms.ModelForm):
class Meta:
model = Member
fields = '__all__'
class SelectForm(forms.Form):
memberid = forms.ModelChoiceField(queryset=Member.objects.values_list('member_id', flat=True))
With the view:
class SelectView(generic.ListView):
template_name = 'expcore/select_member.html'
model = Member
def select_member(request):
form = SelectForm()
if request.method == 'POST':
form = SelectForm(request.POST)
if form.is_valid():
return HttpResponseRedirect('/questions/')
else:
form = SelectForm()
return render(request, 'select_member.html', {'form': form})
Right now, all the HTML gives me is 'Member Selection: Please blablablabla' with a LIST of bullet points that correspond to the number of existing member IDs. However, the actual member IDs don't show up; furthermore, the whole thing is in a list format right now and not a drop-down menu, which I want.
select_member.html:
{% load staticfiles %}
<title>Member Selection</title>
<h1>Member Selection</h1>
Please select your Member ID from the drop-down menu.
<ul>
{% for member_id in object_list %}
<li><a href='/member/{{ member.name }}'></a></li>
{% empty %}
<li>None available.</li>
{% endfor %}
</ul>
I believe the form I created is supposed to generate a drop-down menu for me but I don't think I'm getting the view/HTML right. Can you guys help me out?
Also - member IDs is under the class Member in my models.py:
class Member(models.Model):
member_id = models.SlugField(max_length=10)
def __str__(self):
return self.name
Thank you.
Please take a look at this third party application: django-crispy-forms. It will make your life way easier.
In your template:
{% load staticfiles %}
<title>Member Selection</title>
<h1>Member Selection</h1>
Please select your Member ID from the drop-down menu.
<!-- Form -->
<form method="POST" action="your_view">
{{ form }}
</form
<ul>
{% for member_id in object_list %}
<li><a href='/member/{{ member.name }}'></a></li>
{% empty %}
<li>None available.</li>
{% endfor %}
</ul>
I have a Django app that contains info on schools and states. I want my template to display a list of schools per state and also the name of the state based on the state parameter in the URL. So if a user goes to example.com/vermont/ they will see a list of Vermont schools and a tag that says they're on the "Vermont" page. I can get the list of schools per state to work, but I can't figure out how to simply list the state name in the h1 tag.
Here is my models.py:
from django.db import models
class School(models.Model):
school_name = models.CharField(max_length=200)
location_state = models.CharField(max_length=20)
def __unicode__(self):
return self.school_name
Here is my views.py:
from django.views.generic import ListView
class StateListView(ListView):
model = School
template_name = 'state.html'
context_object_name = 'schools_by_state'
def get_queryset(self):
state_list = self.kwargs['location_state']
return School.objects.filter(location_state=state_list)
And here's my template for state.html:
{% extends 'base.html' %}
{% block content %}
<h1>{{school.location_state }}</h1> [THIS IS THE LINE THAT DOES NOT WORK]
{% for school in schools_by_state %}
<ul>
<li>{{ school.school_name }}</li>
</ul>
{% endfor %}
{% endblock content %}
What am I missing here?
The problem is that the school variable never enters the context. You are only setting the schools_by_state to the context.
To add some extra context you need to override the get_context_data method. This way you can add the location_state from the url parameter:
def get_context_data(self, **kwargs):
context = super(StateListView, self).get_context_data(**kwargs)
context.update({'state': self.kwargs['location_state']})
return context
Then you can use the {{ state }} instead of {{ school.location_state }} in your template.