Why the form doesn't show field errors and submits the form blank or invalid? - python-3.x

I'm creating a form where a field has a regex validator. But when I submit a blank form, it doesn't prompt the user for required field or validation error. It just redirects the user to 'ValueError at /data/
The InitialData could not be created because the data didn't validate.'
The Traceback:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/data/
Django Version: 3.2.4
Python Version: 3.9.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "E:\Sonu\Projects\Billing\rough\account\views.py", line 10, in initialview
fm.save()
File "C:\Users\ceo\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py", line 460, in save
raise ValueError(
Exception Type: ValueError at /data/
Exception Value: The InitialData could not be created because the data didn't validate.
models.py:
from django.db import models
from django.core.validators import RegexValidator
# Create your models here.
class InitialData(models.Model):
pattern = RegexValidator(r'OOPL\/D\/[0-9]', 'Enter Case Number properly!')
case_number=models.CharField(max_length=12, blank=False, primary_key=True, validators=[pattern])
forms.py:
from django import forms
from django.forms import ModelForm, fields
from .models import InitialData
class TrackReportForm(forms.ModelForm):
class Meta:
model=InitialData
fields='__all__'
views.py:
from django.shortcuts import render
from .forms import TrackReportForm
from .models import InitialData
# Create your views here.
def initialview(request):
if request.method=='POST':
fm=TrackReportForm(request.POST)
if fm.is_valid:
fm.save()
return render(request, 'account/database.html', {'form':fm})
else:
fm=TrackReportForm()
return render(request, 'account/database.html', {'form':fm})
database.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="post" novalidate>
{% csrf_token %}
{{form}} {{field.errors}}
<input type="submit" value="Submit">
</form>
</body>
</html>
URLs:
from django.contrib import admin
from django.urls import path
from account import views
urlpatterns = [
path('admin/', admin.site.urls),
path('data/', views.initialview),
]
Where am I wrong?

You need to change:
if fm.is_valid:
fm.save()
To the code below with brackets ():
if fm.is_valid():
fm.save()
See the docs here for is_valid().

Related

Django href link not routing to correct url

The links within my pages/templates/base.html which are used for a header template results in 404 error. The pages load correctly when manually written 'http://127.0.0.1:8000' 'http://127.0.0.1:8000/about/'.
I am using class based views and following chapter 3 of Django for beginners (William Vincent).
pages/templates/base.html:
<header>
Home |
About
</header>
pages/urls.py:
from django.urls import path
from .views import HomePageView, AboutPageView
urlpatterns = [
path("", HomePageView.as_view(), name="home"),
path("about/", AboutPageView.as_view(), name="about"),
]
portfolio/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("pages.urls")),
]
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages.apps.PagesConfig',
]
pages/views.py:
from django.views.generic import TemplateView
# Create your views here.
from django.http import HttpResponse
class HomePageView(TemplateView):
template_name = 'home.html'
class AboutPageView(TemplateView):
template_name = "about.html"
The error is as follows:
Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about/ [name='about']
The current path, about/{% url 'about' %, didn’t match any of these.
Terminal error:
Not Found: /{% url 'about' %
[26/Oct/2022 11:40:02] "GET /%7B%%20url%20'about'%20% HTTP/1.1" 404 2497
I think the issue lies in pages/urls.py, as if click the 'home' link from 'http://127.0.0.1:8000/about/' the url is 'http://127.0.0.1:8000/about/%7B%%20url%20'home'%20%'. I've tried to remove the "about/" from " path("about/", AboutPageView.as_view(), name="about"),
"
I am also not sure whether the href tags have been written correctly. I have looked at this and this but can't figure it out. Thanks.
{% url 'about' % <- you need to close it properly.

Issue with circular import in Django tutorials?

I am getting a circular import error with a basic Django page setup and I have no idea why. Am following the guides of at least 4 or 5 different tutorials with the same result.
I have varied the syntax in the webapps urls.py to no avail. Any ideas ?
mainproject
urls.py file
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('members/', include('members.urls')),
path('admin/', admin.site.urls),
]
webapp
Views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello world!")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Error
"/Users/Desktop/website/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 706, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'members.urls' from '/Users/Desktop/website/main/members/urls.py'>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import.

error in django templates at {{form.as_table}} when trying to use Create form

I'm workin on a project of a webApp for fleet managment, using Django 3.1 and Python 3.7.
I'm using models:
class Driver(Employee):
supervisor_id = models.ForeignKey('Supervisor', on_delete=models.CASCADE, blank=True, null=True)
projects = models.ManyToManyField('Client', through='ProjectFleet', blank=True, null=True)
is_driver=True
def __str__(self):
return (self.last_name)
class Client(models.Model):
client_name = models.CharField(max_length=128, blank=True, null=True)
client_adress = models.CharField(max_length=128, blank=True, null=True)
client_logo = models.ImageField(upload_to='ClientsLogos/', max_length=100, blank=True, null=True)
phone_number1 = PhoneNumberField(blank=True, null=True)
phone1_label = models.CharField(max_length=128, blank=True, null=True)
phone_number2 = PhoneNumberField(blank=True, null=True)
phoneé_label = models.CharField(max_length=128, blank=True, null=True)
phone_number3 = PhoneNumberField( blank=True, null=True)
phone3_label = models.CharField(max_length=128, blank=True, null=True)
client_email1 = models.EmailField(blank=True, null=True)
email1_label = models.CharField(max_length=128, blank=True, null=True)
client_email2 = models.EmailField(blank=True, null=True)
email2_label = models.CharField(max_length=128, blank=True, null=True)
client_email3 = models.EmailField(blank=True, null=True)
email3_label = models.CharField(max_length=128, blank=True, null=True)
drivers = models.ManyToManyField('Driver', through='ProjectFleet')
def __str__(self):
return (self.client_name)
class ProjectFleet(models.Model):
client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL)
drivers = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL)
def __str__(self):
return (self.client_id)
class Contract(models.Model):
client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL)
contract_title = models.CharField(max_length=128, blank=True, null=True)
contract_details = models.CharField(max_length=512, blank=True, null=True)
effective_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
expiration_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True)
def __str__(self):
return (self.contract_title)
the views I'm trying to use :
class DriverCreationView(LoginRequiredMixin, CreateView):
model = Driver
fields = ['registration_number','first_name', 'last_name', 'password', 'cni', 'birth_date', 'birth_city', 'picture', 'matricule_cnss', 'driving_licence', 'recruitment_date', 'phone', 'salary', 'Contract_type', 'adress', 'city_id', 'region_id', 'payment_mode', 'bank_address', 'bank_id', 'is_driver', 'vehicle_id', 'supervisor_id', 'projects']
success_url = reverse_lazy('Drivers_App_Management:all-drivers')
class ClientCreationView(LoginRequiredMixin, CreateView):
model = Client
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-clients')
class ProjectFleetCreationView(LoginRequiredMixin, CreateView):
model = ProjectFleet
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-projectsfleet')
class ContractCreationView(LoginRequiredMixin, CreateView):
model = Contract
fields = '__all__'
success_url = reverse_lazy('Drivers_App_Management:all-contracts')
The problem I have is when I try to access the forms for the creation of Project fleet which is a trough table and also the creation of Contract.
The Templates for each one are:
projectfleet_form.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Client Creation</title>
</head>
<body>
<h1>This is the Project Fleet Creation form </h1>
<form class="" action="" method="post">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" name="" value="submit">
<input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-projectsfleet' %}' ; return False;" value="Cancel">
</form>
</body>
</html>
and the contract_form.html
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Contract Creation</title>
</head>
<body>
<h1>This is the Contract Creation form </h1>
<form class="" action="" method="post">
{% csrf_token %}
<table>
{{form.as_table}}
{{ form.contract_title }}
{{ form.contract_details }}
{{ form.effective_date }}
{{ form.expiration_date }}
</table>
<input type="submit" name="" value="submit">
<input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-contracts' %}' ; return False;" value="Cancel">
</form>
</body>
</html>
for both templates I get an error that I don't understand:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Drivers_App_Management/ProjectFleetCreation
Django Version: 3.1.3
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django_extensions',
'phonenumber_field',
'Drivers_App_Management',
'django_rename_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/mohammed/Projects/Transport_Project/Drivers_App_Management/templates/Drivers_App_Management/projectfleet_form.html, error at line 11
__str__ returned non-string (type NoneType)
1 : <html lang="en" dir="ltr">
2 : <head>
3 : <meta charset="utf-8">
4 : <title>Client Creation</title>
5 : </head>
6 : <body>
7 : <h1>This is the Project Fleet Creation form </h1>
8 : <form class="" action="" method="post">
9 : {% csrf_token %}
10 : <table>
11 : {{ form.as_table }}
12 : </table>
13 : <input type="submit" name="" value="submit">
14 : <input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-projectsfleet' %}' ; return False;" value="Cancel">
15 : </form>
16 : </body>
17 : </html>
18 :
Traceback (most recent call last):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
obj = self.var.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
value = self._resolve_lookup(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 858, in _resolve_lookup
current = current()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 277, in as_table
errors_on_separate_row=False,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 236, in _html_output
'field_name': bf.html_name,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/utils/html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 34, in __str__
return self.as_widget()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 97, in as_widget
renderer=self.form.renderer,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 241, in render
context = self.get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 678, in get_context
context = super().get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 639, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1157, in __iter__
yield self.choice(obj)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1171, in choice
self.field.label_from_instance(obj),
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1240, in label_from_instance
return str(obj)
Exception Type: TypeError at /Drivers_App_Management/ProjectFleetCreation
Exception Value: __str__ returned non-string (type NoneType)
and for the Contract form :
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/Drivers_App_Management/ContractCreation
Django Version: 3.1.3
Python Version: 3.7.4
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.gis',
'django_extensions',
'phonenumber_field',
'Drivers_App_Management',
'django_rename_app']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/mohammed/Projects/Transport_Project/Drivers_App_Management/templates/Drivers_App_Management/contract_form.html, error at line 11
__str__ returned non-string (type NoneType)
1 : <html lang="en" dir="ltr">
2 : <head>
3 : <meta charset="utf-8">
4 : <title>Contract Creation</title>
5 : </head>
6 : <body>
7 : <h1>This is the Contract Creation form </h1>
8 : <form class="" action="" method="post">
9 : {% csrf_token %}
10 : <table>
11 : {{form.as_table}}
12 : {{ form.contract_title }}
13 : {{ form.contract_details }}
14 : {{ form.effective_date }}
15 : {{ form.expiration_date }}
16 : </table>
17 : <input type="submit" name="" value="submit">
18 : <input type="submit" onclick="window.location='{% url 'Drivers_App_Management:all-contracts' %}' ; return False;" value="Cancel">
19 : </form>
20 : </body>
21 : </html>
Traceback (most recent call last):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 202, in _get_response
response = response.render()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 105, in render
self.content = self.rendered_content
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/response.py", line 83, in rendered_content
return template.render(context, self._request)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 170, in render
return self._render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 162, in _render
return self.nodelist.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 938, in render
bit = node.render_annotated(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 905, in render_annotated
return self.render(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 988, in render
output = self.filter_expression.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 671, in resolve
obj = self.var.resolve(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 796, in resolve
value = self._resolve_lookup(context)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/template/base.py", line 858, in _resolve_lookup
current = current()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 277, in as_table
errors_on_separate_row=False,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/forms.py", line 236, in _html_output
'field_name': bf.html_name,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/utils/html.py", line 376, in <lambda>
klass.__str__ = lambda self: mark_safe(klass_str(self))
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 34, in __str__
return self.as_widget()
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/boundfield.py", line 97, in as_widget
renderer=self.form.renderer,
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 241, in render
context = self.get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 678, in get_context
context = super().get_context(name, value, attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 639, in get_context
context['widget']['optgroups'] = self.optgroups(name, context['widget']['value'], attrs)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/widgets.py", line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1157, in __iter__
yield self.choice(obj)
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1171, in choice
self.field.label_from_instance(obj),
File "/home/mohammed/anaconda3/envs/myEnv/lib/python3.7/site-packages/django/forms/models.py", line 1240, in label_from_instance
return str(obj)
Exception Type: TypeError at /Drivers_App_Management/ContractCreation
Exception Value: __str__ returned non-string (type NoneType)
I want to mention that I don't get any error if I use form with fields names {{form.contract_title}} for example but I got them without the label.
You managed to trick yourself into thinking that nullable foreign keys in a through model is a sane thing. It's not. In any ManyToMany relation, both foreign keys to the relation models should be set, otherwise there is no relation and no need for a row in the model.
This results in model choices with None values for the labels, which is what it's complaining about.
Root problem
The underlying problem is your __str__() method for both models. As the name indicates, it should always return a string, but you allow it to return None.
Change to:
def __str__(self) -> str:
return self.contract_title or ""
But you should really revisit your model design. Having fields with null=True has its uses, but for a CharField without unique=True, it's only causing problems with no benefits.

Reverse for 'action' with arguments '('',)' not found

I have error that seemed to happen to some other people, still I didn't figure out what am I doing wrong, so asking you all for help. Can you please support me with my code? As soon as I try to use form element with action "{% url 'mtg:action' card.name %}" I receive error Reverse for 'action' with arguments '('',)' not found
EDIT: I'd like to add that card name is suppsed to be written by the user, so its not available as page is loaded.
Thanks in advance!
views.py:
def index(request):
context = {'cards': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def lookup(request, card_name):
context = {'card_lookup': Card.objects.all()}
return render(request, 'mtg/index.html', context)
def action(request, card_name):
card = get_object_or_404(Card, pk=card_name)
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('mtg:tmpl', args=card_name))
urls.py:
app_name = 'mtg'
urlpatterns = [
path('', views.index, name="index"),
path('<str:card_name>/img', views.lookup, name='img'),
path('<str:card_name>/action', views.action, name='action'),
]
index.html:
<body>
<form class="wrap" action="{% url 'mtg:action' card.name %}" method="post">
<input class="searchTerm"/>
<button class="center" name="search">Search for synergy</button>
<button class="center" name="lookup">Lookup a card</button>
</form>
{% if lookup_card %}<div>{{ card_lookup }}</div>{% endif %}
</body>
EDIT: as requested adding also logs of error:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.3
Python Version: 3.7.8
Installed Applications:
['mtg.apps.MtgConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\templates\mtg\index.html, error at line 45
Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']
35 : .wrap{
36 : width: 30%;
37 : position: absolute;
38 : top: 30%;
39 : left: 50%;
40 : transform: translate(-50%, -50%);
41 : }
42 : </style>
43 : </head>
44 : <body>
45 : <form class="wrap" action=" {% url 'mtg:action' card.name %} " method="post">
46 : <input class="searchTerm"/>
47 : <button class="center" name="search">Search for synergy</button>
48 : <button class="center" name="lookup">Lookup a card</button>
49 : {% if card_lookup %}<img src="{{ card_lookup }}" width="80" height="200"/>{% endif %}
50 : </form>
51 : </body>
52 : </html>
Traceback (most recent call last):
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Sajemiur\PycharmProjects\MtG_reader\mtg_django\mtg\views.py", line 14, in index
return render(request, 'mtg/index.html', context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\loader.py", line 62, in render_to_string
return template.render(context, request)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 170, in render
return self._render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 162, in _render
return self.nodelist.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 938, in render
bit = node.render_annotated(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\base.py", line 905, in render_annotated
return self.render(context)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\template\defaulttags.py", line 446, in render
url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\base.py", line 87, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "C:\Users\Sajemiur\anaconda3\envs\mtgenv\lib\site-packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'action' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<card_name>[^/]+)/action$']
you used {% if lookup_card %} but you passed in your view card_lookup
and if you want only name of card than get only name from Card object context = {'cards': Card.objects.values(name)}

Django not picking up the functions

I have tried every thing from making new function and saving every file thrice but nothing seems to work. And its my first time using Django if any one find anything please point it out...
Note: Django ver 3.1
Server Error:
path('', views.home_view),
AttributeError: module 'pages.views' has no attribute 'home_view'
settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products', 'pages',
]
views.py
from django.http import HttpResponse
# Create your views here.
def home_view(*args, **kwargs):
return HttpResponse("Hello world")
urls.py
from django.contrib import admin
from django.urls import path
from pages import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.home_view),
]
in urls.py change "from pages import views" to "from . import views"

Resources