"Key 'current' not found in 'InputForm'. Choices are: ." in Djangoforms - python

I have a model from which I am making a django form. my model have all the feild but form has not ? I don't know where is the error?
models.py:
from django.db import models
class flightInfo(models.Model):
airCode=models.CharField(max_length=20)
aircraft_departure=models.CharField(max_length=20)
departure_time=models.TimeField(auto_now=False, auto_now_add=False)
aircraft_destination=models.CharField(max_length=20)
arrivale_time=models.TimeField(auto_now=False, auto_now_add=False)
airCode2=models.CharField(max_length=20)
aircraft_departure2=models.CharField(max_length=20)
departure_time2=models.TimeField(auto_now=False, auto_now_add=False)
aircraft_destination2=models.CharField(max_length=20)
arrivale_time2=models.TimeField(auto_now=False, auto_now_add=False)
airCode3=models.CharField(max_length=20)
aircraft_departure3=models.CharField(max_length=20)
departure_time3=models.TimeField(auto_now=False, auto_now_add=False)
aircraft_destination3=models.CharField(max_length=20)
arrivale_time3=models.TimeField(auto_now=False, auto_now_add=False)
start_date=models.DateField()
end_date=models.DateField()
current =models.DateField()
day1=models.BooleanField(default=False)
day2=models.BooleanField(default=False)
day3=models.BooleanField(default=False)
day4=models.BooleanField(default=False)
day5=models.BooleanField(default=False)
day6=models.BooleanField(default=False)
day7=models.BooleanField(default=False)
def __str__(self):
return self.airCode
forms.py:
from django import forms
from . models import *
class InputForm(forms.Form):
class Meta:
model = flightInfo
fields = ['airCode', 'start_date', 'day7', 'current']
views.py:
from django.shortcuts import render
from . models import *
from django.http import HttpResponseRedirect, HttpResponse
from .forms import InputForm
def detail(request):
print(request.GET)
print(request.POST)
if request.method == 'POST':
print( request.POST.get('current'))
form = InputForm(request.POST)
print (form['current'].value())
print (form.data['current'])
if form.is_valid():
print( form.cleaned_data['current'])
print( form.instance.my_field)
form.save()
return HttpResponse('<h1>Hello World</h1>')
and urls.py:
from django.urls import path , include
from . import views
urlpatterns = [
path('', views.detail),
]
Please help me .And yeah I am getting date from a form to make an instance of django form and not from django form making a html form.

The InputForm should be extending ModelForm if you are trying to create a form based off of a model. You can learn more about model forms here
from django.forms import ModelForm
from .models import *
class InputForm(ModelForm):
class Meta:
model = flightInfo
fields = ['airCode', 'start_date', 'day7', 'current']

Related

Error No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model

i'm working on a django project to create football trainings. I'm testing the model and its saving. The problem appears when I try to save it, must be something about redirection, because in the database the training does get saved, but it doesn't redirect me anywhere and the error comes out.
models.py
from django.db import models
from django.utils import timezone
from users.models import User
class Entrenamiento(models.Model):
autor = models.ForeignKey(User, on_delete=models.CASCADE)
idEntrenamiento = models.AutoField(primary_key=True)
idEquipo = models.IntegerField()
fecha = models.DateTimeField(default=timezone.now)
idDireccionCampo = models.IntegerField()
temporadas = [
('2022/2023','2022/2023'),
('2023/2024','2023/2024'),
('2024/2025','2024/2025'),
('2025/2026','2025/2026')
]
temporada = models.CharField(max_length=50, choices=temporadas, default='2022/2023')
def __str__(self):
return 'Entrenamiento {}'.format(self.idEntrenamiento)
#property
def entreno(self):
return 'Entrenamiento {} de {} para {} con fecha del {}, será en el campo {}'.format(self.idEntrenamiento, self.temporada, self.idEquipo, self.fecha, self.idDireccionCampo)
views.py
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.models import User
from django.contrib import messages
from django.http import HttpRequest, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.views.generic import (CreateView, DeleteView, DetailView, ListView,UpdateView)
from django import forms
from django.urls import reverse_lazy
from .models import Entrenamiento
def home(request):
context = {
'entrenamientos': Entrenamiento.objects.all()
}
return render(request, 'entrenamientos/entrenamientos.html', context)
class PostListView(ListView):
model = Entrenamiento
template_name = 'entrenamientos/entrenamientos.html'#<app>/<model>_<viewtype>.html
context_object_name = 'entrenamientos'
ordering = ['-fecha']
class PostDetailView(DetailView):
model = Entrenamiento
class PostCreateView(LoginRequiredMixin, CreateView):
model = Entrenamiento
fields = ['autor','idEntrenamiento','idEquipo','idDireccionCampo','fecha']
widgets = {'fecha': forms.DateInput(attrs={'type': 'date'})}
def form_valid(self,form):
form.instance.autor = self.request.user
return super().form_valid(form)
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = Entrenamiento
fields = ['autor','idEntrenamiento','idEquipo']
def form_valid(self,form):
form.instance.autor = self.request.user
return super().form_valid(form)
def test_func(self):
entrenamiento = self.get_object()
if self.request.user == entrenamiento.autor:
return True
return False
class PostDeleteView(DeleteView):
model = Entrenamiento
success_url = '/'
def test_func(self):
entrenamiento = self.get_object()
if self.request.user == entrenamiento.autor:
return True
return False
urls.py
from django.urls import path
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView
from django.contrib.auth.decorators import login_required
app_name = 'entrenamientos'
urlpatterns = [
path('', login_required(PostListView.as_view()), name='entrenamientos'),
path('entrenamiento/<int:pk>/',login_required( PostDetailView.as_view()), name='entrenamiento-detail'),
path('entrenamiento/new/',login_required( PostCreateView.as_view()), name='entrenamiento-create'),
path('entrenamiento/<int:pk>/update/',login_required( PostUpdateView.as_view()), name='entrenamiento-update'),
path('entrenamiento/<int:pk>/delete/',login_required( PostDeleteView.as_view()), name='entrenamiento-delete'),
path('entrenamiento', login_required(PostListView.as_view()), name='entrenamientos')
]
The error:
ImproperlyConfigured at /entrenamientos/entrenamiento/new/
No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.
I think that something it's wrong with: def form_valid(self,form):
I've tried adding this in the def form_valid but another error appears
# success_url = reverse_lazy('entrenamiento')
# success_message = 'Entrenamiento añadido'
I hope the solution
You have to provide success_url inside your class view. You can do it in one of possibilities, but the first one is enough for this problem:
class PostCreateView(LoginRequiredMixin, CreateView):
...
success_url = reverse_lazy('entrenamientos:entrenamientos')
# OR
def get_success_url(self):
return reverse_lazy('entrenamientos:entrenamientos')
Also look at your urls:
urlpatterns = [
path('', login_required(PostListView.as_view()), name='entrenamientos'),
...
path('entrenamiento', login_required(PostListView.as_view()), name='entrenamientos')
]
You have set two urls with exactly the same name. You should not do that. Always the first one will be rendered with {% url %} tag. Do you even need the second one?

Django Can't See Where I Typed in User ID

So I'm creating a web app in Django, and I encountered this error:
my urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<int:user_id>/', views.profile, name="profile"),
#path('signup/', views.signup, name="signup"),
path("signup/", views.signup, name="signup")
]
my views.py:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth import forms
from django.urls import reverse_lazy
from django.http import HttpResponse, Http404
from django.template import loader
from .models import User
from .forms import SignUpForm
from datetime import datetime
def index(request):
cool_people_list = User.objects.order_by("-username")[:5]
_template = loader.get_template("front_page.html")
context = {
"cool_people_list" : cool_people_list,
}
return HttpResponse(_template.render(context, request))
def profile(request, user_id):
try:
user = get_object_or_404(User, pk=user_id)
_template = loader.get_template("profile.html")
context = {
"user" : user
}
return HttpResponse(_template.render(context, request))
except:
raise Http404("The user you are looking for doesn't exist.")
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = str(datetime.today().strftime("%Y-%m-%D"))
rn2 = str(datetime.today)
"""usr_list = User.objects.order_by('-join_date')
latest_usr = usr_list.first()"""
new_user = User(3, str(form.cleaned_data.get("username")), str(form.cleaned_data.get("password")), rn, rn2)
new_user.save()
return render(request, "signup.html")
my models.py:
from django.db import models
from django.core.validators import MinLengthValidator
import datetime
class User(models.Model):
user_id = models.IntegerField(unique=True)
username = models.CharField(max_length=25, validators=[MinLengthValidator(3)])
password = models.CharField(max_length=25, validators=[MinLengthValidator(7)])
join_date = models.DateField()
last_online = models.DateTimeField()
def __str__(self):
return self.username
I kept trying different methods, like manually adding the user ID (temporary fix), but Django can't see where I type in the ID! It doesn't register it when I typed it in what I believe is the correct format for my 'User' model.
You need to save an object in User Model like this...
def signup(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
rn = datetime.today().strftime("%Y-%m-%D")
rn2 = datetime.today
new_user = User(username= form.cleaned_data["username"], password=form.cleaned_data["password"], rn=rn, rn2=rn2)
new_user.save()
else:
form.errors
return render(request, "signup.html")

How and where should I add a check condition to see if the user is above 18 years in Django?

What I want to do is, if the user is above 18, then ask him to fill out a form ... if below 18, then ask him to fill up a different form and save the form to the database
views.py
from django.shortcuts import render
from app1.form import UserForm
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,"home.html")
def formpage(request):
form=UserForm()
if(request.method=='POST'):
form=UserForm(request.POST)
if(form.is_valid()):
form.save()
return home(request)
return render(request,'formpage.html',{'form':form})
models.py
from django.db import models
# Create your models here.
gen_opts= [
('male','Male'),
('female', 'Female'),
]
class MyUser(models.Model):
name=models.CharField(max_length=40)
gender = models.CharField(max_length=6, choices=gen_opts)
age= models.PositiveIntegerField()
ph.num=models.PositiveIntegerField()
check_box = models.BooleanField()
def __str__(self):
return self.name
forms.py
from app1.models import MyUser
from django import forms
class UserForm(forms.ModelForm):
class Meta():
model=MyUser
fields='__all__'
One option would be to parse the form data, and then take action based on the parsed data.
This should look something like the following:
if form.is_valid():
age = form.cleaned_data['age']
if age < 18:
# render < 18 form
else:
# render >= 18 form

Django error on form - ValueError: Cannot create form field

One of my Django applications have a ModelForm based on a Model that has a ForeignKey from another app. The code is the following:
App - EstoqueGeral - models.py:
class ItemEstoqueGeral(models.Model):
nome = models.CharField(max_length=200, verbose_name="Nome do Produto")
preco_de_compra = models.DecimalField(decimal_places=2, max_digits=6, verbose_name="Preço de Compra")
codigo_fornecedor = models.CharField(max_length=10, verbose_name="Código do Fornecedor")
peso_em_Kg = models.DecimalField(decimal_places=1, max_digits=6, verbose_name="Peso (Kg)")
quantidade_estoque_geral = models.IntegerField(verbose_name="Quantidade no Estoque Geral")
quantidade_minima_estoque_geral = models.IntegerField(verbose_name="Quantidade Mínima no Estoque Geral")
App - EstoqueLoja - models.py:
from django.db import models
import ast
from django import forms
from django.forms import ModelForm
class Loja(models.Model):
nome_loja = models.CharField(max_length=200, verbose_name="Nome da Loja")
def __unicode__(self):
return self.nome_loja
class itemEstoqueLoja(models.Model):
item_estoque = models.ForeignKey('EstoqueGeral.ItemEstoqueGeral', verbose_name="Item do Estoque")
loja = models.ForeignKey(Loja)
preco_loja = models.DecimalField(decimal_places=2, max_digits=6, verbose_name="Preço da Loja")
quantidade_estoque_loja = models.IntegerField(verbose_name="Quantidade no Estoque da Loja")
quantidade_minima_estoque_loja = models.IntegerField(verbose_name="Quantidade Mínima no Estoque da Loja")
def __unicode__(self):
return self.loja.nome_loja + " - " + self.item_estoque.nome
class itemEstoqueLojaForm(ModelForm):
class Meta:
model = itemEstoqueLoja
And i try to use the itemEstoqueLojaForm on a view, like this:
from django.shortcuts import render
from EstoqueLoja.models import Loja, itemEstoqueLoja, itemEstoqueLojaForm
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.template import Context, loader
from django.forms.models import modelform_factory
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def editar_estoque_loja(request, item_estoque_loja):
template = 'EstoqueLoja/editar_estoque_loja.html'
instance = itemEstoqueLoja.objects.get(pk=item_estoque_loja)
if request.method == 'POST':
form_itemestoqueloja = itemEstoqueLojaForm(request.POST, instance=instance)
if form_itemestoqueloja.is_valid():
form_itemestoqueloja.save()
return HttpResponseRedirect('/EstoqueLojas')
else:
form_itemestoqueloja = itemEstoqueLojaForm(instance=instance)
return render_to_response(template, { 'form_itemestoqueloja' : form_itemestoqueloja }, context_instance = RequestContext(request))
But when i try to access the corresponding url, i receive a 500 Internal Server Error. On my log is the following:
ValueError: Cannot create form field for 'item_estoque' yet, because its related model 'EstoqueGeral.ItemEstoqueGeral' has not been loaded yet
I already checked my settings and everything looks fine. Both apps are on the INSTALLED_APPS and EstoqueGeral comes before EstoqueLoja. Does anybody have any idea of what could be causing that error?
If you are using Django 1.6 you might be encountering this Django bug
Try importing your first model (ItemEstoqueGeral) into your 2nd models.py file
App - EstoqueLoja - models.py
from EstoqueGeral.models import ItemEstoqueGeral
In case of a Foreign Key relation, the referenced model ("Parent Table") has to be declared first.

newbie Django smart/chained menu trouble

i am trying to make a chained select menu, i have this model:
from django.db import models
class Health_plan(models.Model):
name = models.CharField(max_length=15)
class Doctors_list(models.Model):
name = models.CharField(max_length=30)
specialty = models.CharField(max_length=15)
health_plans = models.ManyToManyField(Health_plan, related_name="doctors")
location = models.CharField(max_length=15)
def __unicode__(self):
return self.name
And this is my forms.py:
class SpecForm(ModelForm):
a = Doctors_list.objects.values_list('specialty', flat=True)
unique = [('---------------','---------------')] + [(i,i) for i in set(a)]
specialty = forms.ChoiceField(choices=unique)
class Meta:
model = Doctors_list
class HealthForm(ModelForm):
hplan = ChainedForeignKey(
Health_plan,
chained_field="specialty",
chained_model_field="specialty",
show_all=False,
auto_choose=True
)
my urls.py:
from django.conf.urls import patterns, include, url
from testApp.views import spec_form
from testApp.views import health_form
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'Medbook.views.home', name='home'),
# url(r'^Medbook/', include('Medbook.foo.urls')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', spec_form),
url(r'^hello/$', health_form),
)
and my views.py:
from django.shortcuts import render_to_response
from testApp.forms import SpecForm
from testApp.forms import HealthForm
def spec_form (request):
if request.method == 'POST':
form = SpecForm(request.POST)
if form.is_valid():
form.save()
else:
form = SpecForm()
return render_to_response('hello.html', {'form':form})
def health_form (request):
if request.method == 'POST':
form = HealthForm(request.POST)
if form.is_valid():
form.save()
else:
form = SpecForm()
return render_to_response('hello.html', {'form':form})
I am new to Django and i find this tricky. The user must select one specialty, and then should appear the health_plans that cover that specialty.
The health_plans have a manytomany relationship with the doctors. When a person chooses a specialty, the script should check wich doctors belong to that specialty and retrieve all the health plans hold by those doctors.
So far the only thing i get in the menu is: Health_plan object
Health_plan object
Health_plan object
I hope i made it clear, for my code it isn't.
Any help kindly appreciated
This has nothing to do with chained selects, and most of the code here is irrelevant. The issue is that, while Doctors_list has a __unicode__ method, Health_plan does not. Define one for that model too.
(Also note that the usual style for model names is CapWords: DoctorsList and HealthPlan. Although the former actually only refers to a single doctor, so it should just be Doctor.)

Categories