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, 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})
By now the error i get is 'function' object is not iterable when i acess the webpage.
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.
I hope i made it clear, for my code it isn't.
Any help kindly appreciated
EDIT: Stack Trace
Internal Server Error: /hello/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 103, in get_response
resolver_match = resolver.resolve(request.path_info)
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py", line 321, in resolve
sub_match = pattern.resolve(new_path)
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py", line 221, in resolve
kwargs.update(self.default_args)
TypeError: 'function' object is not iterable
[08/May/2013 19:30:45] "GET /hello/ HTTP/1.1" 500 62490
Change:
url(r'^hello/$', spec_form, health_form) to url(r'^hello/$', spec_form)
Also, In the models:
class Health_plan(models.Model):
name = models.CharField(max_length=15)
def __unicode__(self):
return "%s"%(self.name)
Related
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?
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")
If I have another field like ISBN in book so how do I filter with this field in from django.views.generic import DetailField
here is my book/urls.py file code
urlpatterns = [
path('',BookListView.as_view(), name="book_list"),
path('<isbn>/',BookDetailView.as_view(), name="book_detail")
]
book/views.py
class BookDetailView(DetailView):
template_name = "book/detail.html"
def get_queryset(self,*args, **kwargs):
print(self.kwargs['isbn'])
return BookModel.objects.filter(isbn=self.kwargs['isbn'])
and the Error is
Generic detail view BookDetailView must be called with either an object pk or a slug in the URLconf.
you can use isbn as slug
book/urls.py
urlpatterns = [
path('',BookListView.as_view(), name="book_list"),
path('<slug:isbn>/',BookDetailView.as_view(), name="book_detail")
]
book/views.py
class BookDetailView(DetailView):
model = BookModel
template_name = "book/detail.html"
slug_field = 'isbn'
slug_url_kwarg = 'isbn'
I am following a tutorial in which we will create a form to hold simple object parameters.
Here's the code:
forms.py
from django.forms import ModelForm
from .models import Item
class ItemForm(ModelForm):
class Meta:
model = Item
fields = ['item_name', 'item_desc', 'item_price', 'item_image']
models.py
from django.db import models
class Item(models.Model):
def __str__(self):
return self.item_name
item_name = models.CharField(max_length = 200)
item_desc = models.CharField(max_length= 200)
item_price = models.IntegerField()
item_image = models.CharField(max_length=500, default ="https://i.jamesvillas.co.uk/images/jvh/holiday-destinations/resort/food-placeholder.jpg" )
urls.py
from . import views
from django.urls import path
urlpatterns = [
path('', views.index, name = 'index'),
path('item/', views.item, name = 'item'),
path('info/', views.info, name = "info"),
path('<int:item_id>/', views.detail, name = "detail" ),
#add form
path('add', views.create_item, name = "create"),
]
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Item
from django.template import loader
from .forms import ItemForm
#Some code here
def create_item(request):
form = ItemForm(request.POST or None)
if (form.is_valid()):
form.save()
return redirect('food/index')
return render(request, 'food/item-form.html', {'form': form})
food/item-form.html
<form method = "POST">
{% csrf_token %}
{{ form }}
<button type= "Submit" >Save</button>
</form>
Now when I go to http://localhost:8000/food/add, it displays an empty page! I have followed the tutorial the exact same way then why is My project not working?
correct your views.py
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
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.)