Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with loading static files on Django
I'm using Django 3.0.3 and Python 3.7.6. I followed Django documentation on https://docs.djangoproject.com/en/3.0/howto/static-files/ but I can't find out what's wrong. Directory: project_name -app_name -static -css -main.css -js ... -project_name ... -settings.py settings.py: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', ] ... STATIC_URL = '/static/' When I try to use static files in my templates: {% load static %} <link rel="stylesheet" href="{% static "css/main.css" %}"> pycharm shows unresolved template reference '"css/main.css"' terminal shows "GET /static/css/animate.css HTTP/1.1" 404 1671 -
key values of dictionary is not showing in html by django
I just start learning Django and I came across this problem in which my key values "hello world" of a key "hello" is not showing in the HTML page, I hope you guys help me to understand this code homepage.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>this is html page</h1> {{ hello }} </body> </html> urls.py from django.urls import path import view urlpatterns = [ path('',view.homepage), ] view.py from django.http import HttpResponse from django.shortcuts import render def homepage(request): return render(request, "homepage.html", {'hello':'hello world'}) -
I want to generate PDF using Reportlab
Currently I am using Weasyprint to generate my PDFs and want to try using reportlab, How do I edit my current codes to use reportlab instead of weasyprint? Thank you! from django.http import HttpResponse from django.template.loader import render_to_string from weasyprint import HTML import tempfile def generate_report(request, test_id): #somethings here html = render_to_string(f'{lang}.html', { 'some': some.where }) html = HTML(string=html) result = html.write_pdf() # Creating http response response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = f'attachment; filename={test.test_taker.name}.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') response.write(output.read()) return response -
Django OAuth Toolkit - AttributeError: get_full_path
I'm trying to setup the token authentication but when I try to get a token, i get this error. Endpoint is '/o/token/'. When i POST a wrong client_id or a wrong grant_type, i receive the response i expect: { "error": "invalid_client" } or { "error": "unsupported_grant_type" } But when sending the actual data (grant_type, client_id, username, password) it crashes: Internal Server Error: /o/token/ Traceback (most recent call last): File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/views/base.py", line 260, in post url, headers, body, status = self.create_token_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/views/mixins.py", line 124, in create_token_response return core.create_token_response(request) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauth2_provider/oauth2_backends.py", line 145, in create_token_response headers, extra_credentials) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/base.py", line 116, in wrapper return f(endpoint, uri, *args, **kwargs) File "/home/ben/.local/share/virtualenvs/riven-Lpl_ShSG/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/endpoints/token.py", line 119, in create_token_response … -
django: ManyToMany: Upating and Insert Business rules
Note: New to django. Doing my with project with it. So I certainly lack many understand and the answer could be trivial. I have a ManyToMany relationship. I have trouble coming up with an analogy but on the "main" side we have a container which contains one or more items. In my case the items aren't "real" things but more like a "template" and templates are unique. This is the background. The business rules are that changes only happen and are initiated on the container side. So the form shows a container an it's items. A user can change one of the items. If an item in a container changes, the item instance (row in database) must not change, as said, it's a template used in many other containers. So the logic must be that if a user changes an item, a lookup is done if it already exists and if yes, instead of updating the current item, reuse the existing one. If it doesn't exist, create a new one and use that. But under no circumstance should the existing one be changed. How and where (at which level) can I achieve this? I would really like to keep this … -
Finding the reason for "Failed to load resource: the server responded with a status of 500"
I am facing an issue in my live website. The stack I am using is Django, Postgresql, Celery, Gunicorn and Nginx in a ubuntu server. And the server has 2vCpus, 4GB of Ram, 25 GB SSD and 4TB data transfer, ubuntu 18. The situation in details - I have a website where user can upload image and after that server starts a task in background using celery and returns the task id to client. From client side, an ajax request starts which sends request to the server every 5 sec to check on the task. When we were trying to stress test the site using about 40 client uploading about 10 images each total 400 images at the same time (uploading an image is in an ajax function) then some results were successful but after some time the remaining ones failed. The error that is given on the console is: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Then I checked my server log and the result of "journalctl -u gunicorn" of that time: Mar 11 09:42:42 ubuntu-** gunicorn[17308]: - - [11/Mar/2020:09:42:42 +0000] "POST /upload/ HTTP/1.0" 500 27 "https:***" "Mozilla/5.0 (X11; Linux x86_64) … -
How to solve this problem? list indices must be integers or slices, not str
I would like to thanks to those people who want to help me in this problem, since no one answer my question here https://stackoverflow.com/users/12951147/mary?tab=bounties even it have bounty, btw its not the same question I just don't know how to figure this problem, and I’m completely stuck with this error, I am selecting a marked(selection box) for every student and for every core values then sending all data back to the database. I hope guys you can help me with this. this is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in behaviorperlevel %} <td colspan="8"><input type="text" value="{{core.id}}" name="core">{{core.Grading_Behavior__Name}}</td> {% endfor %} </tr> <tr> {% for corevalues in behaviorperlevels %} <td colspan="4" style="font-size: 12px"><input type="text" value="{{corevalues.id}}" name="coredescription">{{corevalues.Grading_Behavior.GroupName}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student name</td> {% for corevalues in behaviorperlevels %} <td colspan="4" style="font-size: 12px"><input type="text" value="{{corevalues.id}}" name="period">Q {{corevalues.Grading_Period.id}}</td> {% endfor %} </tr> {% for student in Students %} <tr> <td colspan="2"><input type="text" value="{{student.id}}" name="student">{{student.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td colspan="4"> <select name="Marking"> {% for behaviors in behavior %} <option value="{{behaviors.id}}">{{behaviors.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> <select name="Marking"> {% for behaviors in behavior %} … -
The current path, accounts/signup/index.html, didn't match any of these
After filling the signup form, I want to redirect my page to the post_list page of my blog. But I am getting the error as stated above. Below are my different files. accounts is app for managing the accounts and blog_app is app for managing other blog related activities. Blog is the root app. In Blog: urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.contrib.auth import views urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog_app.urls')), url(r'^accounts/',include('accounts.urls')), path('accounts/login/', views.LoginView.as_view(template_name='blog_app/login.html'),name='login'), path('accounts/logout/',views.LogoutView.as_view(template_name='blog_app/base.html'),name='logout'), ] In accounts: views.py: from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm def signup_view(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() # log the user in return redirect('blog_app:post_list') else: form = UserCreationForm() return render(request,'accounts/signup.html',{'form':form}) urls.py: from django.conf.urls import url from .import views app_name = 'accounts' urlpatterns = [ url(r'^signup/$', views.signup_view, name = "signup"), ] signup.html: {% extends 'base.html' %} {% block content %} <h1>Signup</h1> <form class="site-form" action="/accounts/signup/" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Signup"> </form> {% endblock %} in blog_app: urls.py: from django.conf.urls import url from blog_app import views from django.urls import path app_name = 'blog_app' urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^about/$', views.AboutView.as_view(),name='about'), url(r'^post/(?P<pk>\d+)$', views.PostDetailView.as_view(),name='post_detail'), url(r'^post/new/$', views.CreatePostView.as_view(),name='new_post'), url(r'^post/(?P<pk>\d+)/edit/$', views.UpdatePostView.as_view(),name='edit_post'), url(r'^drafts/$', … -
Why Django think OR is complex?
I read some model operation from Django's document, and find this I'm curious that OR in WHERE is just basic concept, why Django think it's a complex query? -
cannot add panel to openstack django horizon
I tried to add panel openstack compute panel group but it's not working I do manually python package because toe is not working here is my mypanel tree enter image description here panel.py from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.project import dashboard class Testpanel(horizon.Panel): name = _("Testpanel") slug = "mypanel.testpanel" permissions = ('openstack.project.compute', 'openstack.roles.admin') policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:get_all")),) dashboard.Project.register(Testpanel) _12221_project_mypanel_test_panel.py from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.project import dashboard class Testpanel(horizon.Panel): name = _("Testpanel") slug = "mypanel.testpanel" permissions = ('openstack.project.compute', 'openstack.roles.admin') policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:get_all")),) dashboard.Project.register(Testpanel) I can't not see mypanel on compute panel group /project dashboard What am I miss?? I just want to see mypanel name on dashboard -
How to create CRUDL API is using python for Automation Test Framework for servicenow?
I am trying to create a new python CRUDL API for the automated testing framework of ServiceNow using the fastAPI library in python. am stuck for the process. please help me with this task anyone -
Django template find <input> 'checked' attr use template tags
this is my template {% if field|is_checkbox_input %} <label {% if field.field.checked %}active{% endif %} {% if field.field.disabled %}disabled{% endif %}">{{ field }}</label> {% endif %} I wanna get the checked & disabled attribute {% if field.field.disabled %}disabled{% endif %} is working but {% if field.field.checked %}active{% endif %} not, what am i doing wrong? -
Djongo FAILED SQL: INSERT INTO \<TABLENAME>
I'm new to the Django Framework and I am using Djongo connector to connect to the MongoDB backend database. When I try to insert a large dictionary i run into a error and i am unable to insert the record in MongoDB. I will be adding a condensed version of the code here. My model.py is given below, i am using the binary field to store the dictionary. from djongo import models as MongoModel class QuickInsights(MongoModel.Model): ChartAttributesData = MongoModel.BinaryField(blank=True) This is what my view.py looks like. def Save(request): try: InsightDocument = QuickInsights.objects.create( ChartAttributesData=request.data.get("ChartAttributesData") MongoId = request.data.get("MongoID") UserID = request.data.get("UserID") ) InsightDocument.save() return Response(status.HTTP_200_OK) except ValueError as e: return Response(e.args[0], status.HTTP_400_BAD_REQUEST) My dictionary is roughly around 30K lines after beautifying/formatting. I can comfortably insert large data to MongoDB via it's shell, but i have an issue while doing the same from Django with the Djongo connector. Is it because of the Model Binary field or the Djongo connector cannot process it? -
Set azure blob in open edx MEDIA_ROOT and MEDIA_URL
I have installed open edx in two different machines, and access by the load balancer. I have configured the Scorm xblock https://github.com/raccoongang/edx_xblock_scorm in open edx. I want to upload scorm in azure blob so both machine access. My configuration in lms.env.json and cms.env.json "AZURE_ACCOUNT_KEY":"xxxxxxxxxxxxxxxxxxxxxxxxxxxx", "AZURE_ACCOUNT_NAME": "myedx", "AZURE_CONTAINER": "edx", "DEFAULT_FILE_STORAGE": "openedx.core.storage.AzureStorageMedia", "MEDIA_ROOT": "https://myedx.blob.core.windows.net/edx/", "MEDIA_URL": "https://myedx.blob.core.windows.net/edx/", My sotorage class class AzureStorageMedia(AzureStorage): account_name = settings.AZURE_ACCOUNT_NAME account_key = settings.AZURE_ACCOUNT_KEY azure_container = settings.AZURE_CONTAINER expiration_secs = None location = 'media' file_overwrite = False My error resp = descriptor.handle(handler, req, suffix) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/xblock/mixins.py", line 89, in handle return self.runtime.handle(self, handler_name, request, suffix) File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule/x_module.py", line 1347, in handle return super(MetricsMixin, self).handle(block, handler_name, request, suffix=suffix) File "/edx/app/edxapp/venvs/edxapp/local/lib/python2.7/site-packages/xblock/runtime.py", line 1037, in handle results = handler(request, suffix) File "/edx/app/edxapp/edx_xblock_scorm/scormxblock/scormxblock.py", line 164, in studio_submit os.mkdir(SCORM_ROOT) OSError: [Errno 2] No such file or directory: 'https://myedx.blob.core.windows.net/edx/scorm' How to solve this error. -
How to go about implementing multi user payment with django
Hello guys I need help with this hope it's not too difficult but I am finding it difficult to implement, here it goes. I have an event app that I have built it's working as expected where I have users create event and tickets for the event can be paid or free. Getting the payment from a user buying ticket is not a problem. The problem I am facing is paying the event creators their money. how do I handle multiple payment solution to each users of the site. Suggestions will be great if there's already a solution out there I would love to be pointed towards it. Thanks. -
Query to send post request in django
I'm trying to create a Calorie Info API which saves calorie intake for a user. If it is a new user, then add an entry for the user id and item id. If the user already exists, If the item is new, then just map the item id and the calorie count with that user. If the item id is already mapped with that user, then add the items calorie count with that item for that user. Url: /api/calorie-info/save/ Method: POST, Input: { "user_id": 1, "calorie_info": [{ "itemId": 10, "calorie_count": 100 }, { "itemId": 11, "calorie_count": 100 }] } Output: - Response Code: 201 My model: class CalorieInfo(models.Model): user_id = models.IntegerField(unique=True) itemId = models.IntegerField(unique=True) calorie_count = models.IntegerField() How will my view look like if I need to input in database in this form ? -
NoReverseMatch error argument not found, Django newbie
Greetings fellow programmers, So I'm a bit of a newbie at posting questions on here, as well as Django in general, and coding for that matter, so looking for constructive criticism. I'm working on building my first from scratch app, a tinder clone, on Django. I've elected to go with a custom model, which has been kinda a pain creating but I wanted to customize the registration so I went with it. I'm stuck at a certain where I'm not sure what's going on. I've looked at similar posts and tried different solutions but it isn't working. The error I'm getting is, Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['profile/(?P[0-9]+)/$'] I don't understand why the profile.id isn't being passed when I've put it in my url href tag. Here is my roots url.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('dating_app.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Here is dating_app/urls.py from django.urls import path from django.contrib.auth.views import LoginView from . import views app_name = 'dating_app' urlpatterns = [ #Home page path('', views.home, name='home'), #List of profiles path('profiles/', views.profiles, name='profiles'), #Individual profiles path('profile/<int:profile_id>/', … -
Django - Posting 2d list of multiple files results to single list
I have dynamic fields: <input type='text' name='names[]'> and <input type='file' name='images[]' multiple> which i will be posting to a view and be processed in batch by zipping the fields. The problem is when I post it, the images[] will be received as single list instead of 2d list. single list: images = [<file 1>, <file 2>, <file 3>, <file 4>] where it should be 2d list: images = [[<file 1>, <file 2>], [<file 3>, <file 4>]]. I need the images to be in 2d list since I will be using them on a zip. is there anyway I can do this without having different names for each <input type='file' name='images[]' multiple> row? template: <form action="__post_url_here__" method="POST" enctype="multipart/form-data"> <div> <input type="text" name="names[]" /> # has value of name 1 <input type="file" name="images[]" multiple /> # has value of [<file 1>, <file 2>] </div> <div> <input type="text" name="names[]" /> # has value of name 2 <input type="file" name="images[]" multiple /> # has value of [<file 3>, <file 4>] </div> ... ... </form> view: form_data = request.POST file_data = request.FILES names = form_data.getlist("names[]") images = form_data.getlist("images[]") print(names) # this results to ["name 1", "name 2"] print(images) # this results to [<file 1>, <file … -
What are the steps to make a ModelForm work with a ManyToMany relationship in Django?
How to call or implement many to many fields at the template? the only that i can think of right now is to make another form just specifically for IncomeSection. Thus the IncomeSection form will be call again in the view and pass it to the template. is there a way that i can put the same form as clientname? model.py class Taxcomp(models.Model): ClientName = models.CharField(_('Client Name'),max_length=50,blank = True, null= True) income = models.ManyToManyField(IncomeSection,blank=True) class IncomeSection(models.Model): Salary= models.CharField(choices=income.choices,max_length=512,null=True,blank=True) Bonus= models.CharField(choices=income.choices,max_length=512,null=True,blank=True) description = models.CharField(max_length=512,null=True,blank=True) form.py class taxCompForm(forms.ModelForm): class Meta: model = Taxcomp fields = ('__all__') view.py def taxcompute(request): msg = 'Tax Comp Successfully Updated' msgerror = 'Invalid inputs' data = request.session.get('session_data') clientname = data['client_name'] if request.method == "GET": form = taxCompForm(initial={'ClientName':clientname}) formc = ProfileUpdateForm() income_list = [] salary = [] bonus = [] taxcompobj = Taxcomp.objects.all() header_fields = [] income_obj = Taxcomp.objects.get(pk=1) print(income_obj) for income in income_obj.income.all(): incomeForm = taxCompForm(instance=income) if income.title == "Salary": salary.append(incomeForm) elif income.title == "Bonus": bonus.append(incomeForm) else: comission.append(**incomeForm**) salary.append(taxCompForm(initial={'title':'Salary'})) bonus.append(taxCompForm(initial={'title':'Bonus'})) context ={ 'form' :form, 'formc': formc, 'salaryform': salary, 'bonusform': bonus } else: form = taxCompForm(request.POST) if form.is_valid() : form.save() messages.success(request, f'{msg}') return redirect ('taxcompute') else: messages.error(request, f'{msgerror}') print(inputf.errors) return redirect ('taxcompute') return render (request,'taxcomp.html',context) taxcomp.html {%for bonus … -
Elasticsearch DSL Filter
I am having a problem with the elastic-search filter. I am trying to search for a text using elastic-search DSL filter, but I am facing issue with sorting. Search text: hello world Other string in the document: Hello there, hello world, hello everyone, hi hello, etc... Elasticsearch-dsl query is: MyDocument.search().filter(Q("match", title="hello world") | Q("match", original_title="hello world")).execute() Elasticsearch query is like this: { 'bool': { 'filter': [{ 'bool': { 'should': [{ 'match': { 'title': 'hello world' } }, { 'match': { 'original_title': 'hello world' } }] } }] } } The output is like hello everyone, hi hello, hello world, etc.. but I want hello world first. Thanks in advance! -
how to get count of rating in django rest framework
I have a model like that class UserRating(models.Model): product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True) rate = models.PositiveSmallIntegerField() status = models.BooleanField(default=False) I rate this in a range of 1 to 4 where 4 is excellent, 3 is very good, 2 is good, 1 is bad and I should get the count of rating according to the number given by user. I am using SerializerMethodField like that is def get_excellent(self, obj): return models.UserRating.objects.filter(rate=4, status=True).count() def get_very_good(self, obj): return models.UserRating.objects.filter(rate=3, status=True).count() def get_good(self, obj): return models.UserRating.objects.filter(rate=2, status=True).count() def get_bad(self, obj): return models.UserRating.objects.filter(rate=1, status=True).count() but it is bad idea to do this because it goes to the db the four times. I am looking for better way of doing this. Is there any help please! Thanks in advance! -
How to check BASE_DIR in django?
I was running into a lot of file not found for webpack in my static folder, and I later realized that for some reason this particular project (which I'm using docker with) keeps trying to check another project folder's static folder for the files I would want. I'm not sure where this could've gone wrong other than the base_dir, but I never changed that setting. There was a while I was going between the projects and trying to run each one (the other project is basically the same thing but not on docker), was that possibly what's confusing the program? How can I solve it? -
How to count no of event by the a user
My model suppose i created a user named 'Ashu',and that user 'Ashu' created multiple sessions, i want to print that no of session by the user 'Ashu' class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE) game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.CharField(max_length=30,blank=False) status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') def __str__(self): return str(self.Host) MY VIEWSET class UserViewSet(viewsets.ViewSet): def create(self,request): try: user_name=request.data.get('user_name') mobile_number=request.data.get('mobile_number') address=request.data.get('address') country=request.data.get('country') joining_date=request.data.get('joining_date') if not all([user_name,mobile_number,address,country,joining_date]): raise Exception('All fields are mandatory') user=MyUser() user.user_name=user_name user.mobile_number=mobile_number user.address=address user.country=country user.joining_date=joining_date user.save() return Response({"response":'delivered'}) except Exception as error: traceback.print_exc() return Response({"message": str(error), "success": False}, status=status.HTTP_200_OK) class SessionViewSet(viewsets.ViewSet): def create(self, request): try: … -
Python Weasyprint causing High CPU usage, How do I queue rendering?
Please bear with me as i put these into words, I am running Weasyprint on Python Django Framework, I have have 15 page html to render to PDF. Rendering takes about 70% to 80% of my CPU when one user click button to render, so what happens is when two or three users render at the same time, it goes above 100% and cause my sever to crash, that I need to reboot the system to make it work again. My question is, Is there something I can use to queue users request for rendering? Instead of processing render requests at the same time, make them wait in a queue? -
ValueError: Cannot assign "<Truckdb: Truckdb object (1)>": "Quiz.truck_name" must be a "truck_name" instance
I am trying to create an instance in my app like this: Views.py new_quiz = Quiz.objects.create(owner=request.user, comments="Autogenerated", truck_type=truck_type_object, truck_name=chosen_truck_object) where chosen_truck_object is this: chosen_truck_object = Truckdb.objects.filter(display_name=chosentruck)[0] And Models.py class Quiz(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes') comments = models.TextField(max_length=256, blank=True) truck_type = models.ForeignKey(truck_type, on_delete=models.CASCADE, related_name='trucks') truck_name = models.ForeignKey(truck_name, on_delete=models.SET_NULL, null=True) How can I pass the truck_type and truck_name instance to the Quiz model in Quiz.objects.create ?