django model dropdown missing in html view - python

I'm writing a django app, and I'd like for users to be able to select a [team_number] from a dropdown menu, then when they hit submit be redirected to a page that renders out the database information associated with that selection. I'm using the redirect class View, but the problem I'm having is that there is no dropdown menu showing up to select [team_number] from on the html page team-stats.html.
views.py:
class TeamStatsView(View):
def get(self, request, *args, **kwargs):
return render(request, 'team-stats.html',
{'team_number': TeamStats()})
def post(self, request, *args, **kwargs):
team_number = TeamStats(request.POST, request.FILES)
if team_number.is_valid():
# do stuff & add to database
team_number.save()
team_number = TeamStats.objects.create()
# use my_file.pk or whatever attribute of FileField your id is
# based on
return HttpResponseRedirect('/team-stats/%i/' % team_number.pk)
return render(request, 'team-stats.html', {'team_number': team_number})
models.py:
class Team(models.Model):
team_number = models.IntegerField()
team_notes = models.CharField(max_length=150)
event_id = models.ForeignKey(
'Event', on_delete=models.CASCADE, unique=False)
def __unicode__(self):
return str(self.team_number)
class Meta:
db_table = 'teams'
app_label = 'frcstats'
forms.py:
class TeamStats(forms.ModelForm):
class Meta:
model = Team
fields = ['team_number']
team-stats.html:
<form method="post" action="">
{% csrf_token %} {{ TeamStatsView }}
<input type="submit" value="Submit" />
</form>
If there are any other files that I need to update into here to show what I'm trying to do, please let me know. Thanks

Try changing your view variable name to team_numbers and replacing your team-stats.html snippet with the following:
<form method="post" action="">
<select name="teams">
{% for team_number in team_numbers %}
<option value="{{ team_number }}">Team Num: {{ team_number }}</option>
{% endfor %}
</select>
</form>
Then update your view to:
class TeamStatsView(View):
def get(self, request, *args, **kwargs):
return render(request, 'team-stats.html',
{'team_numbers':Team.objects.values('team_number')})

You can use choices=NUMBERS
NUMBERS = (
('1','1'),
('2','2'),
('3','3'),
('4','4')
)
class Team(models.Model):
team_number = models.IntegerField(choices=NUMBERS )
team_notes = models.CharField(max_length=150)
event_id = models.ForeignKey(
'Event', on_delete=models.CASCADE, unique=False)
def __unicode__(self):
return str(self.team_number)
class Meta:
db_table = 'teams'
app_label = 'frcstats'

Your view variable is called team_number.
Try to change TeamStatsView into team_number:
<form method="post" action="">
{% csrf_token %} {{ team_number }}
<input type="submit" value="Submit" />
</form>

Related

Get values from Django data base

I need to get the data from a form in a Django database. The problem when I use .cleaned_data['name'] I am getting an attribute error
'SnippetForm' object has no attribute 'cleaned_data'.
when I tried passing through if old_form.is_valid(), the if is False.
With my code, I can get the HTML info, but I can not parser it with .clean_data.
Basically I don't want to create a regex and parse the html, I am looking for some Django Method that can help.
Html code got from Django:
<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="Ariel" maxlength="100" id="id_name"></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="email" name="email" value="as#onsemi.com" maxlength="254" id="id_email"></td></tr>
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" value="Test" maxlength="100" id="id_subject"></td></tr>
<tr><th><label for="id_body">Body:</label></th><td><textarea name="body" cols="40" rows="10" id="id_body">
This is a test</textarea></td></tr>
In my views.py
def data_detail (request, request_id):
data_detail_django = get_object_or_404(Snippet, pk=request_id)
if request.method == "POST": #Also, it is not going throu this if...
old_form = SnippetForm(request.POST, instance=data_detail_django)
else: #The old_form is the html output and is get it with this
old_form = SnippetForm(instance=data_detail_django)
if old_form.is_valid():
print(old_form.cleaned_data['name'])
return HttpResponse("contact view")
In my models
from django.db import models
# Create your models here.
class Snippet(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(blank=True, null=True)
subject = models.CharField(max_length=100, blank=True, null=True)
body = models.TextField(blank=True, null=True)
def __str__(self):
return self.name
in my form.py
from django import forms
from .models import Snippet
class SnippetForm(forms.ModelForm):
class Meta:
model = Snippet
fields = ('name', 'email','subject', 'body')
The solution was: Uning .objects.get(pk = vaule)
def data_detail (request, request_id):
data_dbs = Snippet.objects.get(pk= request_id)
data_out = {'data_dbs': data_dbs}
return render(request, 'form_app/detail.html', data_out )
and in the html to render:
{% extends 'form_app/base.html' %}
{% block main_content %}
{% if data_dbs %}
<p>Name: {{data_dbs.name}}</p>
<p>Email: {{data_dbs.email}}</p>
<p>Subject: {{data_dbs.subject}}</p>
<p>Body: {{data_dbs.body}}</p>
{% else %}
<p> No data</p>
{% endif %}
<a href = '/data'><b>See Form</b></a></li>
{% endblock %}

using models.manager to count the number of votes

I'm using models.manager to count the number of votes but I don't understand why the number of vote isn't showing off. the voting system works(checked with admin) but the manager isn't working.
models.py
class PostVoteCountManager(models.Manager):
def get_query_set(self):
return super(PostVoteCountManager, self).get_query_set.annotate(
votes=Count('vote')).order_by("-votes")
class Post(models.Model):
rank_score = models.FloatField(default=0.0)
with_votes = PostVoteCountManager()
class Vote(models.Model):
voter = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
def __str__(self):
return "%s voted %s" %(self.voter.username, self.post.title)
my views.py
class PostListView(ListView):
model = Post
template_name = 'community/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
#ordering = ['-date_posted']
queryset = Post.with_votes.all()
def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated:
voted = Vote.objects.filter(voter=self.request.user)
posts_in_page = [post.id for post in context["object_list"]]
voted = voted.filter(post_id__in=posts_in_page)
voted = voted.values_list('post_id', flat=True)
context["voted"] = voted
return context
In html I do
{% for post in posts %}
<form method="post" action="{% url 'vote' %}" class="vote_form">
<li> [{{ post.votes }}]
{{post}}
{% csrf_token %}
<input type="hidden" id="id_post" name="post" class="hidden_id" value="{{ post.pk }}" />
<input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
{% if not user.is_authenticated %}
<button disabled title="Please login to vote">+</button>
{% elif post.pk not in voted %}
<button>+</button>
{% else %}
<button>-</button>
{% endif %}
</form>
{% endform%}
You wrote the function as get_query_set, but the name is get_queryset [Django-doc]. Furthermore, you forgot to call the get_queryset(..) function here:
class PostVoteCountManager(models.Manager):
def get_queryset(self):
return super(PostVoteCountManager, self).get_queryset().annotate(
votes=Count('vote')).order_by("-votes")

Django: Form is not valid

I am currently struggling to get my form to work properly. I created the form manually (template.html) and I can see all the data when I call it with print(request.POST) (in views.py - checkout) however form.is_valid(): (in views.py - checkout) doesn't work. Means my form is not valid.
I think the issue is, that I created the form manually and combined it with a model form where I want after validating my data with form.valid() save it in. Can anyone of you guys help me with my problem, why it's not valid?
template.html
<form action="{% url 'checkout:reserve_ticket' %}" method="post">
{% csrf_token %}
{% for ticket in event.tickets.all %}
<p>
{{ ticket.name }} for {{ ticket.price_gross }} with quantity:
<input type="hidden" name="order_reference" value="123456af">
<input type="hidden" name="ticket" value="{{ ticket.id }}">
<input type="hidden" name="ticket_name" value="{{ ticket.name }}">
<input type="number" name="quantity" max="{{ ticket.event.organiser.max_quantity_per_ticket }}" placeholder="0">
</p>
{% endfor %}
<button type="submit" class="btn btn-primary">Continue</button>
</form>
models.py
class ReservedItem(models.Model):
order_reference = models.CharField(
max_length=10,
unique=True
)
ticket = models.ForeignKey(
Ticket,
on_delete=models.PROTECT,
related_name='reserved_tickets'
)
ticket_name = models.CharField(max_length=100)
quantity = models.IntegerField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
forms.py
class ReserveForm(forms.ModelForm):
class Meta:
model = ReservedItem
fields = ['order_reference', 'ticket', 'ticket_name', 'quantity']
views.py - events
# Create your views here.
class EventDetailView(DetailView):
context_object_name = 'event'
def get_object(self):
organiser = self.kwargs.get('organiser')
event = self.kwargs.get('event')
queryset = Event.objects.filter(organiser__slug=organiser)
return get_object_or_404(queryset, slug=event)
views.py - checkout
def reserve_ticket(request):
if request.method == 'POST':
form = ReserveForm(request.POST)
if form.is_valid():
print("Hello World")
return redirect("https://test.com")
else:
print("back to homepage")

Hidden fields, auto assign values in django

I am still a newbie on django and Python. This is also my first question. I am trying to create a hidden field and auto assign a value to the hidden field. It can be either in the views or in the templates. I have a field "kind" that needs to be hidden. Also I need to assign a value to it depending on different views/templates so it populates the database.
This is my class view:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form = forms.LeadForm()
fields = ['name','email','tel','kind']
This is my model form:
class LeadForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kind = models.Lead.kind
class Meta:
model = models.Lead
kind = forms.CharField(widget=forms.HiddenInput())
fields = ['name','email','tel','kind']
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="{{ form.kind.monthly }}" />
<input type="submit" name="" value="Submit" class="btn btn-info">
I have tried many options and spend 2 days using different solutions. But no matter what I do I can't seem to populate the kind field in the database.
I found the solution! Yeah! Please let me know if there is maybe a better or more correct solution!
This is my class View:
class Monthlypage(CreateView):
template_name = 'monthly.html'
model = models.Lead
form_class = forms.LeadForm
This is my model form:
class LeadForm(forms.ModelForm):
class Meta:
model = models.Lead
fields = ['name','email','tel','kind']
widgets = {
'kind':forms.HiddenInput()
}
This is my model:
class Lead(models.Model):
name = models.CharField(max_length=265)
email = models.EmailField(max_length=265)
tel = models.IntegerField()
kind = models.CharField(max_length=265)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('registrations')
This is my template:
<form class="" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="hidden" name="kind" value="monthly">
<input type="submit" name="" value="Submit" class="btn btn-info">
Finally after 2 days of struggling, I hope this can help someone else out!

django action with intermediate page keyerror

I'm newbie in django and I'm doing my first educational project. I would like make an action with an intermediate page, but I receive :
KeyError at /admin/students/student/ 'action'
Scenario:
User selects from "Actions" listbox , action called :
u'Перемістити у групу'
Presses Go
New page should appears with the list of students and listbox to select a group.
please explain where is my error. My code is listed below:
class UpdateGroupForm(forms.Form):
group = forms.ModelChoiceField(queryset=Group.objects.all().order_by('title'), required=False)
def update_group(modeladmin,request,queryset):
if 'change_group' in request.POST:
form=UpdateGroupForm(request.POST)
if form.is_valid():
group=form.cleaned_data['group']
updated_group=queryset.update(student_group=group)
counter=queryset.count()
modeladmin.message_user(request,u"У %s студентів було змненно групу на %s")%(counter,group)
return
if not form:
form= UpdateGroupForm()
return (request,'/students/change_group.html',{'students':queryset,'form':form,'title':u'Зміна групи'})
update_group.short_description=u'Перемістити у групу'
class StudenAdmin(admin.ModelAdmin):
action_form = UpdateGroupForm
actions = [update_group]
list_display = ['last_name','first_name' ,'ticket','student_group']
list_display_links = ['last_name','first_name']
list_editable = ['student_group']
ordering = ['last_name']
list_filter = ['student_group']
list_per_page = 10
search_fields = ['last_name','first_name' ,'ticket','notes']
def get_view_on_site_url(self, obj):
return reverse ('students_edit',kwargs={'pk':obj.id})
code of my page:
{% extends "admin/base_site.html" %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{{ form }}
<p>Групу буде змінено у таких студентів:</p>
<ul>{{ students|unordered_list }}</ul>
<input type="hidden" name="action" value="update_group" />
<input type="submit" name="change_group" value="Зберігти" />
</form>
{% endblock %}
and here is code of my models:
class Student (models.Model):
"""Student Model"""
class Meta (object):
verbose_name=u"Студент"
verbose_name_plural=u"Студенти"
first_name=models.CharField(max_length=256,blank=False,verbose_name=u"Ім'я")
last_name=models.CharField(max_length=256,blank=False,verbose_name=u"Прізвище")
middle_name=models.CharField(max_length=256,blank=True,verbose_name=u"По-батькові")
birthday=models.DateField(blank=False,verbose_name=u"Дата народження",null=True)
photo=models.ImageField(blank=True,verbose_name=u"Фото",null=True)
ticket=models.CharField(max_length=256,blank=False,verbose_name=u"Білет")
student_group=models.ForeignKey('Group',verbose_name=u"Група",blank=False,null=True,on_delete=models.PROTECT)
notes=models.TextField(blank=True,verbose_name=u"Додаткові нотатки")
def __unicode__(self):
return u"%s %s" % (self.first_name,self.last_name)
# post_delete signal deletes student photo
post_delete.connect(remove_photo,Student)
class Group (models.Model):
"""Group Model"""
class Meta(object):
verbose_name=u"Група"
verbose_name_plural=u"Групи"
title=models.CharField(max_length=256,blank=False,verbose_name=u"Назва")
leader=models.OneToOneField('Student',verbose_name=u"Староста",blank=True,null=True,on_delete=models.SET_NULL)
notes=models.TextField(blank=True,verbose_name=u"Додаткові нотатки")
def __unicode__(self):
if self.leader:
return u"%s(%s %s)"%(self.title,self.leader.first_name,self.leader.last_name)
else:
return u"%s"%(self.title)

Categories

Resources