i am learning Django tutorial, could you pls advise me how to edit cod to get search result to put into database? Below are my cod and sure that the rest of cod in this tutorial i did correctly and test complete, many thanks
I have updated the code as per your request. The result on home page fail is also attached at the bottom of the question section. If you have any additional question, please ask and I will be able to share.
def __str__(self):
"""Returns a string representation of a message."""
date = timezone.localtime(self.log_date)
return f"'{self.message}' logged on {date.strftime('%A, %d %B, %Y at %X')}"
class HomeListView(ListView):
"""Renders the home page, with a list of all messages."""
model = LogMessage
def get_context_data(self, **kwargs):
context = super(HomeListView, self).get_context_data(**kwargs)
return context
def log_message(request):
form = LogMessageForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
query = form.save(commit=False)
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0):
message = LogMessage(log_date = datetime.now(), message =j)
message.save()
return redirect("home")
else:
return render(request, "hello/log_message.html", {"form": form})
--- HOME PAGE FAIL INFO
TypeError at /log/
quote_from_bytes() expected bytes
Request Method: POST
Request URL: http://127.0.0.1:8000/log/
Django Version: 3.1.5
Exception Type: TypeError
Exception Value:
quote_from_bytes() expected bytes
Exception Location: C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\urllib\parse.py, line 866, in quote_from_bytes
Python Executable: C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\python.exe
Python Version: 3.8.7
Python Path:
['D:\\Apps\\07.1\\hello_django',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\lib',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32',
'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages']
Server time: Thu, 07 Jan 2021 14:38:11 +0000
Traceback Switch to copy-and-paste view
C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py, line 47, in inner
response = get_response(request) …
▶ Local vars
C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) …
▶ Local vars
D:\Apps\07.1\hello_django\hello\views.py, line 34, in log_message
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0): …
▼ Local vars
Variable Value
form
<LogMessageForm bound=True, valid=True, fields=(message)>
query
<LogMessage: '333321212121121221' logged on Thursday, 07 January, 2021 at 14:38:11>
request
<WSGIRequest: POST '/log/'>
Try the code below:
for j in search(query, tbs='qdr:h', num=10, start=0, stop=10, pause=2.0):
message = LogMessage(log_date = datetime.now(), message =j)
message.save()
Related
I am learning Djnago and
I have this function inside admin.py that counts how many participants in an activity, it is working fine until, I want to know if the current user is a superuser and added request inside def set_count(self, request, obj) expecting to make a request for the user. Since I am getting an error, this means, this it's not how to do it and wrong. How to correct this? Thanks.
Below is what I want to do, evaluate the user.is_superuser if true, it will display in the list_display the link to the participants_changelist otherwise, display a plain text.
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(set_count=Count('activity_activity'))
return queryset
def set_count(self, request, obj):
counter = obj.set_count
if request.user.is_superuser:
url = (
reverse("admin:activity_announcements_participants_changelist")
+ "?"
+ urlencode({"activity__id": f"{obj.id}"})
)
return format_html('{} Paticipants', url, counter)
else:
counter = obj.set_count
return format_html('{} Paticipants', counter)
set_count.short_description = "No. of Paticipants"
Error:
TypeError at /admin/activity_announcements/activity/
ActivityAdmin.set_count() missing 1 required positional argument: 'obj'
Request Method: GET
Request URL: http://localhost:8000/admin/activity_announcements/activity/
Django Version: 4.1.5
Exception Type: TypeError
Exception Value:
ActivityAdmin.set_count() missing 1 required positional argument: 'obj'
Exception Location: /py/lib/python3.11/site-packages/django/contrib/admin/utils.py, line 280, in lookup_field
Raised during: reversion.admin.changelist_view
Python Executable: /py/bin/python
Python Version: 3.11.1
Python Path:
['/app',
'/usr/local/lib/python311.zip',
'/usr/local/lib/python3.11',
'/usr/local/lib/python3.11/lib-dynload',
'/py/lib/python3.11/site-packages',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf',
'/py/lib/python3.11/site-packages/odf']
Server time: Sun, 22 Jan 2023 03:06:22 +0800
The problem is that when defining a custom field to list in the admin, you don't have access to the request. The function definition should be like this def your_field(self, obj): . In order to get the request in a field definition you can do the following:
class YourAdmin(admin.modeladmin):
def get_queryset(self, request):
self.request = request
return super().get_queryset(request)
def set_count(self, obj):
counter = obj.set_count
if self.request.user.is_superuser:
url = (
reverse(
"admin:activity_announcements_participants_changelist")
+ "?"
+ urlencode({"activity__id": f"{obj.id}"})
)
return format_html('{} Participants', url, counter)
else:
counter = obj.set_count
return format_html('{} Participants', counter)
set_count.short_description = "No. of Paticipants"
Error:
TypeError: loadshortlink() got multiple values for argument 'shortlink'
My urls.py:
path('s/<str:shortlink>',views.loadshortlink, name="get_longlink")
views.py:
def loadshortlink(shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'
When I visit the url: http://127.0.0.1:8000/s/4nI
I get the error:
Internal Server Error: /s/4nI
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: loadshortlink() got multiple values for argument 'shortlink'
Why is this happening?
First argument of view function should be request. You need to add it to loadshortlink:
def loadshortlink(request, shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
Actually, it is not able to handle the request because loadshortlink method is missing request parameter. Your code should be:
def loadshortlink(request, shortlink):
print("Translating short link %s" % shortlink)
link = get_longlink(shortlink)
return render(request, 'shortlinks/openlong.html', {
'link': link
})
def get_longlink(shortlink):
print('Short link is %s' % shortlink)
links = Links.objects.filter(shortlink=shortlink)
if len(links)>1 or len(links)==1:
link = links[0].longlink
return link
else:
return 'No matched long links'
In my project, I have a model, Project, that when saved creates another model, Access, which contains a manytomanyfield, access_list, where users can add other users onto their project as collaborators. It works - when I create a new project, I can add additional users into it, but if I add a 2nd user, it will no longer serve the page with the error,
Exception Value: get() returned more than one Access -- it returned 2!"
If I switch to an account I've added to the project, then add other users on with that account, they add fine and it does not break the page.
When the page breaks, it also creates an additional instance of the project on my Projects page, even though there's only one instance of the project in the database.
My code:
Models.py:
class Project(models.Model):
created_by = models.ForeignKey(User)
super(Project, self).save()
Access.objects.get_or_create(project=self)
class Access(models.Model):
project = models.ForeignKey(Project)
access_list = models.ManyToManyField(User)
pubdate = models.DateTimeField(default=timezone.now)
Views.py:
#login_required
def access(request, project_id=1):
thisuser = request.user
if Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser), project__id=project_id).exists():
accesspermission = Access.objects.filter(Q(access_list=thisuser) | Q(project__created_by=thisuser), project__id=project_id).order_by('-project__project_pubdate')[0]
else:
accesspermission = None
if Entry.objects.filter(project_id=project_id).exists():
anyentries = Entry.objects.filter(project_id=project_id, entry_unique=1).order_by('-entry_pubdate')[0]
else:
anyentries = None
if Entry.objects.filter(project_id=project_id, entry_unique=1).exists():
firstentry = Entry.objects.filter(project_id=project_id, entry_unique=1).order_by('-entry_pubdate')[0]
else:
firstentry = None
if Entry.objects.filter(project_id=project_id).exists():
lastentry = Entry.objects.filter(project_id=project_id).order_by('-entry_pubdate')[0]
lastentrynumber = lastentry.entry_unique
else:
lastentrynumber = None
if request.method == "POST":
form = AddAccessForm(request.POST)
if form.is_valid():
p = form.save(commit=False)
adduserfromform = p.accessupdate
if User.objects.filter(username=adduserfromform).exists():
usertoadd = User.objects.get(username=adduserfromform)
projecttoadd = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]
projecttoadd.access_list.add(usertoadd)
else:
usertoadd = None
removeuserfromform = p.accessremove
if User.objects.filter(username=removeuserfromform).exists():
usertoremove = User.objects.get(username=removeuserfromform)
projecttoremove = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]
projecttoremove.access_list.remove(usertoremove)
else:
usertoremove = None
form.save()
return HttpResponseRedirect('/projects/get/%s/access' % project_id)
Traceback:
Traceback (most recent call last):
File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py", line 22, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/webapps/filmeditdb/filmeditdb/docproject/views.py", line 284, in access
def access(request, project_id=1):
File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/db/models/manager.py", line 151, in get
return self.get_queryset().get(*args, **kwargs)
File "/webapps/filmeditdb/local/lib/python2.7/site-packages/django/db/models/query.py", line 310, in get
(self.model._meta.object_name, num))
MultipleObjectsReturned: get() returned more than one Access -- it returned 2!
2014-03-25 22:48:26 [17264] [INFO] Handling signal: winch
2014-03-25 22:48:26 [17264] [INFO] SIGWINCH ignored. Not daemonized
Adding a full traceback is generally recommeded, but from the error shown the issue is most likely on this line:
projecttoremove = Access.objects.get(project__id=project_id).order_by('-project__project_pubdate')[0]
Djangos get() always expects to return only 1 object. If there is 0 objects, it throws a DoesNotExist exception if there is more than 0, it throws MultipleObjectsReturned Exception.
Change that line to match the earlier line here:
projecttoadd = Access.objects.filter(project__id=project_id).order_by('-project__project_pubdate')[0]
Failing this, identify the erroneous call. The exception you are getting is quite clear.
At some point in the code, you are calling Access.objects.get() with some parameters and it is finding 2 objects instead of 1. Either fix the parameters, or moer likely switch it to use filter().
From my view, I am simply returning
context = {'message':'Request Accepted'}
return HttpResponse(context)
I am calling this view with AJAX call and its returning Http 500
with error message
KeyError at /routes/AcceptRequest/
'status'
Request Method: POST
when i try to stringify the response in javascript it gives :
{"readyState":4,"responseText":"KeyError at /routes/AcceptRequest/\n'status'\n\nRequest Method: POST\nRequest URL: http://localhost:8000/routes/AcceptRequest/\nDjango Version: 1.4\nPython Executable: /home/subodh/joinwheelsv6/env/bin/python\nPython Version: 2.7.3\nPython Path: ['/home/subodh/joinwheelsv6/env/joinwheels', '/home/subodh/joinwheelsv6/env/lib/python2.7/site-packages/PIL-1.1.7-py2.7-linux-x86_64.egg', '/home/subodh/joinwheelsv6/env/lib/python2.7', '/home/subodh/joinwheelsv6/env/lib/python2.7/plat-linux2', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-tk', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-old', '/home/subodh/joinwheelsv6/env/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages', '/home/subodh/joinwheelsv6/env/lib/python2.7/site-packages']\nServer time: Thu, 17 Oct 2013 15:48:36 +0530\nInstalled Applications:\n('django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'django.contrib.admindocs',\n 'south',\n 'account',\n 'socialaccounts',\n 'routes',\n 'Groups')\nInstalled Middleware:\n('django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware')\n\nTraceback:\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/core/handlers/base.py\" in get_response\n 111. response = callback(request, *callback_args, **callback_kwargs)\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/views/generic/base.py\" in view\n 48. return self.dispatch(request, *args, **kwargs)\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/views/generic/base.py\" in dispatch\n 69. return handler(request, *args, **kwargs)\nFile \"/home/subodh/joinwheelsv6/env/joinwheels/routes/views.py\" in post\n 1157. return HttpResponse(response['Status'])\nFile \"/home/subodh/joinwheelsv6/env/local/lib/python2.7/site-packages/django/http/__init__.py\" in __getitem__\n 615. return self._headers[header.lower()][1]\n\nException Type: KeyError at /routes/AcceptRequest/\nException Value: 'status'\nRequest information:\nGET: No GET data\n\nPOST:\ncsrfmiddlewaretoken = u'Dxm5R7omqawuGtJ2v8AuOGsDXXdTCXCa'\nRequestID = u'7'\n\nFILES: No FILES data\n\nCOOKIES:\ncsrftoken = 'Dxm5R7omqawuGtJ2v8AuOGsDXXdTCXCa'\nsessionid = '139167c44021568cf40311753e0480fc'\n\nMETA:\nwsgi.version = \nwsgi.multiprocess = False\nRUN_MAIN = 'true'\nHTTP_REFERER = 'http://localhost:8000/account/TravelCard/Ride/2059/7/'\nGNOME_DESKTOP_SESSION_ID = 'this-is-deprecated'\nSERVER_PROTOCOL = 'HTTP/1.1'\nSERVER_SOFTWARE = 'WSGIServer/0.1 Python/2.7.3'\nSCRIPT_NAME = u''\nLESSOPEN = '| /usr/bin/lesspipe %s'\nREQUEST_METHOD = 'POST'\nLOGNAME = 'subodh'\nUSER = 'subodh'\nHTTP_ORIGIN = 'http://localhost:8000'\nPATH = '/home/subodh/joinwheelsv6/env/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'\nQUERY_STRING = ''\nGNOME_KEYRING_CONTROL = '/tmp/keyring-KIXbNa'\nPS1 = '(env)\\\\[\\\\e]0;\\\\u#\\\\h: \\\\w\\\\a\\\\]${debian_chroot:+($debian_chroot)}\\\\u#\\\\h:\\\\w\\\\$ '\nDISPLAY = ':0'\nSSH_AGENT_PID = '2016'\nLANG = 'en_IN'\nTERM = 'xterm'\nSHELL = '/bin/bash'\nXDG_SESSION_PATH = '/org/freedesktop/DisplayManager/Session0'\nXAUTHORITY = '/home/subodh/.Xauthority'\nLANGUAGE = 'en_IN:en'\nSESSION_MANAGER = 'local/dell:#/tmp/.ICE-unix/1981,unix/dell:/tmp/.ICE-unix/1981'\nSHLVL = '1'\nMANDATORY_PATH = '/usr/share/gconf/ubuntu.mandatory.path'\nwsgi.url_scheme = 'http'\nCOMPIZ_CONFIG_PROFILE = ...
Well, you seem to be doing something else that you haven't explained. From your error, cleaned up slightly:
File "/home/subodh/joinwheelsv6/env/joinwheels/routes/views.py" in post
1157. return HttpResponse(response['Status'])
So you have some code in views.py that is looking for a Status field that doesn't exist. Of course, we have no idea why.
Change the return line:
import json
return HttpResponse(json.dumps(context))
I'm trying to implement a progress bar in Django, I'm taking references from this code snippet I found http://djangosnippets.org/snippets/2898/ but my efforts are in vane because I don't know what happening but the task_idfor celery is always null when executes the method task, that's my code:
def add_categoria(request):
if request.POST:
form_cat = CategoriaModelForm(request.POST,request.FILES)
if form_cat.is_valid():
file = request.FILES['imagen']
job = upload_image_categoria(request).delay()
request.session['task_id'] = job.id
return HttpResponse(json.dumps({'task_id':job.id}))
else:
return HttpResponseBadRequest(json.dumps(form_cat.errors),
mimetype="application/json")
else:
form = CategoriaModelForm()
return render_to_response("ventas/form.html",{'form':form},context_instance=RequestContext(request))
#task()
def upload_image_categoria(request):
form = CategoriaModelForm(request.POST, request.FILES)
path = MEDIA_ROOT+'/categorias/%s' % form.cleaned_data['imagen'].name
file = request.FILES['imagen']
destination = open(path, 'wb+')
porcentaje = 0
acum = 0
for chunk in file.chunks():
time.sleep(0.1)
current_task.update_state(state='PROGRESS', meta={'current': porcentaje})
acum += len(chunk)
porcentaje = int((acum*100)/file.size)
destination.write(chunk)
#csrf_exempt
def upload_state(request):
""" A view to report the progress to the user """
data = 'Fail'
if request.is_ajax():
if 'task_id' in request.POST.keys() and request.POST['task_id']:
task_id = request.POST['task_id']
task = AsyncResult(task_id)
data = task.result or task.state
else:
data = 'No task id'
else:
data = 'This is not an ajax request'
json_data = json.dumps(data)
return HttpResponse(json_data, mimetype='application/json')
So, when I report the state of progress bar in upload_image_categoria at current_task.update_state(state='PROGRESS', meta={'current': porcentaje}) always I get this Traceback:
Traceback:
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
115. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
25. return view_func(request, *args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in add_categoria
446. job = upload_image_categoria(request).delay()
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in __call__
330. return self.run(*args, **kwargs)
File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in upload_image_categoria
462. current_task.update_state(state='PROGRESS',meta={'current': i, 'total': 100})
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in update_state
695. self.backend.store_result(task_id, meta, state)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/base.py" in store_result
282. self._store_result(task_id, result, status, traceback, **kwargs)
File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/amqp.py" in _store_result
128. routing_key=task_id.replace('-', ''),
Exception Type: AttributeError at /ventas/categorias/add/
Exception Value: 'NoneType' object has no attribute 'replace'
That's my settings.py for celery options:
BROKER_URL = "amqp://guest#localhost:5672//"
CELERY_IMPORTS = ("ventas.forms",)
CELERY_TRACK_STARTED = True
CELERY_RESULT_BACKEND = "amqp"
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
CELERY_RESULT_DBURI = "mysql://root#localhost/dgp"
So I don't know what's happening, worker is correctly, settings (I guess, is correctly) and always I get the same, I prove in some other projects with the same settings (this project particularly http://iambusychangingtheworld.blogspot.com.es/2013/07/django-celery-display-progress-bar-of.html) and it works perfectly so I don't know why here not, something I'm missing? Any ideas would be appreciate.
Regards!