Form data not stored in database. What is the problem? - django

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.

Related

How to compare a two table values in django using filter

I need to compare the row values of Specific_product table (product) and Product table (name) using the sp.product
def count_time(request):
sp = Specific_product.objects.filter(boolean=False)
products = Product.objects.all().filter(name={{sp.product}})
stu={
"pro_d":sp,'products': products,'purchases':purchases
}
return render(request, 'mf_ta/product_status.html', stu)
How can I satisfy this condition?
I'm getting this error
AttributeError at /count_time/
'QuerySet' object has no attribute 'product'
Request Method: GET
Request URL: http://127.0.0.1:8000/count_time/
Django Version: 4.0.7
Exception Type: AttributeError
Exception Value:
'QuerySet' object has no attribute 'product'
Exception Location: C:\Users\Admin\PycharmProjects\pythonProject1\invention_on_macroalgae\manufacturing_team_app\views.py, line 56, in count_time
Python Executable: C:\Users\Admin\PycharmProjects\pythonProject1\venv\Scripts\python.exe
Python Version: 3.9.0
Python Path:
['C:\\Users\\Admin\\PycharmProjects\\pythonProject1\\invention_on_macroalgae',
'C:\\Users\\Admin\\PycharmProjects\\pythonProject1',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\Admin\\PycharmProjects\\pythonProject1\\venv',
'C:\\Users\\Admin\\PycharmProjects\\pythonProject1\\venv\\lib\\site-packages']
Server time: Mon, 26 Dec 2022 03:54:39 +0000
.filter returns a QuerySet not a single object. You probably need one of:
sp = Specific_product.objects.filter(boolean=False).first()
sp = Specific_product.objects.filter(boolean=False).last()
sp = Specific_product.objects.get(boolean=False)
try this
def count_time(request):
sp = Specific_product.objects.filter(boolean=False)
products = Product.objects.all().filter(name__in=list(sp.values('product', flat=True)))
products = Product.objects.all().filter(name__in=list(sp.values('product__name', flat=True)))
stu = {
"pro_d": sp, 'products': products, 'purchases': purchases
}
return render(request, 'mf_ta/product_status.html', stu)

MultiValueDictKeyError Django at /student_form

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')

Cannot assign "<SimpleLazyObject

class ProductDetailSlugview(ObjectViewedMixin, DetailView):
queryset = Product.objects.all()
template_name = "products/product_detail.html"
def get_context_data(self, *args, **kwargs):
context=super(ProductDetailSlugview, self).get_context_data(*args , **kwargs)
cart_object, new_object = Cart.objects.new_or_get(self.request)
context['cart']=cart_object
return context
this is my view
ValueError at /product/list/blackberry Cannot assign
"
at 0x7f0488733860>>": "ObjectViewed.user" must be a "User" instance.
Request Method: GET Request
URL: http://127.0.0.1:8000/product/list/blackberry Django
Version: 2.1.3 Exception Type: ValueError Exception Value: Cannot
assign "
object at 0x7f0488733860>>": "ObjectViewed.user" must be a "User"
instance. Exception
Location: /home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py
in set, line 210 Python
Executable: /home/wiwigi/Desktop/django-virtual/bin/python3 Python
Version: 3.6.5 Python Path: ['/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/ecommerce_sample',
'/home/wiwigi/Desktop/django-virtual/lib/python36.zip',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/lib-dynload',
'/usr/lib/python3.6',
'/home/wiwigi/Desktop/django-virtual/lib/python3.6/site-packages',
'/home/wiwigi/pycharm-2018.1.2/helpers/pycharm_matplotlib_backend']
Server time: mar, 26 Fév 2019 11:31:14 +0000
and my error code please help me
You are assigning an AnonymousUser object to the attribute user of an ObjectViewed instance. From the naming, my guess is that this happens in the ObjectViewedMixin.
For a more definite answer, you have to post the full stack trace and the relevant code.
This is because of you are accessing this view with out login (So it shows AnonymousUser) so you need to add LoginRequiredMixin to your class as below to ensure that only logged in users can visit this view.
from django.contrib.auth.mixins import LoginRequiredMixin
class ProductDetailSlugview(LoginRequiredMixin, ObjectViewedMixin, DetailView):
# rest of the code

Django 1.7 matching query does not exist

I have the following error when I try to create a class-based view to Modify my model Destino.
If possible I would do without using slug or pk in the urls.py
Error:
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
Django Version: 1.7
Exception Type: DoesNotExist
Exception Value:
Destino matching query does not exist.
Exception Location: /usr/local/lib/python2.7/dist-packages/Django-1.7- py2.7.egg/django/db/models/query.py in get, line 357
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/juanma/Escritorio/exPWfebrero/Django/AgenciaViajes',
'/usr/local/lib/python2.7/dist-packages/Django-1.7-py2.7.egg',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PILcompat',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/python2.7/dist-packages/wx-2.8-gtk2-unicode']
URLS:
url(r'^modificarVC/modificar.html', modificarVC.as_view(), name='modificarDestino'),
VIEWS:
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
def get_object(self):
return Destino.objects.get(pk=self.request.GET.get('pk'))
As stated in some comments, you've done a few things that go against the power of class based views. In regards to the UpdateView which you're using, it's expecting a pk to be passed in.
# urls.py
url(r'^modificarVC/modificar/(?P<pk>\d+)/$', modificarVC.as_view(), name='modificarDestino')
When you hit a URL such as /modificarVC/modificar/5/ the UpdateView automatically sets the object by selected the object in your model Destino that has an id of 5.
# views.py
class modificarVC(UpdateView):
model = Destino
template_name = "modificarVC/modificar.html"
success_url = '/'
your error message hints at problem -- your request url didn't include a 'pk' request parameter (see 'Request URL')
Destino matching query does not exist.
Request Method: GET
Request URL: http://localhost:8002/modificarVC/modificar.html
run your request again, but add the pk parameter to the end as a query parameter: http://localhost:8002/modificarVC/modificar.html?pk=42

Sleekxmpp with Django not working?

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')
...