Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Cursor Pagination with ContentType framework in List view
I'm using Django-Rest-Framework's cursor pagination class as well as Django's ContentType framework. I have some models that basically (handwriting these) look like these: from django.contrib.contentypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class CombinedModel(models.Model): id = models.UUIDField(default=uuid4(), primary_key=True) created = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = BigIntegerField() content_object = GenericForeignKey() class Amodel(models.Model): stuff = models.CharField(max_length=100) Now I want to be able to paginate the CombinedModel using a generic view set. The problem arises with the cursor pagination being unable to get the stuff data when accessing the AModel through content_object. So this is what I have for a viewset and cursor pagination so far (that is failing): from rest_framework.pagination import CursorPagination class MyObject(object): def __init__(self, content_type, object_id, stuff): self.content_type = content_type self.object_id = object_id self.stuff = stuff class MySerializer(serializer.Serializer): content_type = serializer.CharField(max_length=20) object_id = serializer.IntegerField() stuff = serializer.CharField(max_length=100) class CursorSetPagination(CursorPagination): page_size = 5 page_size_query_param = "page_size" ordering = "-created" def get_paginated_response(self, data): items = [] for x in data: model_name = x.content_type.model.capitalize() items.append(MyObject(content_type=model_name, object_id=x.object_id, stuff=x.content_object.stuff)) serializer = MySerializer(items, many=True) return Response({'results': serializer.data}) There should also be the next cursor and the number of pages left or at least the page count and current page but I can't seem to access … -
How can I import class from base.py in __init__.py in django 3.0. It seems it isn't able to set self.apps_ready while app registry
Django Version - 3.0 BaseModel - base_models/models.py # Create your models here. from django.db import models class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) base_models/__init__.py from base_models.models import BaseModel settings.py INSTALLED_APPS = [ ..., 'base_models.apps.BaseModelsConfig', ... ] Error - File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/rm-api/base_models/__init__.py", line 1, in from base_models.models import BaseModel File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/rm-api/base_models/models.py", line 6, in class BaseModel(models.Model): File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/db/models/base.py", line 107, in new app_config = apps.get_containing_app_config(module) File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/apps/registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "/Users/vaibhavsharma/vaibhav/workspace/rm-api/env/lib/python3.7/site-packages/django/apps/registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. -
Error 500 in Django production, can't see the error
i'm using django and wsgi. When i run the command runserver with DEBUG = True or False everything it's fine but when i create the daemon to run my app i got the page with 500 error, in the apache's logs i got the error 500 but i can't see the error even if the DEBUG is in True, i think it's problem with apache(2.4.41) and wsgiThis is the config file to create the daemon Alias /static /home/(user)/(domain)/static <ifmodule mod_wsgi.c> WSGIDaemonProcess ic user=(user) group=(user) processes=1 threads=2 python-path=/home/(user)/(domain):/home/(user)/.venv/ic </ifmodule> WSGIProcessGroup ic WSGIApplicationGroup ic WSGIScriptAlias / /home/(user)/(domain)/ic/wsgi.py WSGIPassAuthorization on <Directory /home/(user)/(domain)/ic/> <Files wsgi.py> Require all granted </Files> </Directory> LogLevel debug Errorlog /var/log/apache2/domlogs/(domain)_error CustomLog /var/log/apache2/domlogs/(domain)_custom combined In the errorlog show this (the venv was created) [Sat Jan 11 10:24:54.138254 2020] [ssl:debug] [pid 9308:tid 47752169862912] ssl_util_stapling.c(874): AH01956: stapling_cb: setting response [Sat Jan 11 10:24:54.316201 2020] [ssl:debug] [pid 9308:tid 47752169862912] ssl_engine_kernel.c(383): [client xxx.xxx.xxx.xxx:23440] AH02034: Initial (No.1) HTTPS request received for child 0 (server (url):443) [Sat Jan 11 10:24:54.316509 2020] [authz_core:debug] [pid 9308:tid 47752169862912] mod_authz_core.c(820): [client xxx.xxx.xxx.xxx:23440] AH01626: authorization result of Require all granted: granted [Sat Jan 11 10:24:54.316520 2020] [authz_core:debug] [pid 9308:tid 47752169862912] mod_authz_core.c(820): [client xxx.xxx.xxx.xxx:23440] AH01626: authorization result of <RequireAny>: granted [Sat Jan 11 … -
Cannot install mysqlcient: Cannot open include file: 'mysql.h'
Everytime I run the command (pip install mysqlclient) I get this error: ERROR: Command errored out with exit status 1: command: 'c:\users\nicko\envs\py1\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\nicko\\AppData\\Local\\Temp\\pip-install-av2k0hkf\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\nicko\\AppData\\Local\\Temp\\pip-install-av2k0hkf\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\nicko\AppData\Local\Temp\pip-record-dbm3hthv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\nicko\envs\py1\include\site\python3.8\mysqlclient' cwd: C:\Users\nicko\AppData\Local\Temp\pip-install-av2k0hkf\mysqlclient\ Complete output (30 lines): running install running build running build_py creating build creating build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building 'MySQLdb._mysql' extension creating build\temp.win32-3.8 creating build\temp.win32-3.8\Release creating build\temp.win32-3.8\Release\MySQLdb C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\bin\HostX86\x86\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 "-IC:\Program Files (x86)\MySQL\MySQL Connector C 6.1\include\mariadb" "-Id:\a\jan10python\new folder\include" "-Id:\a\jan10python\new folder\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.24.28314\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /TcMySQLdb/_mysql.c /Fobuild\temp.win32-3.8\Release\MySQLdb/_mysql.obj /Zl /D_CRT_SECURE_NO_WARNINGS _mysql.c MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory error: … -
Why is django context a string when returned to template?
I'm sending data (id of the selected option from a drop-down) back to my views using some ajax: $.ajax({ type: "GET", data: {'customer_select': selected_data }, success: function(data){ console.log(data) } }); I handle it in my class-based view in get_context_data(): def get_context_data(self, **kwargs): ... if 'customer_select' in self.request.GET: customer_id = self.request.GET['customer_select'] context['new_customer_id'] = customer_id return context The success function in the ajax runs console.log(data). The output is super weird - it's basically the html of my page source. I don't understand how to parse context within success. I want to be able to access new_customer_id in success. When I do console.log(typeof data) it returned string. Why is data (and by extension context) a string? -
What is the equivalent ManyToMany `through Model` on a ForeignKey?
I have the following models: class List(models.Model): pass class People(models.Model): list = models.ForeignKey(List) name = models.CharField() class Membership(models.Model): date_joined = models.DateTimeField() Here are the conditions: There can be numerous Lists There can be numerous People Each Person can only be on one List I want to record details about the person's membership of that list in a Membership model. If list.people was a ManyToMany field I would do this via through= using Membership. However this is not possible as it's a ForeignKey. What's the alternative way to set this up? -
How to save excel file using openpyxl in Django FileField?
I am using the excel file uploaded by the user, editing it using openpyxl lib and trying to save it in my FileField attribute( feeSlip here) in one my Django model named as Fee. I used this method to save my excel file. with NamedTemporaryFile() as tmp: wb.save(tmp.name) tmp.seek(0) stream = tmp.read() Fee.objects.create(regNo=reg_no, student=student, classSection=classRoom,submissionDate=date.today(), monthsPaid=months, payment_method=payment_method, amount=amount, feeSlip=stream) I'm trying to save the stream format of the file which results in error as : 'bytes' object has no attribute '_committed' -
'QuerySet' object has no attribute 'timetable_files'
I'm trying to save file in my models which I'm generating with views models.py class Timetables(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1, related_name='timetables_files', null=True) timetable_files = models.FileField( null=True, blank=True, upload_to='word_documents') views.py def schoolinput_view(request): if request.method == 'POST': worddocument = docx.Document() documenttitle = worddocument.add_heading( school_name_view.title(), 0) file_io = io.BytesIO() worddocument.save(file_io) file_io.seek(0) savedfile = Timetables.objects.filter(user=request.user) savedfile.timetable_files.save("generated_doc.docx", File(file_io)) response = HttpResponse( content_type='application/vnd.openxmlformats- officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename =quicktimetable.docx' worddocument.save(response) path = join(settings.MEDIA_ROOT, 'word_documents', 'quicktimetable. file = open(path, 'w+b') return response What am I doing wrong? -
How can I retrieve the friend_id column data of friend_user table , generated by friend model?
class Friend(models.Model): users = models.ManyToManyField(User) #following users current_user = models.ForeignKey(User, related_name='owner', null=True,on_delete=models.CASCADE) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) This model has 2 tables friends_friend having columns----- id, current_user_id friends_friend_user having columns------id ,friend_id, user_id -
Python manage.py runserver does not work with new or existing projects in my PC
rsonal\website>python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by .wrapper at 0x0000028159B61048> Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 268, in build_graph raise exc File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 242, in build_graph self.graph.validate_consistency() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20190704_0341 dependencies reference nonexistent parent node ('admin', '0003_logentry_add_action_flag_choices') -
How to set up a long running django command in google cloud
I have recently moved my site to google cloud run. The problem is I also need to move a couple of cronjobs that run a django command every day inside a container. What is the preferred way of doing this if I dont want to pay for a full kubernetes with alwasys running node instances? I would like the task to run and then spin the server down, just as Google Run does when I get an incoming request. I have searched all docs, but am having trouble in finding the correct solution for long running tasks inside containers that do not require and underlying always on server on Google Cloud... Can someone point me in the right direction? -
CSS - Display block as if buttons are present
everyone. In my django I have 2 options: I want to be list with admin/user always on the right, like in my second jpeg. My code is: <body> <div class="container2"> <div class="butts"> <form action="{% url 'catalog:redir' %}" method="post"> <button class="butt" type="submit"> <p> На главную </p> </button> </form> <div> {% if author_list.1 %} <div> <form action="{% url 'catalog:author_delete' author_list.1.id %}" method="post"> <button class="butt" type="submit"> <p> Новая раздача </p> </button> </form> </div> </div> </div> {% endif %} <div class="voted-users"> {% if author_list|length == 0 %} <p>Игра не началась</p> {% else %} {% if voted_list %} </ul> {% else %} <p>Непроголосовавшие пользователи</p> <ul> {% for i in user_list %} <p> {{ i }} <p> {% endfor %} </ul> {% endif %} {% endif %} </div> </div> </body> ------------------------------------------------------------------ .butts { display: flex; align-items: flex-start; justify-content: space-between; flex-direction: column; } .butt { display: flex; align-items: center; justify-content: center; } .container2 { width: 100%; display: flex; align-items: flex-start; justify-content: space-around; } The page is done using flexbox. Don't have any idea. It looks, like if my IF doesnt work my second div gets into first div (voted users into butts), but in the other case it doesnt happen -
how to solve maximum recursion depth exceeded while calling a Python object
File "/usr/lib/python3.7/inspect.py", line 3083, in signature return Signature.from_callablenter code heree(obj, follow_wrapped=follow_wrapped) File "/usr/lib/python3.7/inspect.py"enter code here, lienter code herene 2833, in from_callable follow_wrapper_chainenter code heres=follow_wrapped) File "/usr/lib/python3.7/inspect.py", line 2284, in _signature_from_callable return _signature_from_function(sigcls, obj) File "/usr/lib/python3.7/inspect.py", line 2154, in _signature_from_function kind=_POSITIONAL_OR_KEYWORD)) File "/usr/lib/python3.7/inspect.py", line 2469, in init self._kind = _ParameterKind(kind) File "/usr/lib/python3.7/enum.py", line 310, in call return cls.new(cls, value) File "/usr/lib/python3.7/enum.py", line 530, in new if type(value) is cls: RecursionError: maximum recursion depth exceeded while calling a Python object urls.py from django.contrib import admin from django.urls import path, include from welcome import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('mysite.urls')), ] views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("<h1>MyClub Event Calendar</h1>") -
Can I display second level up related fields in Django Admin?
Lets say I have a three tier model as below, where posts are in categories which are then in categories. I'd like to get the Posts page in the Admin panel to display both the sub category and category that each post belongs to. And ideally let me filter by both. So far I can only get the Admin panel to work up one relationship level. So I can display and filter by the sub_category but when I add the category I get an error. models.py: class Category(models.Model): name=models.CharField(max_length=10) def __str__(self): return self.name class Subcategory(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE,null=True) name=models.CharField(max_length=10) def __str__(self): return self.name class Posts(models.Model): title=models.CharField(max_length=15) sub_category=models.ForeignKey(Subcategory,on_delete=models.CASCADE,null=True) def __str__(self): return self.title Admin.py: class PostsAdmin(admin.ModelAdmin): ordering = ('name',) list_display = ('name','id','sub_category', 'sub_category__category.name', ) exclude = ('sort',) list_filter = ['sub_category','sub_category__category'] search_fields = ['name'] admin.site.register(Posts, PostsAdmin) Error is something like this: <class 'journal.admin.PostsAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'sub_category__category', which is not a callable, an attribute of 'PostsAdmin', or an attribute or method on 'journal.Admin'. -
not sure what to put in action attribute in form
This code is for my signup page as you can see action is set for signup {% block content %} <form class="form-horizontal" action="signup" method="post"> {% csrf_token %} {{ form }} <br /> <input type="submit" value="Sign up" class="btn btn-default" /> </form> {% endblock %} This is my views.py in the same app def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('app:home') # log the user in else: form = UserCreationForm() return render(request, 'accounts/signup.html', {'form': form}) This is my url for which doesn't work path('signup/', accounts_views.signup, name='signup') -
'Charss' object has no attribute 'get'
i am new on django and i have this problem in the title 'Charss' object has no attribute 'get' this is my code class Charss(View): def __init__(self,data): self.data = models.Chars.objects.using('Chars').filter(del_field = 0) def ppop(request,self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1',1433)) if result == 0: msg = 'ON' return render(request, 'CharsAccount.html',{'msg':msg}) else: msg ='OFF' return render(request, 'CharsAccount.html',{'msg':msg}) def CharsAccount(request,self): return render(request, 'CharsAccount.html',{'data':self.data}) sorry for my bad english -
How to pick up html IDs from auto generated elements in Django formset using jQuery
In some of my pages I am using Django inline formset. Where I am setting the auto_id = True, the element ids are generated quite conveniently. In one case I need to pick up the auto generated id during runtime when the element gets focus. I have tried a something like this: $('#items td').on('focusin', function() { elemID = $(this).id; }); But I am getting no result (undefined). In the html codes the id is nicely lined up: <input type="text" ......id="abc-1-xyz" class="......> However for manually generated id tags, the above code works perfectly. Can somebody guide me as how I may get the element's id? -
Joining 3 tables in a query in python django
I checked for multiple solutions and other questions here but nothing seems to help me. models.py class Project(models.Model): completed =models.BooleanField(default=False) project_name = models.CharField(max_length=200) def __str__(self): return self.project_name class Team(models.Model): teamName = models.CharField(max_length=200) employee = models.ForeignKey(Employee, on_delete=models.CASCADE) def __str__(self): return self.teamName class TeamProjectList(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) views.py def team_projects(request): team_project = TeamProjectList.objects.all().select_related('project').select_related('team') return render(request, 'myteam.html', {'team_project':team_project}) html code {% for team_project in team_projects %} <p> {{ team_project.project.project_name }} </p> <p> {{ team_project.team.teamName }} </p> {% endfor %} I'm sure I've made a mistake, no errors pop up but nothing is displayed either. I want to simply list all teams and their projects. -
How to get the friend id from the model
I have made a model for making friends on django. I am unable to extract the friend id from the tables made from the following model. class Friend(models.Model): users = models.ManyToManyField(User) #following users current_user = models.ForeignKey(User, related_name='owner', null=True,on_delete=models.CASCADE) #followers @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user = current_user ) friend.users.remove(new_friend) Kindly help me to extract the required id -
How to convert Django datetime to HighCharts format
I am trying to display datetime on a chart but having some trouble as it seems to be putting out an odd format to the chart. Django template: var employeeLastLoginWithPoints = [ {% for employee in employee_list %} [{{ employee.last_login|date:"SHORT_DATE_FORMAT" }}, {{ employee.points }}] {% if not forloop.last %}, {% endif %}{% endfor %} ]; Highcharts snippet: xAxis: { type: "datetime", dateTimeLabelFormats: { day: '%b/%d/%Y' }, What the chart looks like: All the date data is pushed to the left at Jan/01/1970 Sources/Index of the DOM: var employeeLastLoginWithPoints = [ [01/11/2020, 0] , [01/07/2020, 3] , [01/11/2020, 14] , [01/08/2020, 8] ]; console.log(employeeLastLoginWithPoints): (4) [Array(2), Array(2), Array(2), Array(2)] 0: (2) [0.000045004500450045, 0] 1: (2) [0.00007072135785007072, 3] 2: (2) [0.000045004500450045, 14] 3: (2) [0.00006188118811881188, 8] Why is the console log showing up different and how do I get it to display correctly? Thanks in advance! -
Dialogflow chatbot integration with Dialogflow
I have been following google codelab's exercise to integrate dialogflow chatbot with django web app and deploy it on google cloud platform. But I am unable to do so. Please help me out as I am fairly new to all of these and I have been trying a lot to solve the issues but nothing happened. Link to the Codelab: Create Front-end Django Client for Dialogflow Application My app's views.py file: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import JsonResponse from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.http import require_http_methods import dialogflow import os import json from django.views.decorators.csrf import csrf_exempt #from dialogflow_v2 import dialogflow_v2 as Dialogflow # Create your views here. @require_http_methods(['GET']) def index_view(request): return render(request, 'home.html') def convert(data): if isinstance(data, bytes): return data.decode('ascii') if isinstance(data, dict): return dict(map(convert, data.items())) if isinstance(data, tuple): return map(convert, data) return data @csrf_exempt @require_http_methods(['POST']) def chat_view(request): print("FIRST STOP") print('Body', request.body) input_dict = convert(request.body) input_text = json.loads(input_dict)['text'] GOOGLE_AUTHENTICATION_FILE_NAME = "project_on_gcp.json" current_directory = os.path.dirname(os.path.realpath(__file__)) path = os.path.join(current_directory, GOOGLE_AUTHENTICATION_FILE_NAME) os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = path GOOGLE_PROJECT_ID = "project_id" session_id = "1234567891" context_short_name = "does_not_matter" context_name = "projects/" + GOOGLE_PROJECT_ID + "/agent/sessions/" + session_id + "/contexts/" + \ context_short_name.lower() parameters = dialogflow.types.struct_pb2.Struct() #parameters["foo"] = "bar" … -
Django and Bootstrap Forms
I'm trying to bind a bootstrap contact form with the Django backend. I tried searching for answers/solutions on the internet but all I get is the suggestion to create a Django form and Bootstrap it. Currently, I like the form that I have and it fits quite nicely with my website. Are there any resources that can be recommended to look at in order to do achieve this? Kind Regards, -
Generate multiple PDFs and zip them for download, all in a single view
I am using xhtml2pdf to generate PDFs in my Django View. The idea is to loop over all the instances that are there in the query, then for each instance create a PDF, then add all the generated PDFs to one zip File for download. The xtml2pdf logic is working okay but the looping logic is what gives me headache. So this is my function so far: def bulk_cover_letter(request, ward_id, school_cat_id, cheque_number): school_type = SchoolType.objects.get(id=school_cat_id) schools_in_school_type = Applicant.objects.filter( school_type=school_type, ward_id=ward_id, award_status='awarded' ).order_by().values_list('school_name', flat=True).distinct() for school in schools_in_school_type: beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school) total_amount_to_beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).aggregate(total=Sum('school_type__amount_allocated')) context = { 'school_name' : school, 'beneficiaries' : beneficiaries, 'total_amount_to_beneficiaries' : total_amount_to_beneficiaries, 'title' : school + ' Disbursement Details', 'cheque_number': cheque_number } response = HttpResponse('<title>Cover Letter</title>', content_type='application/pdf') filename = "%s.pdf" %(cheque_number) content = "inline; filename=%s" %(filename) response['Content-Disposition'] = content template = get_template('cover_letter.html') html = template.render(context) result = io.BytesIO() pdf = pisa.CreatePDF( html, dest=response, link_callback=link_callback) if not pdf.error: # At this point I can generate a single PDF. # But no idea on what to do next. # The zipping logic should follow here after looping all the instances - (schools) From that Point I have no idea on what to do … -
Why can't i use static css files?
I'm currently creating django project in pycharm, I was trying to use bootstrap example https://getbootstrap.com/docs/4.4/examples/blog/ but it refused to work. I created static directory inside my app and put the css files needed for the example to work. I used {% static %} to reference the css files in the template: <link rel="stylesheet" href="{% static 'blogs/bootstrap.min.css' %}" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'blogs/blog.css' %}" rel="stylesheet"> but the output was https://imgur.com/a/yRfY5bC instead of https://getbootstrap.com/docs/4.4/examples/blog/ However when i put the direct links to the css files: <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="https://getbootstrap.com/docs/4.4/examples/blog/blog.css" rel="stylesheet"> it worked just well. The css files were properly detected by django when i used the static method: [11/Jan/2020 16:16:33] "GET / HTTP/1.1" 200 13290 [11/Jan/2020 16:16:33] "GET /static/blogs/bootstrap.min.css HTTP/1.1" 200 159521 [11/Jan/2020 16:16:33] "GET /static/blogs/blog.css HTTP/1.1" 200 1781 [11/Jan/2020 16:16:33] "GET / HTTP/1.1" 200 13290 [11/Jan/2020 16:22:07] "GET / HTTP/1.1" 200 13365 -
UNIQUE constraint failed: auth_user.username integrityError
im getting this error when i want that the username not be repeated in my django form. i saw a lot of this situations here in stackoverflow but it seems that every situation is unique. every time that i want to create a new user the error pops out and i dont know why i review my code but i have no idea where could be the error. i hope that someone could help me with this error. regrets forms.py from django import forms from django.contrib.auth.models import User class RegisterForm(forms.Form): username = forms.CharField(required=True, min_length=4, max_length=50, widget=forms.TextInput(attrs={ 'class': 'form-control', 'id': 'username'})) email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={ 'class': 'form-control', 'id': 'email', 'placeholder': 'example@hotmail.com'})) password = forms.CharField(required=True, widget= forms.PasswordInput(attrs={ 'class': 'form-control'})) def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): raise forms.ValidationError('El username ya esta en uso') return username def clean_email(self): username = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError('El email ya esta en uso') return username views.py from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages from django.contrib.auth import login from django.contrib.auth import logout from django.contrib.auth import authenticate from django.contrib.auth.models import User from .forms import RegisterForm def index(request): return render(request, 'index.html', { 'message': 'Listado De Productos', 'title': 'Productos', 'products': [ {'title': 'Playera', 'price': 5, …