Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display only specific data from the entire list storage on python django server (rest framework)
I have to display (as in topic title) only specific data from the list which is storage on server (PYTHON/DJANGO/REST_FRAMEWORK). F.e. I want to choose data which has planted on the server with 'id=1', but I always get back all items. Can you explain how to correct this? 'urls' file (project level) : # URL routes - known as endpoints API urlpatterns = [ path('admin/', admin.site.urls), path('devices/', include('efota.api.urls')), ] 'urls' file (subordinate folder) : urlpatterns = [ url('', views.DeviceList.as_view()), url('<int:pk>/', views.DeviceDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) 'views' file : class DeviceList(generics.ListAPIView): queryset = Device.objects.all() serializer_class = DeviceSerializer class DeviceDetail(generics.RetrieveAPIView): queryset = Device.objects.all() serializer_class = DeviceSerializer 'serializers' file: class DeviceSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') # the 'fields' controls which database attributes are available class Meta: model = Device fields = ( 'id', 'user', 'id_token', 'current_firmware', 'carrier_code', 'model_name', 'owner', ) read_only_fields = ['id'] def get_url(self, obj): request = self.context.get("request") return obj.get_api_url(request=request) 'models' file: class Device(models.Model): created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey('auth.User', related_name='owner', on_delete=models.CASCADE) user = models.CharField(max_length=50, verbose_name='user') id_token = models.CharField(max_length=1000, verbose_name='id_token') current_firmware = models.CharField(max_length=41, verbose_name='current_firmware') carrier_code = models.CharField(max_length=5, verbose_name='carrier_code') model_name = models.CharField(max_length=10, verbose_name='model_name') class Meta: ordering = ('created', ) def __str__(self): return self.model_name 'admin' file: from django.contrib import admin from .models import Device # … -
Auto-generating user email when creating user profile?
I am creating a application using django My Code as follows: class Profile(models.Model): Name = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) E_mail = models.EmailField(max_length=70) Phone_no = models.BigIntegerField() Skills = models.TextField() Image = models.ImageField(upload_to='user_images') I want to autogenerate the user email in the user profile which the user had given at the time of signup. I am using the django autheticated models for signup and login and I am using class based views for my profile generation. Can anybody help me in this? Thank you -
How do I access data from local storage in Django views?
In Django templates --> index.html HTML -User will key in input and button will activate local storage function <input type="text" id="firstID"> <button onclick="myFunction()">LocalStorage</button> Javascript -User input is saved in variable which is used to for local storage var siteName = document.getElementById('firstID'); function myFunction() { localStorage.setItem('store1', siteName.value); How do I access the value of key "store1" inside local storage in my Django views.py?? -
append data to the JSON list of objects
I have created a simple service wich returns the data from a single table based on a param in the url as folow: I would like to append to the json another object as { "running_time": "13:00" } How can I add the abobe object to the json list of objects? thanks http://127.0.0.1:8000/api/figo?figonr=1078924300-01 output is the json: HTTP 200 OK Allow: GET Content-Type: application/json Vary: Accept [ { "figonr": "1078924300-01", "description": "F150/C+W/CC/GE201S/S/OE/SE", "productgroup": null } ] my View is as folowing: from django.shortcuts import render from django.http import HttpResponse # Create your views here. from rest_framework import generics from servicesapp.models import Figo from servicesapp.serializers import ServiceAppSerializer class ListCreateFigos(generics.ListCreateAPIView): queryset = Figo.objects.all() serializer_class = ServiceAppSerializer http_method_names = ['get'] def get_queryset(self): queryset = None figo_nr = self.request.query_params.get('figonr', None) if figo_nr is not None: queryset = Figo.objects.filter(figonr = figo_nr) return queryset and serializer: from rest_framework import serializers from servicesapp.models import Figo import datetime class ServiceAppSerializer(serializers.ModelSerializer): class Meta: model = Figo fields=('__all__') -
Django; default error message doesn't show up on form
The default error message doesn't show up on form. html <div class="form-group"> {{ form.description.errors }} <label>{{ form.description.label }}</label> {{ form.description|add_class:'form-control' }} </div> I want to write form manually. What am I wrong with this? Do I have to set custom error message somewhere so it can be shown up? For some fields that I set custom error message, the error messages does show up. -
"SELECT DISTINCT field_name from table" Django using raw sql
How can I run SELECT DISTINCT field_name from table; SQL query in Django as raw sql ? When I try to use Table.objects.raw("""SELECT DISTINCT field_name from table"""), I got an exception as InvalidQuery: Raw query must include the primary key -
Python - Converting XLSX to PDF
I have always used win32com module in my development server to easily convert from xlsx to pdf. However, I have deployed my Django app in production server where I don't have Excel application installed and it raises the following error: File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\__init__.p y", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,c lsctx) File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\dynamic.py ", line 114, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\virtualenvs\structuraldb\lib\site-packages\win32com\client\dynamic.py ", line 91, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.II D_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) Is there any good alternative to convert from xlsx to PDF in Python? Thanks! -
while use .env got NameError: name 'config' is not defined
I'm following a tutorial to upload static file to amazon S3 to. I need to add two things in the settings.py AWS_ACCESS_KEY_ID = config'AWS_ACCESS_KEY_ID' AWS_SECRET_ACCESS_KEY = config'AWS_SECRET_ACCESS_KEY' For safety reasons I create a file named .env its form is .text directly through pycharm. After I added these code in the settings.py.I restarted nginx and gunicorn and then I activated virtual environment and run python manage.py collectstatic Then I got the error NameError: name 'config' is not defined Any friends could tell me what need I do? Thanks! -
Why does printing an IntegerField field does not give me a number? [Django]
Having following field declared in my model: info_number_of_views = models.IntegerField(blank=False, default=0, null=False) Whenever I am trying to print or log it with following command: print('queried_model_of_particular_user.info_number_of_views: ' + str(queried_model_of_particular_user.info_number_of_views)) Instead of a number, I do receive that kind of an output: queried_model_of_particular_user.info_number_of_views: (<django.db.models.fields.IntegerField>,) -
Calling a Django server function from PHP server
I Just hired as a junior python developer at a company (i'm the only python developer). Here they want to pass a heavy tasks (bulk mailing,Excel import,PDF export) from a PHP server to a django server(celery) to reduce work load. In my computer I managed to run them both locally (separately). My question is what is the best way to pass the data or trigger a function at django server from PHP server For example consider the code below : some_shit.php public function actionExportPdf() { $mPDF = Yii::app()->ePdf->mpdf(); $model = new Gulfuniversityapplication('search'); $dbcriteria = Yii::app()->session['criteria']; $model->setDbCriteria($dbcriteria); $row = Yii::app()->db->createCommand("select field_data from modules where table_name='".$model->tableName()."'")->queryRow(); $filteredData = CJSON::decode($row['field_data']); //$filteredData = $data[$model->tableName()]; $stylesheet = file_get_contents(getcwd().'/path/to/core/assets/css/social.css'); $mPDF->WriteHTML($stylesheet, 1); $mPDF->WriteHTML($this->renderPartial('_exportPdf',array( 'model' => $model, 'data' => $filteredData, ), true)); $mPDF->Output(); } This is their PHP I have no idea what's in it. Here is my Django celery code tasks.py @shared_task def export_task(arg1,arg2): my_cursor = my_db.cursor() my_cursor.execute("SELECT arg1 FROM arg2") out =[] for i in my_cursor.fetchall(): out.append(i) my_cursor.execute("DESCRIBE app_gulfuniversityapplication") column = [] for i in my_cursor.fetchall(): column.append(i[0]) df = pd.DataFrame(data=out,columns=column) writer = pd.ExcelWriter('output.xlsx') df.to_excel(writer,'Sheet1') writer.save() This is my first question here thanks in advance. -
Easiest method for mapping polygons in GeoDjango
I have a simple application with a PosGIS back end. I want to have a page per feature in the database. I have used a slug and a URL routing. The PostGIS features have a polygon stored in a geom column which is modelled as a MultiPolygonField using geodjango. What is the easiest way to parse this geom column in to geojson so that I can add it to a leaflet map? Below is my code which is attempting to use the geojson serializer though I receive this error code on my page. Views.py from django.shortcuts import render from Countries_App.models import Countries from django.core.serializers import serialize # Create your views here. def show_country(request, country_slug): # Create a context dictionary which we can pass # to the template rendering engine. context_dict = {} try: # Can we find a category name slug with the given name? # If we can't, the .get() method raises a DoesNotExist exception. # So the .get() method returns one model instance or raises an exception. country = Countries.objects.get(slug=country_slug) Country_geojson = serialize('geojson', Countries.objects.get(slug=country_slug)) # We also add the category object from # the database to the context dictionary. # We'll use this in the template to verify … -
django xhtml2pdf table border issue
I'm using xhtml2pdf with Django to generate a PDF with a table that runs over multiple pages. I can't seem to get the table body <tbody> to generate a border. I am not trying to get a border around the whole table including header <thead>, just the main body. I've been able to generate left and right borders by adding style to <td>, and a bottom border to <thead> so that it appears that the tbody has borders on 3 sides, leaving only the <tbody> bottom. but i suspect this is really a hack and not the correct way to get a full border around <tbody>. In any event I'm left stuck with this part solution and no bottom border. I've tried applying lots of css via id's classes and elements. has anyone had any experience successfully implementing table borders with xhtml2pdf in Django and could kindly offer me some guidance? Any help is much appreciated! -
django celery chain task hang
I'm the newbie to celery task. I'd like to test celery chain tasked for workflow. I have tested the chained example code as below but it only execute first job (add.s(2,1) then hang (no response from second job). Do I miss setup anything for celery chain job ? Any advice will be appreciated. Thanks in advanced. By the way, I also want to know how to get the job id from job1(add.s(2,1) and job2(add.s(4)) . Hang: job2 = chain(add.s(2, 1),add.s(4)).apply_async (queue='test') OK: job2 = chain(group(add.s(2, 1)),add.si(4,4)).apply_async (queue='test') OK: parallel run 2 job. job2 = group(add.s(2, 1),add.si(4,4)).apply_async (queue='test') Thanks. ps: app = Celery('tasks',broker='amqp://xx.xx.xx.xx', backend='amqp://xx.xx.xx.xx') Celery 4.2.1 and RabbitMQ -
Send request to gunicorn directly
Can I send a http request to gunicorn directly. Like to the below url which nginx uses http://unix:/code/tanmay.garg/web/utrade/run/gunicorn.sock -
How to round integer 3 in Django template
I have one param in my Django model, the type is Float. Imagine that it is a weight of payload. But it is in kg. But I have to show in a template in ton. Ex. class car(models.Model): ...... weight = models.FloatField(default=0) 45234 kg => 45.2 t (in template) -
why i cant user category detailview ? if use it get 404 in django?
I want use category_slug or id_slug for detailview as productdetailview and show all of product that category there but i don't know how do that i used this views but i get errors 404. why is different between productdetailview and categorydetailview? could plz help me to solve this problem? models.py class Category(models.Model): name = models.CharField(max_length=120,unique=True) slug = models.SlugField(unique=True) def __str__(self): return self.name class Brand(models.Model): name = models.CharField(max_length=120,unique=True) class Product(models.Model): category = models.ManyToManyField(Category,blank=True) brand = models.ForeignKey(Brand,on_delete=models.CASCADE) car = models.ForeignKey(Car,on_delete=models.CASCADE) title = models.CharField(max_length=120,unique=True) slug = models.SlugField(unique=True) description = models.TextField(max_length=10000) price = models.DecimalField(max_digits=10,decimal_places=2) stock = models.PositiveIntegerField() active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now=True,auto_now_add=False) defalut = models.ForeignKey(Category,related_name="defalut_category",blank=True,null=True,on_delete=models.CASCADE) class Meta: ordering = ['-timestamp'] def __str__(self): return self.title def get_absolute_url(self): return reverse('products:product_detail',kwargs={"slug":self.slug}) views.py def ProductDetail(request,slug): product = get_object_or_404(Product,slug=slug,active=True) context = { "product":product } template_name = "product_detail.html" return render (request,template_name,context) def CategoryDetail(request,category_slug): category = get_object_or_404(Category,slug = category_slug) product = Product.objects.filter(category=category) context = { 'category':category, 'product': product } template_name ="category_detail.html" return render(request,template_name,context) -
Run Django on Oracle Application Container
I have an existing django project which I am trying to deploy to Oracle's cloud service, Application Container. I followed Oracle's guide to do this however there are some details missing from this guide. Specifically the guide references an app.py file which seems to come from this guide. But I can't see how to use that in a django project. I've tried replacing the calls to app.py to use django's manage.py or wsgi.py files but Oracle servers still fail to launch. The server logs Oracle provide also don't help, only telling me the python packages are being installed. ACCS[web.1]: Content of APP_HOME [ /u01/app/ ] dir ACCS[web.1]: total 96 ACCS[web.1]: -rw-r----- 1 apaas apaas 28423 May 17 10:51 readme.html ACCS[web.1]: -rw-r----- 1 apaas apaas 40960 May 17 10:51 db.sqlite3 ACCS[web.1]: -rw-r----- 1 apaas apaas 355 Sep 10 13:26 manage.py ACCS[web.1]: -rw-r----- 1 apaas apaas 254 Sep 10 13:28 DjangoProject.pyproj.user ACCS[web.1]: -rw-r----- 1 apaas apaas 6990 Sep 10 13:28 DjangoProject.pyproj ACCS[web.1]: -rw-r----- 1 apaas apaas 186 Sep 12 11:24 manifest.json ACCS[web.1]: drwxr-x--- 1 apaas apaas 10 Sep 13 03:42 obj ACCS[web.1]: drwxr-x--- 1 apaas apaas 160 Sep 13 03:42 app ACCS[web.1]: drwxr-x--- 1 apaas apaas 94 Sep 13 03:42 DjangoProject ACCS[web.1]: … -
Issue in configuring Django with Apache in Centos7
I am using CPANEL to maintain the server with CentOS7 and Apache2. I am trying to configure Apache(EasyApache) to support Python, I have an issue in installing mod_wsgi getting error Error: Package: mod_wsgi-3.4-12.el7_0.x86_64 (base) Requires: httpd-mmn = 20120211x8664 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest -
obtain django dropdown menu item queryset
I am trying to make a calendar html page, that has a dropdown button to select the different months. How to get to this calendar page is via the nav bar that is created at base.html base.html - how to get to the calendar page. .... .... <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" data-target="scheduler_dropdown" href="#"><i class="fas fa-calendar"></i>Scheduler</a> <div class="dropdown-menu" aria-labelledby="scheduler_dropdown"> <a class="dropdown-item" href="{% url 'view_schedule' %}"><i class="fas fa-calendar-alt"></i>View Schedule</a> </div> </li> what i've build so far: urls.py urlpatterns = [ path('schedule/view-schedule/', views.view_schedule, name='view_schedule'), path('schedule/view-schedule/?query=month<str:selected_month>', views.view_schedule, name='view_schedule_selected_month'), ] Views.py def view_schedule(request, selected_month=None): if request.method == 'POST': print('post') else: current_month = date.today().month current_year = date.today().year # a = request.GET # How to get query set from dropdown menu??? # print(a) args = { 'month_cal': monthcalendar(current_year, current_month), 'month_name': calendar.month_name[current_month], 'year_name': current_year, } return render(request, 'static/html/view_schedule.html', args) view_schedule.html <div class="card-header"> Schedule for {{ month_name }} {{ year_name }} <form class="date-selector" method="post"> {% csrf_token %} <div class="dropdown"> <button class="btn dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="far fa-caret-square-down"></i> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=1 %}>Jan</a> <a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=2 %}>Feb</a> <a class="dropdown-item" href={% url 'view_schedule_selected_month' selected_month=3 %}>Mar</a> </div> </div> </form> </div> My problem is that, when I click … -
Django-Select2 Heavy
I am using Django-select2 I am trying to use the HeavySelect2Widget. THe widget is accessing the view; but is not able to display the response in the box. View: def autocomplete(request): qs = {'name':'Test'} return JsonResponse(qs) Forms.py class ReportForm1(forms.Form): auto = forms.ChoiceField(widget=HeavySelect2Widget( data_url='/autocomplete/'), ) -
complex sub-queries in MySQL
I have 3 tables as: First Table: (Purchase) date (mm-dd) quantity p_id 05-05 3 1 05-06 2 1 Second Table: (Sales) date (mm-dd) quantity p_id 05-07 1 1 Third Table: (Expired) date (mm-dd) quantity p_id 05-08 4 1 Now what I want is get details of products that have expired as: When the product that has expired was purchased (FIFO) Product that was purchased first, will expire/sell first. The Output shall be: purchase_date expired_date quantity p_id 05-05 05-08 2 1 05-06 05-08 2 1 Explanation, Store have total of 5 products by 05-06 with p_id: 1, then on 05-07 1 quantity was sold of p_id: 1 i.e. product that was received on 05-05 was sold first as per FIFO so now product we have are: (only for visualization) date (mm-dd) quantity p_id 05-05 2 1 -its 1 quantity is sold 05-06 2 1 Then Expiry is made on 05-08, expired products are: (by FIFO) purchase_date expired_date quantity p_id 05-05 05-08 2 1 05-06 05-08 2 1 i.e. 2 products of 05-05 have expired and 2 of 05-06 By now logic I am implementing is: All Appended transactions: date (mm-dd) quantity p_id expired 05-05 3 1 False 05-06 2 1 False … -
How to sort and group an list of dictionaries in right way in Python
I have an list of dict in Python as follows: options = [ {'group_priority': 2, 'group': u'Comfort', 'name': u'Air conditioning'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Air suspension'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Cruise control'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Leather interior'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Parking assist system camera'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Parking assist system sensors rear'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Power steering'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Seat heating'}, {'group_priority': 2, 'group': u'Comfort', 'name': u'Sunroof'}, {'group_priority': 3, 'group': u'Entertainment', 'name': u'Bluetooth'}, {'group_priority': 3, 'group': u'Entertainment', 'name': u'MP3'}, {'group_priority': 3, 'group': u'Entertainment', 'name': u'Navigation system'}, {'group_priority': 4, 'group': u'Extra', 'name': u'Alloy wheels'}, {'group_priority': 4, 'group': u'Extra', 'name': u'Trailer hitch'}, {'group_priority': 4, 'group': u'Extra', 'name': u'Winter tyres'}, {'group_priority': 4, 'group': u'Security', 'name': u'Xenon headlights'}] I want to order it by group_priority and group it by group and show it in Django template/ What I have tried: options_grouped_dict = {} for item in options_grouped: options_grouped_dict.setdefault(item['group'], []).append(item['name']) And then in Django template: {% for key, values in car.options_grouped.items %} <div> <div><strong>{{key}}</strong></div> {% for option in values %} <div> {% if option|length > 31 %} {{ option|truncatechars:34 }} {% else %} {{ option }} {% endif %} </div> {% endfor … -
Django's cache framework - auto deletion?
I have encountered the following problem and I have no clue why. I use Django's cache framework to cache part of my site. I have set the expires time as 15mins. Sometimes when I am checking with the database, there is no record in the cache table. At first, I suspect Django will remove the expired cache in the database. But later, I can find some expired caches still exist in the table. I want to ask how Django handles the cache in the database? Does Django auto-remove all the expired cache in the table? Thanks! -
How to redirect url in Django Template View?
I want to send Json data and then redirect back to home.Should i use success_url? class ApiLoginView(TemplateView): template_name = 'index.html' def post(self,request): email = request.POST.get('login-email') password = request.POST.get('login-password') API_KEY = GetAPIkey().api_key_token() API_URL = GetAPIurl().api_url_token() parameter = { 'authToken':API_KEY, 'email':email, 'password':password, } r = requests.post(url = API_URL, params=parameter) if email: request.session['email'] = email return HttpResponse(r) -
Django in edx and whant to solve
The following is the error code generated when the Django system operates a webpage exercise. After reading this bunch of error codes, I still don't know how to solve the problem. Does Django have a folder or file to store error information? How can I solve the problem after seeing such an error code? Can you give me a direction? Thank you The error code is as follows: Staff debug info: Traceback (most recent call last): File "/edx/app/edxapp/edx-platform/common/lib/xmodule/xmodule line 1151, in submit_problem correct_map = self.lcp.grade_answers(answers) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/capa_problem.py", line 400, in grade_answers return self._grade_answers(answers) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/capa_problem.py", line 462, in _grade_answers results = responder.evaluate_answers(self.student_answers, oldcmap) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/responsetypes.py", line 306, in evaluate_answers new_cmap = self.get_score(student_answers) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/responsetypes.py", line 2255, in get_score self.execute_check_function(idset, submission) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/responsetypes.py", line 2310, in execute_check_function self._handle_exec_exception(err) File "/edx/app/edxapp/edx-platform/common/lib/capa/capa/responsetypes.py", line 2512, in _handle_exec_exception raise ResponseError(err.message, traceback_obj) ResponseError: ('Couldn\'t execute jailed code: stdout: \'\', stderr: \'Traceback (most recent call last):\\n File "jailed_code", line 15, in <module>\\n exec code in g_dict\\n File "<string>", line 91, in <module>\\n File "<string>", line 76, in get_score\\n File "/usr/lib/python2.7/csv.py", line 8, in <module>\\n from _csv import Error, __version__, writer, reader, register_dialect, \\\\\\nImportError: /edx/app/edxapp/venvs/edxapp-sandbox/lib/python2.7/lib-dynload/_csv.x86_64-linux-gnu.so: failed to map segment from shared object\\n\' with status code: 1', <traceback object …