I am new to Django, I have created a model and trying to post data from the front end.
following is my view.py
def studentForm(request):
userProfile = StudentProfileForm.objects.create(FirstName=request.POST['userFirstName'] LastName=request.POST['userLastName'], GreScore= request.POST['userGreScore'], IELTSTOEFL=request.POST['userIeltsToefl'],WorkEx=request.POST['userWorkEx'],ResearchDone=request.POST['userResearch'])
userProfile.save()
return render(request,'register/bg-pages.html')
Following is my model
class StudentProfileForm(models.Model):
FirstName = models.CharField(max_length=255)
LastName = models.CharField(max_length=255)
GreScore = models.IntegerField()
IELTSTOEFL = models.IntegerField()
WorkEx = models.IntegerField()
ResearchDone = models.IntegerField()
Error is following:
Request
Method: GET
Request URL: http://127.0.0.1:8000/student_form
Django Version: 2.1.5
Exception Type: MultiValueDictKeyError
Exception Value:
'userFirstName'
Exception Location: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 79
Python Executable: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.1
Python Path:
['D:\\AB\\UOR_everything\\semester_2(winter_2019)\\Software_Engineering\\login_registration',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\AB\\AppData\\Roaming\\Python\\Python37\\site-packages',
'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time: Sun, 10 Mar 2019 00:35:51 +0000
If one of your POST parameters is missing, you will get an error unless you use .get() with a fallback parameter. Also, You are missing a , in your .create() method.
Example:
name = request.POST.get('name', '') # This will get the name value, or be an empty string if empty
Try this:
def studentForm(request):
if request.METHOD == 'POST': # This will protect you against GET requests
first_name = request.POST.get('userFirstName', '')
last_name = request.POST.get('userLastName', '')
gre_score = request.POST.get('userGreScore', '')
ieltstoefl = request.POST.get('userIeltsToefl', '')
work_ex = request.POST.get('userWorkEx', '')
research_done = request.POST.get('userResearch', '')
# `userProfile.save()` is unnecessary bc `.create()` already does this
userProfile = StudentProfileForm.objects.create(FirstName=first_name, LastName=last_name, GreScore=gre_score, IELTSTOEFL=ieltstoefl, WorkEx=work_ex, ResearchDone=research_done)
return render(request,'register/bg-pages.html')
Related
This form working working perfectly,
class FeedBackForm(forms.Form):
feedBACK = forms.CharField(widget=forms.Textarea, required=True)
But this form didn't work
class FeedBackForm(forms.Form):
feedBACK = forms.CharField(widget=forms.Textarea, required=True)
rating = forms.CharField(widget=forms.IntegerField, required=True)
It is showing below error. Where did the problem occur? I checked documentation but no clue I found.
AttributeError at /quick_view/11/
'IntegerField' object has no attribute 'value_from_datadict'
Request Method: POST
Request URL: http://127.0.0.1:8000/quick_view/11/
Django Version: 4.0.4
Exception Type: AttributeError
Exception Value:
'IntegerField' object has no attribute 'value_from_datadict'
Exception Location: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\lib\site-packages\django\forms\forms.py, line 224, in _widget_data_value
Python Executable: D:\1_WebDevelopment\17_Ecomerce Website\ecomerce site\env\Scripts\python.exe
Python Version: 3.9.5
Python Path:
['D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\python39.zip',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\DLLs',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39\\lib',
'c:\\users\\dcl\\appdata\\local\\programs\\python\\python39',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce site\\env',
'D:\\1_WebDevelopment\\17_Ecomerce Website\\ecomerce '
'site\\env\\lib\\site-packages']
Server time: Wed, 13 Jul 2022 10:41:38 +0000
An IntegerField [Django-doc] is a form field, not a widget. You specify the field as:
class FeedBackForm(forms.Form):
feedBACK = forms.CharField(widget=forms.Textarea)
rating = forms.IntegerField()
Note: By default, a form field has required=True [Django-doc], hence you do not need to mark fields as required.
When using get_next_by_Foo, it doesnt show content in template file.
I get data from this query:
request.session['contract_posts_search'] is results I get from filtering in another view.
def contract_detail_test(request, contract_id=None):
context = {}
contract_posts_search=request.session['contract_posts_search']
contract_filtered=[]
for i in range(len(contract_posts_search)):
contract_filtered.append(contract_posts_search[i]["fields"]["contract"])
contract_posts_search= Contracts.objects.filter(contract__in=contract_filtered).distinct()
contract_posts = get_object_or_404(contract_posts_search, contract=contract_id)
After having contract_post, I use get_next_by_created_at:
if contract_posts is not None:
print(contract_posts)
try:
the_next = contract_posts.get_next_by_created_at()
except:
the_next=None
try:
the_prev = contract_posts.get_previous_by_created_at()
except:
the_prev=None
context = { "contract_posts": contract_posts,
"the_next" : the_next,
"the_prev": the_prev,
}
return render(request, "contract_detail_test.html", context)
My ulr:
path('contract_detail_test/<str:contract_id>/', contract_detail_test, name="contract_detail_test")
My model:
class Contracts(models.Model):
id=models.AutoField(primary_key=True)
contract=models.CharField(max_length=255,blank=True, null=True)
name=models.CharField(max_length=255,blank=True, null=True)
debt=models.IntegerField(blank=True, null=True)
created_at=models.DateTimeField(auto_now_add=True,blank=True)
updated_at=models.DateTimeField(auto_now_add=True,blank=True)
objects=models.Manager()
class Meta:
ordering=["-created_at","-id"]
def get_absolute_url(self):
return "/contract_detail_test/%s/" % self.contract
For example:
I filter contract contain "2016" and get 10 results, using request_session in another view, I can print out 10 results.
Then I use get_next_by_created_at, It will show first result correctly, but after clicking, it will show
this error. There is no contract number 20170709-0010161 in contract_posts
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/contract_detail_test/20170709-0010161/
Raised by: test_upload_filter.views.contract_detail_test
No Contracts matches the given query.
My Code:
models.py
from flask_mongoengine import MongoEngine, QuerySet
import datetime
db = MongoEngine()
class Service(db.Document):
service_name = db.StringField(max_length=50, required=True)
date_created = db.DateTimeField(default=datetime.datetime.utcnow)
meta = {
'ordering': ['-date_created'], 'strict' : False
}
class Organisation(db.Document):
org_name = db.StringField(max_length=50, required = True)
service = db.ReferenceField(Service, reverse_delete_rule='CASCADE', required=True)
date_created = db.DateTimeField(default=datetime.datetime.utcnow)
meta = {
'ordering': ['-date_created'], 'strict' : False
}
API(routes.py)
#service.route('/services/<name>', methods=['GET'])
def get_one_service(name):
s = Service.objects(service_name=name)
if s:
output = {'service_name' : s.service_name}
else:
output = "No such name"
return jsonify({'result' : output})
The get_one_service() method returns the above mentioned error. As per the documentation, this is correct.
In your get_one_service function, s is not a Service instance but a queryset (this example from the documentation might make it clearer)
You can access a single instance of Service by doing something like:
try
s = Service.objects.get(service_name=name)
output = {'service_name' : s.service_name}
except Service.DoesNotExist:
output = 'no such name'
Though, since the service_name field is not unique in your model, you may get a MultipleObjectsReturned exception if there's two documents with the same service_name.
Alternatively, you can see if s contains multiple Services and act accordingly.
Am working with sleekxmpp with python for sending messages and its working perfectly.Now i need to implement same in django to create web api for my mobile application.
When i implement that code in django its not getting connected to ejabberd server.xmpp=self.aaaa(jid,password,receiver,message) this function is throughing none value.
Below is my code in django:
class SendMessageView(APIView,sleekxmpp.ClientXMPP):
def aaaa(self,jid, password, recipient, message):
print "dddddddddddddddddddddddddddddddd",jid,password
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.recipient = recipient
self.msg = message
self.add_event_handler("session_start", self.start)
def start(self, event):
self.send_presence()
try:
self.get_roster()
except IqError as err:
logging.error('There was an error getting the roster')
logging.error(err.iq['error']['condition'])
self.disconnect()
except IqTimeout:
logging.error('Server is taking too long to respond')
self.disconnect()
self.send_message(mto=self.recipient,mbody=self.msg,mtype='chat')
self.disconnect(wait=True)
def post(self,request,format=None):
serializer=SendMessageSerializer(request.DATA)
jid=request.DATA.get('sender')
password=request.DATA.get('password')
receiver=request.DATA.get('receiver')
message=request.DATA.get('message')
print "ddddddddddddd",jid,password,receiver,message
xmpp=self.aaaa(jid,password,receiver,message)
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",xmpp
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
if xmpp.connect():
xmpp.process(block=False)
print "Connected"
else:
print "Not Connected"
Error shown is:
AttributeError at /chat-message/send/
'NoneType' object has no attribute 'register_plugin'
Request Method: POST
Request URL: ******/chat-message/send/
Django Version: 1.6
Exception Type: AttributeError
Exception Value:
'NoneType' object has no attribute 'register_plugin'
Exception Location: /home/ntech/projects/project_path/apps/chats/views.py in post, line 58
Python Executable: /home/ntech/Virtualenv/project_path/bin/python
Python Version: 2.7.6
Python Path:
['/home/ntech/projects/chatline',
'/home/ntech/Virtualenv/project_path/lib/python2.7',
'/home/ntech/Virtualenv/project_path/lib/python2.7/plat-i386-linux-gnu',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-old',
'/home/ntech/Virtualenv/project_path/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-i386-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/ntech/Virtualenv/project_path/local/lib/python2.7/site-packages',
'/home/ntech/Virtualenv/project_path/lib/python2.7/site-packages']
Server time: Mon, 29 Dec 2014 06:02:10 +0000
Your method aaaa always return None. Try to use self.
Also it is not a good idea to multiple inheritance here. Try aggregation
class SendMessageView(APIView):
def aaaa(self,jid, password, recipient, message):
...
self.xmpp = sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
self.aaaa(jid,password,receiver,message)
self.xmpp.register_plugin('xep_0030')
self.xmpp.register_plugin('xep_0199')
...
Or even better:
class SendMessageView(APIView):
def get_xmpp(self,jid, password, recipient, message):
...
return sleekxmpp.ClientXMPP(jid, password)
...
def post(self,request,format=None):
...
xmpp = self.get_xmpp(jid,password,receiver,message)
xmpp.register_plugin('xep_0030')
xmpp.register_plugin('xep_0199')
...
Please see my urlpatterns given below, I get the following error when I try to run the program...
ImproperlyConfigured at /
"^product/(?p<product_slug> [-\w]+)/$" is not a valid regular expression: unexpected end of pattern
Request Method:
GET
Request URL:
http://127.0.0.1:8000/
Django Version:
1.5.1
Exception Type:
ImproperlyConfigured
Exception Value:
"^product/(?p<product_slug> [-\w]+)/$" is not a valid regular expression: unexpected end of pattern
Exception Location:
C:\Python27\lib\site-packages\django-1.5.1-py2.7.egg\django\core\urlresolvers.py in regex, line 178
Python Executable:
C:\Python27\python.exe
urls.py
urlpatterns = patterns('ecomstore.catalog.views',
(r'^$','index',{'template_name':'catalog/index.html'},'catalog_home'),
(r'^category/(?P<category_slug>[-\w]+)/$','show_category',{'template_name':'catalog/category.html'},'catalog_category'),
(r'^product/(?p<product_slug> [-\w]+)/$','show_product',{'template_name':'catalog/product.html'},'catalog_product'),
)
views.py
def index(request,template_name="catalog/index.html"):
page_title = 'Music instruments and Sheet music for musicians'
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_category(request,category_slug,template_name="catalog/category.html"):
print 'In Catalog views|category_slug=', category_slug
c = get_object_or_404(Category,slug=category_slug)
products = c.product_set.all()
page_title = c.name
meta_keywords = c.meta_keywords
meta_description = c.meta_description
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
def show_product(request,product_slug,template_name="catalog/product.html"):
p = get_object_or_404(Product, slug=product_slug)
categories = p.categories.filter(is_active=True)
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
return render_to_response(template_name,locals(),context_instance=RequestContext(request))
You just need to capitalize your ?p, so:
r'^product/(?P<product_slug> [-\w]+)/$'