I have created a Django form to get the data from user and search that given data in database models.
But i am not able to use the dropdown functionality correctly. I have used ModelChoiceField but I am getting it empty.
I have three fields(forms.py) which i am searching in the database.
models.py
class Release(models.Model):
number = models.CharField(max_length=50,unique=True)
notes = models.CharField(max_length=50)
changes = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.number)
class Metamodule(models.Model):
name = models.CharField(max_length=50,unique=True)
version = models.IntegerField(default=0)
release = models.ForeignKey(Release,related_name="num")
createdate = models.DateField(auto_now=True, null=True)
createdby = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
class Module(models.Model):
name = models.CharField(max_length=50,unique=True)
version = models.IntegerField(default=0)
metamodule = models.ForeignKey(Metamodule,related_name="metaname")
createdate = models.DateField(auto_now=True, null=True)
changes = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
forms.py
class ModuleForm(forms.Form):
release_num = forms.ModelChoiceField(queryset=Release.objects.all().values('number'),empty_label='Pick a Release')
metamodule_name = forms.CharField(max_length=50)
module_name = forms.CharField(max_length=50)
views.py
from django.shortcuts import render
from search.forms import ModuleForm
from django.http import HttpResponse
from search.models import Module,Metamodule,Release
def searchview(request):
if request.method == 'GET':
form = ModuleForm(request.GET)
if form.is_valid():
release_num = form.cleaned_data['release_num']
metamodule_name = form.cleaned_data['metamodule_name']
module_name = form.cleaned_data['module_name']
results = Module.objects.filter(metamodule__release__number=release_num).filter(metamodule__name=metamodule_name).filter(name=module_name)
return render(request,'search/search_result.html',{'form': form, 'results': results})
else:
form = ModuleForm()
return render(request, 'search/search_form.html',{'form': form})
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
{% if error %}
<p style="color: red;">Please submit a search term.</p>
{% endif %}
<form action="/search/" method="get">
<select name="release_num">
{% for release_num in release_num %}
<option value="{{ release_num.number }}">{{ release_num.number }}</option>
{% endfor %}
</select>
<p><label for="metamodule_name">Metamodule:</label>
<input type="text" name="metamodule_name">
<p><label for="module_name">Module:</label>
<input type="text" name="module_name">
<input type="submit" value="Search">
</form>
</body>
</html>
try in the search_form.html:
<form action="/search/" method="get">
{{ form.release_num }}
{{ form.metamodule_name }}
{{ form.module_name }}
Related
I am struggling with my code. I want to show data from a specific user on screen. When the second dropdown is selected with the user from a specific group, I want his records to be shown on screen. But what ever I try, the data stays the same from one user. In a later stadium I want to make an Else and say if there is no data, that there is no data of the person. Should I do something with a jquery, or is there an easier way to solve this?
The first dropdown is the group, the second dropdown the user.
models.py
from django.db import models
from django.contrib.auth.models import User
# 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
class CijferLijst(models.Model):
name = models.CharField(max_length=200, default='')
vak1 = models.CharField(max_length=200, default='')
cijfer1 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0')
vak2 = models.CharField(max_length=200, default='')
cijfer2 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0')
username = models.ForeignKey(User, on_delete=models.CASCADE, default='')
def __str__(self):
return '%s %s %s %s %s %s'%(self.name, self.vak1, self.cijfer1, self.vak2, self.cijfer2, self.username)
bekijk.html
{% 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 $select1 = $('#groupdd1'),
$select2 = $('#userdd1'),
$options = $select2.find('option');
$select1.on('change', function()
{
$select2.html($options.filter('[value="'+this.value+'"]'));
}).trigger('change');
});
</script>
{% endblock %}
{% block content %}
{% if user.is_staff %}
<h1>Studentresultaten</h1>
<select id="groupdd1">
<option disabled="true" selected>Kies een groep</option>
{% for result in DisplayGroups %}
<option>{{result}}</option>
{% endfor %}
</select>
<select id="userdd1">
<option disabled="true" selected>Kies een gebruiker</option>
{% for result in DisplayUsername %}
<option value="{{result.username}}">{{result}}</option>
{% endfor %}
</select>
{% endif %}
<br/>
{% for antwoord in CijferLijst %}
<h2>{{antwoord.name}}</h2>
<div class="container px-4">
<div class="row justify content-start gx-5">
<div class="col-5 border bg-light"><strong>Vaknaam</strong></div>
<div class="col-5 border bg-light"><strong>Cijfer</strong></div>
</div>
<div class="row gx-5 justify-content-start">
<div class="col-5 border bg-light">{{antwoord.vak1}}</div>
<div class="col-5 border bg-light">{{antwoord.cijfer1}}</div>
</div>
<div class="row gx-5 justify-content-start">
<div class="col-5 border bg-light">{{antwoord.vak2}}</div>
<div class="col-5 border bg-light">{{antwoord.cijfer2}}</div>
<div class="col-5 border bg-light">{{antwoord.username}}</div>
</div>
</div>
{% endfor %}
{% endblock %}
views.py
from django.shortcuts import render, redirect
from .models import DisplayGroups, DisplayUsername, CijferLijst
from .forms import Grades
from django.contrib.auth.models import User, Group
# Create your views here.
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)
Cijfer = CijferLijst.objects.all()
print(Cijfer)
return render(request, "home/bekijk.html",
{"DisplayGroups": DisplayGroup, "DisplayUsername": DisplayNames, "CijferLijst": Cijfer})
def cijfers(request):
if request.method == "POST":
form = Grades(request.POST)
if form.is_valid():
form.save()
print(form)
return redirect('gelukt')
else:
form = Grades()
return render(request, "home/cijfers.html", {"form":form})
def done(response):
return render(response, "home/gelukt.html")
forms.py
from django import forms
from .models import CijferLijst
from django.contrib.auth.models import User
class Grades(forms.ModelForm):
name = forms.CharField(max_length=200)
vak1 = forms.CharField(max_length=200)
cijfer1 = forms.DecimalField(max_digits=3, decimal_places=1)
vak2 = forms.CharField(max_length=200)
cijfer2 = forms.DecimalField(max_digits=3, decimal_places=1)
username = forms.ModelChoiceField(queryset=User.objects.all())
check = forms.BooleanField()
class Meta:
model = CijferLijst
fields = ['name', 'vak1', 'cijfer1', 'vak2', 'cijfer2', 'username']
Thanks in advance.
In my Django website, I'm trying to create a search bar on my homepage that returns results that are stored in two different models(Articles, Jobs)
Currently, I get an empty result set when I search using this code:
In models.py,
class Articles(models.Model):
objects = None
news_title = models.CharField(db_column="title", max_length=400)
news_url = models.URLField(db_column="link", max_length=400)
image_link = models.CharField(db_column="image", max_length=400)
published_date = models.CharField(db_column="published_date", max_length=400)
class Meta:
managed = False
db_table = "articles"
def __str__(self):
return self.news_title
class Jobs(models.Model):
objects = None
company = models.CharField(db_column='company', max_length=100)
job_title = models.CharField(db_column='job_title', max_length=300)
experience = models.CharField(db_column='experience', max_length=300)
edu_level = models.CharField(db_column='edu_level', max_length=50)
class Meta:
managed = False
db_table = "job_list"
def __str__(self):
return self.job_title
In views.py,
class SearchView(ListView):
template_name = 'blog/search_results.html'
def get_queryset(self):
request = self.request
query = request.GET.get('q', '')
articles_results = Articles.objects.filter(Q(news_title__icontains=query))
jobs_results = Jobs.objects.filter(Q(job_title__icontains=query))
context={
'articles':articles_results,
'jobs':jobs_results,
}
return render(request, 'blog/search_results.html', context)
In main_view.html, I'm using this code for creating a search bar:
<form action="{%url 'search_results' %}" method="get" values="{{request.GET.q}}" class="search-jobs-form">
<div class="row mb-5">
<input name="q" type="text" values="{{request.GET.q}}" placeholder="search">
</div>
<button type="submit">Search</button>
</form>
And in search_results.html,
{% block content %}
{% for job in jobs %}
<h5>{{job.job_title}}</h5>
<p>{{job.company}}</p>
{% endfor %}
{% for article in articles %}
<h5>{{article.news_title}}</h5>
<p>{{article.published_date}}</p>
{% endfor %}
{% endblock %}
I ended up not using class SearchView(ListView) in views.py and made it work
Here's the code that I used
#index.html Search Bar
<form method="get" class="search-jobs-form" action="{% url 'main_search'%}">
{% csrf_token %}
<input type="text" placeholder="Job title, Company..." name="search_query">
<button type="submit" class="btn btn-info btn-lg btn-block text-white btn-search">Search Job</button>
</form>
In views,
#views.py
def main_search(request):
q = request.GET['search_query']
articles = Articles.objects.filter(news_title__icontains=q)
jobs = Jobs.objects.filter(Q(job_title__icontains=q) | Q(company__icontains=q))
return render(request, "blog/main_search.html", {'articles':articles, 'jobs':jobs, 'page_name':'Search Results', 'q':q})
I'm trying to get a list of objects in Django from a model.
I just want to get the list of 'dht node' from the request user, but it shows nothing in the html file (as if the list was empty). The user that I'm using has 2 'dht nodes' and they're shown in the django admin.
I don't know what is wrong, because if I use the instruction "member.dht.create(...)" in the views function and a create a new 'dht node' like this, this is shown. Only 'dht nodes' that I enter by form do not show. Can be the form?
Thanks a lot, Here's my code:
Models.py
class Node(models.Model):
name = models.CharField(primary_key=True, null=False, max_length= 50)
description= models.CharField(default=None, null=False, max_length= 250)
topic=models.CharField(default=None, null=False, max_length= 50, unique=True)
def __unicode__(self):
return self.name
class dht(Node):
temp = models.IntegerField(default=None, null=True)
hum = models.IntegerField(default=None, null=True)
class UserProfile(User):
uid = models.CharField(default=None, null=False, max_length= 250)
dht = models.ManyToManyField(dht, blank=True)
def __unicode__(self):
return self.user.username
Views.py -dht list-
#login_required(login_url = '/web/login')
def listDhtSensor(request):
member = request.user.userprofile
list = member.dht.all()
return render(request, 'web/listDhtSensor.html', {'list':list})
Html -listDhtSensor.html-
{% block content %}
{% for dht in list %}
{{ dht.name }}
{{ dht.topic }}
{% endfor %}
{% endblock %}
Forms.py
class newDHTSensorForm(forms.ModelForm):
class Meta:
model = dht
field = ['name',
'description',
'topic',]
labels = {'name': 'Name' ,
'description': 'Description',
'topic': 'Topic',}
exclude = ['temp', 'hum']
Views.py -dht form-
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Html -newDhtSensor.html-
{% block content %}
<div class="boxReg">
<form method="post">
{% csrf_token %}
<h2>{{ form.name.errors.as_text }}</h2>
<p><label for="id_name">Name:</label> <input class="barraForm" type="text" name="name" maxlength="150" autofocus="" required="" id="id_name"></p>
<p><label for="id_description">Description:</label> <input class="barraForm" type="text" name="description" maxlength="150" id="id_description"></p>
<h2>{{ form.topic.errors.as_text }}</h2>
<p><label for="id_topic">Topic:</label> <input class="barraForm" type="text" name="topic" maxlength="254" id="id_topic"></p>
<div class="boxButtonReg">
<button class="buttonReg" type="submit">Save</button>
</div>
</form>
</div>
{% endblock %}
It shows nothing because you did not link you dht objects to that UserProfile, so if you later query for the dhts for that UserProfile, evidently the list is empty. You should add it to the dht relation, like:
#login_required(login_url = '/web/login')
def newDHTSensor(request):
if request.method == "POST":
form = newDHTSensorForm(request.POST)
if form.is_valid():
post = form.save()
request.user.userprofile.dht.add(post)
return redirect('/web/dhtDetail')
else:
form = newDHTSensorForm()
return render(request, 'web/newDhtSensor.html', {'form': form})
Note that you first need to save the post, so you should omit the commit=False aprameter.
I created a model and respective ModelForm, view and Template for it, but ModelForm does not save data to the model even though .save() function is used.
I have tried reviewing forms and views but I do not know what is wrong.I have posted the respective models, forms, views and templates in the question.
models.py:
class Centre(models.Model):
Location = (
('rashmi_heights', 'Rashmi Heights Centre'),
('Levana', 'Levana Centre')
)
name= models.CharField(max_length=50, blank=False, choices=Location, unique=True)
address = models.CharField(max_length =250)
contact = models.CharField(max_length=100, blank=False)
phone = PhoneField(blank=True, help_text='Contact phone number')
def __str__(self):
return self.name
forms.py:
class CentreForm(forms.ModelForm):
class Meta():
model = Centre
fields = '__all__'
views.py:
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
centre = forms.save(request.POST)
centre.save()
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
template:
<!DOCTYPE html>
{% extends 'NewApp/base.html' %}
{% load staticfiles %}
{% block body_block %}
<div class="jumbotron">
<h2>Fill details about your centre.</h2><br>
<h3> </h3>
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<a class="btn btn-primary" href="{% url 'NewApp:centreinfo' %}">Submit</a>
</form>
</div>
{% endblock %}
forms.py:
class CentreForm(forms.ModelForm):
class Meta: -> change here
model = Centre
fields = '__all__'
def centre(request):
forms = CentreForm()
if request.method == 'POST':
forms = CentreForm(request.POST)
if forms.is_valid():
forms.save(request.POST)
else:
forms = CentreForm()
return render(request,'NewApp/centreinfo.html',{'forms':forms})
html
<form method="post" enctype="multipart/form-data">
{{forms.as_p}}
{% csrf_token %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I created two classes: Client (attributes: name and sex) and Account (attributes: customer[fk], the payment status). I show the form from templates; When I click the link "Add Customer" it opens the form of creation, from what has in models.py, other words can only create a client to "name and sex," but not I can integrate in the same form payment situation.
models.py
from django.db import models
class Cliente(models.Model):
SEXO = (
('M', 'Masculino'),
('F','Feminino'),
)
nome = models.CharField("Nome do cliente", max_length=255)
sexo = models.CharField("Sexo", max_length=1, choices=SEXO)
def __unicode__(self):
return self.nome
class Meta:
verbose_name = 'Cliente'
verbose_name_plural = 'Clientes'
class Conta(models.Model):
STATUS_CONTA = (
('A', 'A Pagar'),
('P', 'Pago'),
)
cliente = models.ForeignKey(Cliente, related_name='conta')
situacao = models.CharField("Situação", max_length=50, choices=STATUS_CONTA)
class Meta:
verbose_name = 'Conta'
verbose_name_plural = 'Contas'
def __unicode__(self):
return self.cliente.nome
forms.py
from django.forms.models import ModelForm
from cadastro.models import Cliente, Conta
__author__ = 'Admin'
class ClienteForm(ModelForm):
class Meta:
model = Cliente
index.html
<html>
<body>
<a href='/adicionar_cliente/'>Adicionar cliente</a>
{% for cliente in clientes %}
{% for conta in cliente.conta.all %}
<p>Nome: {{cliente.nome}}</p>
<p>Sexo: {{cliente.get_sexo_display}} </p>
<p>Situação do pedido: {{conta.get_situacao_display}}</p>
{% endfor %}
<p><a href='/excluir/{{cliente.id}}/'>Excluir?</a></p>
<p><a href='/editar/{{cliente.id}}/'>Editar</a></p>
<hr>
{% empty %}
<h3>Não existe nenhum cliente.</h3>
{% endfor %}
</body>
</html>
form.html
<html>
<body>
<form action='/{{action}}/' method='post'>
{% csrf_token %}
<table>
{{form}}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
</html>
You can create two forms to accomplish this task.
forms.py
...
class ClienteForm(ModelForm):
class Meta:
model = Cliente
class ContaForm(ModelForm):
class Meta:
model = Conta
exclude = ("cliente") #exclude the cliente field from showing up in the form rendering.
form.html
<html>
<body>
<form action='/{{ action }}/' method='post'>
{% csrf_token %}
<table>
{{ form.as_table }} <!-- added as table which was missing from original post. -->
{{ form2.as_table }}
</table>
<input type='submit' value='Adicionar' />
</form>
</body>
views.py
...
def form(request):
if request.method == 'POST':
form = ClienteForm(request.POST)
form2 = ContaForm(request.POST)
if form.is_valid() and form2.is_valid():
client = form.save()
conta = form2.save(commit=False)
conta.cliente = client
contra.save()
else:
form = ClienteForm()
form2 = ContaForm()
return render_to_response('form.html', locals(), context_instance = RequestContext(request))