Python - Invalid Syntax - Why is this error being thrown? [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I already know that this is going to be a trashy question, as per the SO question guidelines, but I have to keep details down to a minimum. I have a traceback, but I don't know why its throwing an error.
Traceback:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "...USER...\threading.py", line 954, in _bootstrap_inner
self.run()
File "...USER...\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "...USER...\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "...USER...\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "...USER...\site-packages\django\core\management\base.py", line 419, in check
all_issues = checks.run_checks(
File "...USER...\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "...USER...\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "...USER...\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "...USER...\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "...USER...\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "...USER...\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "...USER...\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "...USER...\urls.py", line 20, in <module>
path('django_app/', include('django_app.urls')),
File "...USER...\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "...USER...\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "...USER...\urls.py", line 2, in <module>
from . import views
File "...USER...\views.py", line 185
if t > 0:
^
SyntaxError: invalid syntax
The "syntax error" is being thrown inside of a class that I made inside of my views.py file...
A general, crude idea of the code is:
import os
import sys
import numpy
some other imports
class my_constructor:
def __init__(self):
some stuff
def func(self):
some logic
(t, b, l, r) = self.removed_space
(w, h, th) = self.dimensions
if l > 0 or r > 0:
ppi_w = 0
if t > 0 or b > 0:
ppi_h = 0
if t > 0: #this is line 185 from the last line in the traceback
t = round(t * ppi_h)
if len(array) > 2:
t_a = 0
else:
t_a = 0
ar = 0
m = 0
if b > 0:
b = 0
if len(array) > 2:
b_a = 0
else:
b_a = 0
ar = 0
m = 0
I know a true answer for this likely isn't a reasonable request, but I am desperate and just asking for general ideas as to why this error might actually be occuring. I am using notepad++, so spacing is consistent. I know the syntax for the if statement is right... and apart from that, its got me beat.

if t > 0:
There's nothing wrong with that line. Check the previous line of code for imbalanced parentheses.

Related

Fill out a form, submit and get a response with scrapy

i'm learning to automate some web tasks, and i have this code to fill out a form using python scrapy. It takes essentially mongolian cyrrilic sentences and translate it into traditional mongolian script. What i want to do is to read the sentences into a list from a file ("test.txt") and then to get the translation back and print it in the console.
import scrapy
class BichigSpider(scrapy.Spider):
name = "bichig"
allowed_domains = ["http://trans.mglip.com"]
start_urls = ["http://trans.mglip.com/EnglishC2T.aspx"]
def LoadListofSentences(self):
output = []
with open('test.txt', 'r',encoding='utf-8') as f:
for el in f:
output.append(el)
return output
def parse(self, response):
ListeSent = self.LoadListofSentences()
for sent in ListeSent:
formdata = {'inputCyrillic_ID': sent}
yield scrapy.http.FormRequest.from_response(response,
formdata=formdata,
clickdata={'name': 'ButtonTran_ID'},
callback=self.parse1)
def parse1(self, response):
print(response.css('outPutTraditonalM_ID::text').get())
Content of file "test.txt", located in the folder spiders with the init file:
Хоёр мянга арван гурван оны өвлийн цагаан будан татсан гэрэлт өдөр Өвөрхангай аймгийн театрт Монгол найргийн дархан цэц Дэндэвийн Пүрэвдорж гуайн нэрэмжит “Болор цом” наадмыг жулдрайхан би эхлүүлж байлаа.
Үндсэндээ түрүү жилийн эзэн дараа жилийнхээ цомыг нээдэг тэрхүү уламжлалын дагуу 30 жилийнх нь тэгш ойд түрүүлсний хувьд Пүрэвдорж гуайнхаа наадмыг “Өвгөд минь өндрийн салхи болохуйд” шүлгээрээ нээж байсан.
Тэрхүү хувь заяагаа би дандаа сүслэн боддог.
Пүрэвдорж гуай өөрөө санаачилж эхлүүлсэн, анхны түрүүг нь хүртсэн авшигтай эл наадмыг 80 насных нь их ойгоор өөрийнх нь нэрэмжит болон хүмүүн биеийг олсон халуун голомт Өврийн хангай нутагт нь болоход нээнэ гэдэг хувь заяа гэхээс өөр яалтай.
Шүлгээ дуудчихаад, шүлгээ уншихаар гараанаас эргэх гэж буй морьд шиг тогтож ядан байгаа найрагчдынхаа дунд орж ирэхэд омог төгөлдөр байсан даа.
Эрдэнэ-Очир ах минь, Хөөдөө ах минь, дархад Мийгаа ах минь, Лхамсүрэнжавын Ганзул ах минь бүгд шүлгээ унших гээд ирийтэл зогсож байсан сан.
Мөн ч алтанхан сайхан он жил байж шүү.
Наадмын урьд өдөр “Уран үгсийн чуулган”-д Монголын яруу найргийн их оргилууд Бавуугийн Лхагвасүрэн, Тангадын Галсан, Пунцагийн Бадарч нарын тоосон дунд орж цомын эзэн хэмээн Ичинхорлоо найрагчаар зарлуулж байснаа одоо эргээд бодох нь ээ, айх ч шиг.
Их найргийн бурхдын сүрд дарагдсан бахдал дүүрэн он цаг минь.
But i get this error after writing scrapy crawl bichig in the command line:
Traceback (most recent call last):
File "C:\Users\User\anaconda3\envs\Test\Scripts\scrapy-script.py", line 10, in <module>
sys.exit(execute())
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\cmdline.py", line 124, in execute
cmds = _get_commands_dict(settings, inproject)
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\cmdline.py", line 52, in _get_commands_dict
cmds = _get_commands_from_module('scrapy.commands', inproject)
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\cmdline.py", line 33, in _get_commands_from_module
for cmd in _iter_command_classes(module):
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\cmdline.py", line 20, in _iter_command_classes
for module in walk_modules(module_name):
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\utils\misc.py", line 88, in walk_modules
submod = import_module(fullpath)
File "C:\Users\User\anaconda3\envs\Test\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\commands\parse.py", line 10, in <module>
from scrapy.utils import display
File "C:\Users\User\anaconda3\envs\Test\lib\site-packages\scrapy\utils\display.py", line 5, in <module>
import ctypes
File "C:\Users\User\anaconda3\envs\Test\lib\ctypes\__init__.py", line 8, in <module>
from _ctypes import Union, Structure, Array
ImportError: DLL load failed while importing _ctypes:the specified module could not be found
Can somebody help me please with this or any other viable solution?
Solved! I needed to reinstall python that's all.

if model._meta.abstract: AttributeError: type object 'ProductObject' has no attribute '_meta'

I want to add one of my models to the admin panel, but this error falls:
> Traceback (most recent call last): File
> "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py",
> line 932, in _bootstrap_inner
> self.run() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py",
> line 870, in run
> self._target(*self._args, **self._kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 53, in wrapper
> fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py",
> line 109, in inner_run
> autoreload.raise_last_exception() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 76, in raise_last_exception
> raise _exception[1] File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",
> line 357, in execute
> autoreload.check_errors(django.setup)() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 53, in wrapper
> fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py",
> line 24, in setup
> apps.populate(settings.INSTALLED_APPS) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py",
> line 122, in populate
> app_config.ready() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\apps.py",
> line 24, in ready
> self.module.autodiscover() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\__init__.py",
> line 26, in autodiscover
> autodiscover_modules('admin', register_to=site) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py",
> line 47, in autodiscover_modules
> import_module('%s.%s' % (app_config.name, module_to_search)) File
> "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py",
> line 127, in import_module
> return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File
> "<frozen importlib._bootstrap>", line 991, in _find_and_load File
> "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
> File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
> File "<frozen importlib._bootstrap_external>", line 783, in
> exec_module File "<frozen importlib._bootstrap>", line 219, in
> _call_with_frames_removed File "C:\Users\smirn\OneDrive\Desktop\SYZYGY\Coding\Python\Django\Megan\Fridge\admin.py",
> line 13, in <module>
> admin.site.register([Product, Fridge, ProductObject]) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\sites.py",
> line 104, in register
> if model._meta.abstract: AttributeError: type object 'ProductObject' has no attribute '_meta'
models.py:
from django.db import models as m
from django.conf import settings
import datetime
def mounth():
now = datetime.datetime.now()
return now + datetime.timedelta(days=20)
class Product(m.Model):
product_name = m.CharField(max_length=200)
product_calories = m.PositiveIntegerField(blank=True)
def __str__(self):
return self.product_name
class Fridge(m.Model):
OPTIONS = (
("1", "BASIC"),
("2", "PRO"),
("3", "KING"),
)
fridge_owner = m.ForeignKey(settings.AUTH_USER_MODEL, on_delete=m.CASCADE)
fridge_mode = m.CharField(max_length=5, choices=OPTIONS)
class Recipe(m.Model):
recipe_name = m.CharField(max_length=200)
recipe_products = m.ManyToManyField(Product)
recipe_description = m.TextField()
def __str__(self):
return self.recipe_name
class ProductObject(): # Не знаю как сделать правильно. Вдруг это можно реализовать по другому
product_obj_fridge = m.ForeignKey(Fridge, on_delete=m.CASCADE)
product_obj_product = m.ManyToManyField(Product)
product_shelf_life = m.DateField(default=mounth())
product_count = m.PositiveIntegerField(default=1)
class Meta:
ordering = ('product_shelf_life', )
admin.py:
from django.contrib import admin
from .models import Product, Fridge, Recipe, ProductObject
from tinymce.widgets import TinyMCE
from django.db import models
# Register your models here.
class RecipeAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TinyMCE}
}
admin.site.register([Product, Fridge, ProductObject])
admin.site.register(Recipe, RecipeAdmin)
If I remove the ProductObject in the registration in the admin panel, then there will be no error, but I do not understand this error at all. It seems that everything should be correct, but for some reason not
Please, help me!
In model ProductObject you are missing m.Model in the definition.
Without this the Meta field can not be constructed.

ImportError: cannot import name 'ApiException' running python manage.py

I am not able to import from rest_framework.exceptions import ApiException
This is my Exception.py:
class APIException(Exception):
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
default_detail = _('A server error occurred.')
default_code = 'error'
def __init__(self, detail=None, code=None):
if detail is None:
detail = self.default_detail
if code is None:
code = self.default_code
self.detail = _get_error_details(detail, code)
def __str__(self):
return self.detail
def get_codes(self):
return _get_codes(self.detail)
def get_full_details(self):
return _get_full_details(self.detail)
error while running : python manage.py makemigrations networscanners
Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_from_command_line(sys.argv)
File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li
ne 381, in execute_from_command_line
utility.execute()
File "D:\Python36-32\lib\site-packages\django\core\management\__init__.py", li
ne 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3
23, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3
61, in execute
self.check()
File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3
90, in check
include_deployment_checks=include_deployment_checks,
File "D:\Python36-32\lib\site-packages\django\core\management\base.py", line 3
77, in _run_checks
return checks.run_checks(**kwargs)
File "D:\Python36-32\lib\site-packages\django\core\checks\registry.py", line 7
2, in run_checks
new_errors = check(app_configs=app_configs)
File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 13, i
n check_url_config
return check_resolver(resolver)
File "D:\Python36-32\lib\site-packages\django\core\checks\urls.py", line 23, i
n check_resolver
return check_method()
File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 400, in
check
for pattern in self.url_patterns:
File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line 80, i
n __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 585, in
url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\Python36-32\lib\site-packages\django\utils\functional.py", line 80, i
n __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Python36-32\lib\site-packages\django\urls\resolvers.py", line 578, in
urlconf_module
return import_module(self.urlconf_name)
File "D:\Python36-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\archerysec framework\archerysec-master\archerysecurity\urls.py", line
36, in <module>
from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token
File "D:\Python36-32\lib\site-packages\rest_framework_jwt\views.py", line 1, i
n <module>
from rest_framework.views import APIView
File "D:\Python36-32\lib\site-packages\rest_framework\views\__init__.py", line
1, in <module>
from .base import BaseApiView
File "D:\Python36-32\lib\site-packages\rest_framework\views\base.py", line 5,
in <module>
from rest_framework.exceptions import ApiException
ImportError: cannot import name 'ApiException'
It's APIException (rest_framework.exceptions.APIException), not ApiException.

Learning to code and a syntax error appears when I conduct nose tests, I can't see the error

I receivee a syntax error when I use nosetests on the following piece code.
I've checked the code to see whether it matches the description in the book and I don't see any errors. This is the segment of code I'm using:
from nose.tools import *
from ex47.game import Room
def test_room():
gold = Room ("GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north."""
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, [])
def test_room_paths():
center = Room("Center", "Test room in the center.")
north = Room("North", "Test room in the north.")
south = Room("South", "Test room in the south.")
center.add_paths(['north': north, 'south': south])
assert_equal(center.go('north'), north)
assert_equal(center.go('south'), south)
def test_map():
start = Room("Start", "You can go west and down a hole.")
west = Room("Trees", "There are trees here, you can go east.")
down = Room("Dungeon", "It's dark down here, you can go up.")
start.add_paths(['west': west, 'down': down])
west.add_paths(['east': start])
down.add_paths(['up': start])
assert_eqaul(start.go('west'), west)
assert_equal(start.go('west').go('east'), start)
assert_equal(start.go('down').go('up'), start)
This is what the expected result should be:
$nosetests
...
Ran 3 tests in 0.008s
OK
And this is the actual result that I get:
E
======================================================================
ERROR: Failure: SyntaxError (invalid syntax (ex47_tests.py, line 9))
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/alasdairkite/anaconda3/lib/python3.7/site-
packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/Users/alasdairkite/anaconda3/lib/python3.7/site-
packages/nose/loader.py", line 417, in loadTestsFromName
addr.filename, addr.module)
File "/Users/alasdairkite/anaconda3/lib/python3.7/site-
packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/Users/alasdairkite/anaconda3/lib/python3.7/site-
packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/Users/alasdairkite/anaconda3/lib/python3.7/imp.py", line 234,
in load_module
return load_source(name, filename, file)
File "/Users/alasdairkite/anaconda3/lib/python3.7/imp.py", line 171,
in load_source
module = _load(spec)
File "<frozen importlib._bootstrap>", line 696, in _load
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 724, in
exec_module
File "<frozen importlib._bootstrap_external>", line 860, in get_code
File "<frozen importlib._bootstrap_external>", line 791, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/alasdairkite/Documents/Programming/LMPTHW/LPTHW/projects/Ex47/skeleton/tests/ex47_tests.py", line 9
assert_equal(gold.name, "GoldRoom")
^
SyntaxError: invalid syntax
----------------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (errors=1)
Missing a bracket. Try this:
def test_room():
gold = Room ("GoldRoom")
"""This room has gold in it you can grab. There's a
door to the north."""
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, [])

ValueError: dictionary update sequence element #0 has length 1; 2 is required

I can not locate this error.
Error is genereted after I added one field in disease that is contact and taggable manager in models
If that is correct than is this error is generated due to Id field that I gave manually
Help to me get out of this!!
personal(myapp)/urls.py
urlpatterns = [
url(r'^.*doctorsu/$', views.doctorsu.as_view(), name = 'doctorsu'),
url(r'^.*disease/$', views.AddDisease.as_view(), name = 'AddDisease'),
]
mysite/urls.py
urlpatterns = [
url(r'^$',include('personal.urls')),
url(r'^taggit/',include('taggit_selectize.urls')),
]
models.py
class DoctorSignup(models.Model):
contact_regex = RegexValidator(regex=r'^[789]\d{9}$',message="Phone number must be start with 7,8 or 9")
doid = models.AutoField(verbose_name='Doctor Id',primary_key=True,default=0)
email = models.CharField(max_length=50)
contact = models.CharField(validators=[contact_regex])
class TaggedSymptoms(TaggedItemBase):
content_object = models.ForeignKey("Disease")
class TaggedMedicine(TaggedItemBase):
content_object = models.ForeignKey("Disease")
class Disease(models.Model):
did = models.AutoField(verbose_name='Disease Id', primary_key=True,default=0)
dName = models.CharField(max_length=20)
dtype = models.CharField(max_length=10)
symptoms = TaggableManager(through=TaggedSymptoms)
symptoms.rel.related_name = "+"
medi = TaggableManager(through=TaggedMedicine)
medi.rel.related_name = "+"
views.py
class doctorsu(TemplateView):
template_name = 'personal/doctorsu.html'
def get(self, request):
dsform = DoctorSignupForm()
data = DoctorSignup.objects.all()
args = {'dsform': dsform,'data': data}
return render(request,self.template_name,args)
def post(self, request):
dsform = DoctorSignupForm(request.POST)
if dsform.is_valid():
dsform.save()
cd = dsform.cleaned_data
args = {'dsform': dsform , 'cd': cd}
return render(request,self.template_name,args)
return render(request, 'personal/doctorsu.html')
class AddDisease(TemplateView):
template_name = 'personal/disease.html'
def get(self, request):
dform = DiseaseForm()
ddata = Disease.objects.all()
args = {'dform': dform,'ddata': ddata}
return render(request,self.template_name,args)
def post(self, request):
dform = DiseaseForm(request.POST)
if dform.is_valid():
dform.save()
cd = dform.cleaned_data
args = {'dform': dform , 'cd': cd}
return render(request,self.template_name,args)
forms.py
class DoctorSignupForm(forms.ModelForm):
dname = forms.CharField()
email = forms.EmailField()
contact = forms.RegexField(regex=r'^[789]\d{9}$',error_messages="Enter valid phone no.")
class Meta:
model = DoctorSignup
fields = "__all__"
class DiseaseForm(ModelForm):
dName = forms.CharField(help_text="Enter disease")
symptoms = TagField(help_text="Enter symptoms separated by comma")
medicine = TagField()
class Meta:
model = Disease
fields = "__all__"
Traceback
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
utility.execute()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 327, in execute
self.check()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\IT\project\program\20-8-17\mysite\mysite\urls.py", line 7, in <module>
url(r'^$',include('personal.urls')),
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\IT\project\program\20-8-17\mysite\personal\urls.py", line 2, in <module>
from . import views
File "E:\IT\project\program\20-8-17\mysite\personal\views.py", line 3, in <module>
from personal.forms import *
File "E:\IT\project\program\20-8-17\mysite\personal\forms.py", line 50, in <module>
class DoctorSignupForm(forms.ModelForm):
File "E:\IT\project\program\20-8-17\mysite\personal\forms.py", line 90, in DoctorSignupForm
contact = forms.RegexField(regex=r'^[789]\d{9}$',error_messages="Enter valid phone no.")
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 517, in __init__
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 228, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 122, in __init__
messages.update(error_messages or {})
ValueError: dictionary update sequence element #0 has length 1; 2 is required
error_messages should be a dict, not a string.
See the docs.

Categories