Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Online compiler Django
I'm working on a Django project that involves to create an online compiler for python code. I found a project in Flask framework and I would like to adapt the code for Django. Someone can help me because I'm a beginner in django and I really need some help. Thanks runcode.py import subprocess import sys import os class RunPyCode(object): def __init__(self, code=None): self.code = code if not os.path.exists('running'): os.mkdir('running') def _run_py_prog(self, cmd="a.py"): cmd = [sys.executable, cmd] p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = p.wait() a, b = p.communicate() self.stdout, self.stderr = a.decode("utf-8"), b.decode("utf-8") return result def run_py_code(self, code=None): filename = "./running/a.py" if not code: code = self.code with open(filename, "w") as f: f.write(code) self._run_py_prog(filename) return self.stderr, self.stdout webdev.py from flask import Flask, render_template, request from runcode import runcode app = Flask(__name__) default_py_code = """import sys import os if __name__ == "__main__": print "Hello Python World!!" """ default_rows = "15" default_cols = "60" @app.route("/py") @app.route("/runpy", methods=['POST', 'GET']) def runpy(): if request.method == 'POST': code = request.form['code'] run = runcode.RunPyCode(code) rescompil, resrun = run.run_py_code() if not resrun: resrun = 'No result!' else: code = default_py_code resrun = 'No result!' rescompil = "No compilation for Python" return render_template("main.html", code=code, target="runpy", resrun=resrun, rescomp=rescompil,#"No compilation … -
Django Adding Prefix to FileField
I have a model that takes in multiple pdf files. When users upload these files, I'd like each file to be renamed with a prefix and some random characters. I can assign the upload_to to callable functions, example: class Order(models.Model): invoice_file = models.FileField(upload_to=invoice_file_name) purchase_order_file = models.FileField( upload_to=po_file_name) payment_file = models.FileField( upload_to=payment_file_name) def invoice_file_name(instance, file_name): return 'inv_' + uuid4.uuid + '.pdf' def po_file_name(instance, file_name): return 'po_' + uuid4.uuid + '.pdf' def payment_file_name(instance, file_name): return 'pmt_' + uuid4.uuid + '.pdf' Is there a way to generalize these upload_to functions so I can pass the prefix in the FileField definition? ATTEMPT: I attempted to solve this by creating a custom file field that extends FileField class CustomFileField(models.FileField): def __init__(self, file_prefix, **kwargs): self.file_prefix = file_prefix # print(kwargs) super().__init__(upload_to=self.custom_upload_to, **kwargs) def custom_upload_to(self, file_name): return self.file_prefix + uuid4.uuid + '.pdf' class Order(models.Model): invoice_file = CustomFileField(file_prefix='inv_') purchase_order_file = CustomFileField(file_prefix='po_') payment_file = CustomFileField(file_prefix='pmt_') However, the migrations failed. One of the errors is TypeError: __init__() got multiple values for keyword argument 'upload_to' Not quite sure what's going on but I looked at the migration file and it seems to be calling this: migrations.CreateModel( name='Order', fields=[ ('invoice_file', CustomFileField(blank=True, null=True, upload_to='') ... ]) Is this the wrong way to subclass FileField? -
Why are logging libraries used when we can simply write files using code?
I am not able to understand that why do we use a library for logging files when we can simply write out the error or the exception by appending to a file. -
error ('datetime.datetime' object has no attribute 'split') in django 1.11.4
I am learning django version 1.11.4 through tutorial on the official documentation. I am using python 3.6.5 and mysql8 for database. I also use mysql.connector.django to connect to mysql database. I tried to do the first Django app, part 2. This is the link of the example I used everything works fine except when I run the this command: Question.objects.all() I got the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 226, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 250, in __iter__ self._fetch_all() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 1118, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 62, in __iter__ for row in compiler.results_iter(results): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 839, in results_iter for rows in results: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1284, in cursor_iter sentinel): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in <lambda> for rows in iter((lambda: cursor.fetchmany(GET_ITERATOR_CHUNK_SIZE)), File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/utils.py", line 101, in inner return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/cursor_cext.py", line 510, in fetchmany rows.extend(self._cnx.get_rows(size)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/connection_cext.py", line 275, in get_rows row[i]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 205, in to_python return self._cache_field_types[vtype[1]](value, vtype) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/django/base.py", line 119, in _DATETIME_to_python dt = MySQLConverter._DATETIME_to_python(self, value) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/mysql/connector/conversion.py", line 506, in _DATETIME_to_python (date_, time_) = value.split(b' ') AttributeError: 'datetime.datetime' object has no attribute … -
Django queryset custom order with some objects on specified positions
I have the model: class Article(models.Model): site = models.ForeignKey('Site') published_at = models.DateTimeField(_('Published at')) promoted = models.BooleanField(_('Promoted)) position = models.PositiveSmallIntegerField( _('Position'), null=True, blank=True, ) valid_from = models.DateTimeField(_('Valid from')) valid_to = models.DateTimeField(_('Valid to')) // (...) I want to get the queryset with a specified position of some objects in specified time range. The rest of them should be ordered by published date. The way I do it now works but it is slow and not efficient, which is a problem because I want to use it on the homepage. def get_articles_list(site): articles = Article.objects.filter( site=site, published_at__lte=now(), ).order_by( '-published_at', ) promoted_articles = Article.objects.filter( site=site, promoted=True, valid_from__lte=now(), valid_to__gte=now(), position__isull=False, ) // create a list with no promoted articles on it (to avoid duplicates) articles_list = list(articles.exclude(id__in=promoted_articles)) // put promoted articles on the specific positions of the list if promoted_articles: for promoted in promoted_articles: articles_list.insert(promoted.position - 1, promoted) return articles_list Is there a way to optimize the process? -
Django reverse foreign key relation doesn't work
Hello i am struggling already since 2 days to get a reverse relation going. I tried almost everything i have found on the internet, but maybe I just have overseen something? here is my models.py: class Doku(models.Model): name = models.CharField(max_length=1000) inhalt = models.TextField(blank=True, null=True) erstellungsdatum = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = "Dokumentation" verbose_name_plural = "Dokumentationen" def __str__(self): return self.name class Bilder(models.Model): doku = models.ForeignKey(Doku, on_delete=models.CASCADE) name = models.CharField(max_length=1000) bilder = models.ImageField(upload_to="bilder/doku/") def __str__(self): return self.name my views.py @login_required(login_url='login') def Dokus(request): doku = Doku.objects.all() context = {'doku':doku} return render(request, "doku/index.html", context) and my template: {% for doku in doku %} <a href="{% url 'apps:DokuDetail' doku.pk %}">{{ doku.name }}</a> {{ doku.bilder.name }} {% for bilder in doku.bilder_set.all %} <img src="{{dokubilder.dokubilder.url}}"> <p>{{ bilder.name }}</p> {% endfor %} {% endfor %} -
honcho takes too long to start django
I have no idea on how to proceed here. I am using a small wrapper to run django: #!/bin/bash echo "Sourcing" source /home/dimitry/.virtualenvs/myenv/bin/activate echo "Python location:" which python echo "Update requirements:" pip install -r requirements.txt echo "Executing runserver" python manage.py runserver echo "Nothing more" When I run it from shell, it responds immediately: Sourcing Python location: /home/dimitry/.virtualenvs/myenv/bin/python Update requirements: Requirement ... Executing runserver Performing system checks... System check identified no issues (0 silenced). April 23, 2018 - 09:18:59 Django version 2.0.4, using settings 'application_www.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. but when I run it from honcho wrap_django: ./dev_wrap_django It seems to get into a loop, sometimes it starts after a delay, some times it does not. Any idea how to root-cause this? -
Django - Zip multiple querysets with uncommon fields data
I have this one model where I have fetch published count , under process count, rejected count, received count on monthly basis class PreData(models.Model): status=models.CharField(max_length=200,default=None,null=True) receivedon=models.DateField(default=None,blank=False,null=True) publishedon = models.DateField(default=None, blank=True, null=True) received count is based on monthly count of receivedon DateField in model, published count is based on monthly count of publishedon DateField in model, rejected count and under process count is based on count of specific status value of CharField in model. I'm struggling after writing below queries,I'm clueless as to how fetch data to fill the columns(see figure). I'm not sure queries I wrote will help. The problem comes when I want to zip received_monthly_data and published_monthly_data but received_monthly_data has data from April month and published_monthly_data didn't have April month. when i zip , results will loose April month. I am not able to figure how to do this. received_monthly_data = PreData.objects.filter(journaluser=request.user.username).\ annotate(month=TruncMonth('receivedon'),year=TruncYear('receivedon')).values('month','year').\ annotate(c=Count('id')).order_by('-month') published_monthly_data = PreData.objects.filter(Q(journaluser=request.user.username)&~Q(pdfsenton=None)). \ annotate(month=TruncMonth('publishedon'), year=TruncYear('publishedon')).values('month', 'year'). \ annotate(c=Count('id')).order_by('-month') underproc_data= PreData.objects.filter(Q(journaluser=request.user.username)&~Q(status="[Published]")) I need the data to fill these columns Any help is highly appreciated. -
Need help understanding many and source fields in a serializer
I am currently trying to familiarize myself with DRF and while going through a tutorial these serializers were used class EmbeddedAnswerSerializer(serializers.ModelSerializer): votes = serializers.IntegerField(read_only=True) class Meta: model = Answer fields = ('id', 'text', 'votes',) class QuestionSerializer(serializers.ModelSerializer): answers = EmbeddedAnswerSerializer(many=True,source='answer_set') class Meta: model = Question fields = ('id', 'answers', 'created_at', 'text', 'user_id',) These are the models class Question(models.Model): user_id = models.CharField(max_length=36) text = models.CharField(max_length=140) created_at = models.DateTimeField(auto_now_add=True) class Answer(models.Model): question = models.ForeignKey(Question,on_delete=models.PROTECT) text = models.CharField(max_length=25) votes = models.IntegerField(default=0) My question is in the statement in the Question serializer answers = EmbeddedAnswerSerializer(many=True,source='answer_set') what is the purpose of many = True and source='answer_set' ? I read from the documentation the following regarding many=True You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. I am confused by what that means ? If I remove many=True from the code I get the error AttributeError at /api/quest/1/2/ Got AttributeError when attempting to get a value for field `text` on serializer `EmbeddedAnswerSerializer`. The serializer field might be named incorrectly and not match any attribute or key … -
Django: problems in migrations for dynamic_preferences
I am having problems making migrations: python manage.py makemigrations Applying dynamic_preferences.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/apps/config.py", line 163, in get_model return self.models[model_name.lower()] KeyError: 'userpreferencemodel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.5/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.5/site-packages/django/db/migrations/operations/models.py", line 95, in database_forwards if self.allow_migrate_model(schema_editor.connection.alias, model): File "/usr/local/lib/python3.5/site-packages/django/db/migrations/operations/base.py", line 115, in allow_migrate_model return router.allow_migrate_model(connection_alias, model) File "/usr/local/lib/python3.5/site-packages/django/db/utils.py", line 311, in allow_migrate_model model=model, File "/usr/local/lib/python3.5/site-packages/django/db/utils.py", line 300, in allow_migrate allow = method(db, app_label, **hints) File "/usr/local/lib/python3.5/site-packages/rest_models/router.py", line 105, in allow_migrate model = apps.get_model(app_label, model_name) File "/usr/local/lib/python3.5/site-packages/django/apps/registry.py", line 195, in get_model return self.get_app_config(app_label).get_model(model_name.lower()) File "/usr/local/lib/python3.5/site-packages/django/apps/config.py", line 166, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) … -
Maintaining a session using Django REST API
Is there any way to maintain state (session) of the user instead of storing tokens in local storage on client side which makes them vulnerable to theft. And how exactly can we do that in Django Rest Framework? Right now I have OAuth imlpemented in my project, however, since access tokens can be exchanged or stolen, I am wondering if maintaining a session on server-side in Django is possible or not? -
File uploading issue in django when static file is added
I have created file uploading page in my django web app.If the static files is not added with the template, it works fine.When I m adding static files, upload option is not working.Please help me to solve the problem -
Web and python suggestions
I have a python script. I have an html form, which takes user input from user. I have to call the python script with the user details as arguments and when the user clicks on submit button, I want to print the result of the python script in my html page. Some suggestions when I googled about it was to use Django, Flask, Ajax with PHP which calls Python. Can anyone tell me which one is ideal, or better ways to do the same. -
Django: Form Initial Value From Other Models via Foreign Key
I am working on an UpdateView of a form. I am having hard time displaying the initial value of grades per subject. I can display the subjects fine in the template, however I can't display the grades using the DecimalField. If change DecimalField to ModelChoiceField in forms.py, I can view the grades in a drop down menu in template but this is not what I want. I want the user to be able to edit using DecimalField. forms.py class GradeUpdateForm(CrispyFormMixin, forms.ModelForm): s_name = forms.ModelChoiceField(queryset=Subject.objects.none(), empty_label=None) final_grade = forms.DecimalField(widget=forms.NumberInput(attrs={'style':'width:80px'}), decimal_places=2, max_digits=5,) class Meta: model = SGrade fields = [ 's_name', 'final_grade', ] views.py class SchoolDashboardGradesUpdateView(SchoolStudentMixin, UpdateView): template_name = 'education/dashboard/grades_update.html' model = SubjectGrade form_class = GradeUpdateForm # def get_object(self): # return get_object_or_404(Recipient, pk=self.kwargs['pk']) def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) form.fields['subject_name'].queryset = Subject.objects.filter( sgrade__recipient__id=self.kwargs.get('pk'), sgrade__status='approved').values_list('name', flat=True) form.fields['final_grade'].queryset = SGrade.objects.filter( recipient__id=self.kwargs.get('pk'), status='approved').values_list('final_grade', flat=True) template <tbody> {% for instance in form.subject_name.field.choices %} <tr> <td>{{instance.1}}</td> <td>{{form.final_grade}}</td> </tr> {% endfor %} </tbody> Any suggestions on how to approach this? I am a complete beginner. -
".sock" does not exist error; connect() error
I'm trying to set up my Mezzanine/Django project on a virtual Ubuntu 14.04 box on Linode, but get a "502 Bad Gateway error" when trying to navigate to my site in my browser. I'm following the instructions here: https://linode.com/docs/web-servers/nginx/deploy-django-applications-using-uwsgi-and-nginx-on-ubuntu-14-04. I ran git clone in /home/django/, so everything's in a folder named FOLDER. /home/django/ has these directories: Env/ and FOLDER/. This should give some idea of what FOLDER/ tree looks like: FOLDER - product_blog -- product_blog --- settings.py --- wsgi.py -- manage.py In my settings.py, I have: ALLOWED_HOSTS = ["PUBLIC IP OF MY LINODE UBUNTU INSTANCE HERE"] wsgi.py has this: """ WSGI config for product_blog project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from mezzanine.utils.conf import real_project_name os.environ.setdefault("DJANGO_SETTINGS_MODULE", "%s.settings" % real_project_name("product_blog")) application = get_wsgi_application() /etc/uwsgi/sites/product_blog.ini has this: [uwsgi] project = product_blog base = /home/django chdir = %(base)/%(project) home = %(base)/Env/%(project) module = %(project).wsgi:application master = true processes = 2 socket = %(base)/%(project)/%(project).sock chmod-socket = 664 vacuum = true /etc/init/uwsgi.conf has this: description "uWSGI" start on runlevel [2345] stop on runlevel [06] respawn env UWSGI=/usr/local/bin/uwsgi env LOGTO=/var/log/uwsgi.log exec $UWSGI --master --emperor /etc/uwsgi/sites --die-on-term … -
Django rename method previously used in migration
I have a model.py file that looks something like def method_to_rename(instance, filename): return 'somthing/' + filename class Person(models.Model): photo = models.ImageField(upload_to=method_to_rename) This model has been through a couple of migrations. Now I'd like to rename the method_to_rename to method_renamed When I run makemigrations I get the following error triggered by the method existing in previous migrations: AttributeError: module 'person.models' has no attribute 'method_to_rename' Am I able to rename this method? I understand that the upload_to method has had some issues previously. -
How to set django project on apache Centos 7
I have created a django project on Centos7 and now I'm trying to make it work on apache web server. But in apache error log I see this errors: [Mon Apr 23 07:01:02.930780 2018] [:error] mod_wsgi (pid=26121): Target WSGI script '/he/django/myshop/myshop/wsgi.py' cannot be loaded as Python module. [Mon Apr 23 07:01:02.930821 2018] [:error] mod_wsgi (pid=26121): Exception occurred processing WSGI script '/he/django/myshop/myshop/wsgi.py'. [Mon Apr 23 07:01:02.930842 2018] [:error] Traceback (most recent call last): [Mon Apr 23 07:01:02.930864 2018] [:error] File "/he/django/myshop/myshop/wsgi.py", line 28, in <module> [Mon Apr 23 07:01:02.930922 2018] [:error] from django.core.wsgi import get_wsgi_application [Mon Apr 23 07:01:02.930947 2018] [:error] ImportError: No module named django.core.wsgi My project path is /he/django/myshop/. I havn't changed my default /he/django/myshop/myshop/wsgi.py file, so it looks like this: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myshop.settings") application = get_wsgi_application() My /etc/httpd/conf.d/htmltest.psina.com.conf looks like this: <VirtualHost *:80> ServerAdmin webmaster@example.com ServerName 185.201.8.84 ServerAlias www.example.com DocumentRoot /he/sites/htmltest.psina.com/htdocs/ LogLevel warn ErrorLog /var/log/httpd/htmltest.psina.com-error.log CustomLog /var/log/httpd/htmltest.psina.com-access.log combined WSGIScriptAlias / /he/django/myshop/myshop/wsgi.py </VirtualHost> WSGIPythonPath /he/django/myshop <Directory "/he/sites/htmltest.psina.com/htdocs"> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory "/he/django/myshop/myshop"> <Files wsgi.py> Require all granted </Files> </Directory> Firstly I've created .conf file for simple html page to check if apache was workig and everything was OK … -
How to Stop Kafka Producer from Django
I am using Django to build my application. In that, I have to start 2 Kafka producers developed using PyKafka, these producers fetch data from stream API and REST API using the Tweepy library and send to Kafka Broker. Intiliaized both producers using Process(). I have to stop my Producers through Django now, please help me how to achieve it. -
Some cases I can't see return value from print()
I asked question similar to this issue. I can't see return value from print() located in some class But I still didn't understand the reason of this question. When I run django server, following index method must be called. def index(request): print("fffffffffffffffffffffffffffffffffffffffffffffffffffff") print("request",request) return render(request, 'personal/home.html') Then, I will see home.html on the web browser. It means index() is called, right? But I can't see return value from print("fffffffffffffffffffffffffffffffffffffffffffffffffffff") and print("request",request) on terminal window, when I run command $python manage.py runserver Please, let me know the reason why this happens, how to see return value. -
i got these Errors like these
I got errors while running runtests.py... I use ubuntu 16.04 and Django version 1.6.5...I copied code from github ./runtests.py: line 3: os.environ[DJANGO_SETTINGS_MODULE]: command not found ./runtests.py: line 4: syntax error near unexpected token `(' ./runtests.py: line 4: `test_dir = os.path.dirname(__file__)' my runtest.py file: import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'test-settings' test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) import django from django.test.utils import get_runner from django.conf import settings def runtests(): if django.VERSION >= (1, 7): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests( ['quiz', 'essay', 'multichoice', 'true_false'] ) sys.exit(bool(failures)) if __name__ == '__main__': runtests() -
Python Django - How to support Socket and APIs both
I am using python 3 and Django 1.9 and frontend is android. I have to provide 2 connections one is via API so that user can use UI and send the his/her details to backend; second, socket connection for receiving Hardware details, failure logs and sending updates to app. Below is my Socket server. import socket, ssl, json from threading import Thread, active_count from socketserver import ThreadingMixIn #from serializers import create_log_entry # Multithreaded Python server : TCP Server Socket Thread Pool class ClientThread(Thread): def __init__(self,ip,port,conn): Thread.__init__(self) self.ip = ip self.port = port self.conn = conn print ("[+] New server socket thread started for " + ip + ":" + str(port), active_count() ) def run(self): connstream = ssl.wrap_socket(self.conn, server_side=True, certfile="/home/ubuntu/workspace/logs/server.crt", keyfile="/home/ubuntu/workspace/logs/server.key") while True : data = connstream.read() print ("Server received data:", data) if data != b"" : data = json.loads(data.decode("utf-8")) else: print("Exiting loop") break print ("Server received data:", data) #create_log_entry(data) connstream.send("OK".encode("utf-8")) # echo # Multithreaded Python server : TCP Server Socket Program Stub TCP_IP = '0.0.0.0' TCP_PORT = 2005 BUFFER_SIZE = 20 # Usually 1024, but we need quick response def socket_server(): tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpServer.bind((TCP_IP, TCP_PORT)) threads = [] while True: tcpServer.listen(4) print ("Multithreaded Python server … -
Uploading two files in single page in django
I am new to django.I want to upload two files in single page.I have created form for uploading one file.But with same code I have tried upload two files by making some changes.But I can't get it . Please help me to submitting two files in one submit button in a single page views.py from __future__ import unicode_literals from django.shortcuts import render from django.conf import settings from django.core.files.storage import FileSystemStorage from django.conf.urls import url #import csv def simple_upload(request): if request.method == 'POST' and request.FILES['myfile']: #request.FILES['myfile'] and request.FILES["myfile1"]: myfile = request.FILES['myfile'] #myfile1=request.FILES["myfile1"] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) #filename1=fs.save(myfile1.name, myfile1) uploaded_file_url = fs.url(filename) #uploaded_file_url1 = fs.url(filename1) #data = [row for row in csv.reader(myfile.read().splitlines())] return render(request, 'myapp/simple_upload.html', { 'uploaded_file_url': uploaded_file_url, }) #upload_file = request.FILES['upload_file'] #data = [row for row in csv.reader(upload_file.read().splitlines())] return render(request, 'myapp/simple_upload.html') def home(request): return render(request,'myapp/home.html') html {% block content %} <form method="post" enctype="multipart/form-data" required="True"> {% csrf_token %} <input type="file" name="myfile"> <button type="submit">Upload</button> /form> {% if uploaded_file_url %} <p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p> {% endif %} \\here some html for uploading 2nd file <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} -
Django REST Framework filter multiple fields
Models class Task(Model): employee_owner = ForeignKey(Employee, on_delete=CASCADE) employee_doer = ForeignKey(Employee, on_delete=CASCADE) Views class TaskViewSet(ModelViewSet): serializer_class = TaskSerializer queryset = Task.objects.all() filter_class = TaskFilter Filter class TaskFilter(FilterSet): doer_id = NumberFilter(name='employee_doer__id') owner_id = NumberFilter(name='employee_owner__id') class Meta: model = Task fields = { 'doer_id', 'owner_id' } Endpoints http://localhost:8000/api/tasks?owner_id=1&doer_id=1 (Gives only those tasks where owner and doer are the same employee) http://localhost:8000/api/tasks?owner_id=1 (Gives only those tasks where owner is specific employee and doer is anyone) http://localhost:8000/api/tasks?doer_id=1 (Gives only those tasks where doer is specific employee and owner is anyone) What I want I want an endpoint like: http://localhost:8000/api/tasks?both_id=1 (Which would give me all results from above 3 endpoints) I want django-filter to do filtering exactly like: Task.objects.filter(Q(employee_owner__id=1) | Q(employee_doer__id=1)) How can I achieve that ? Thank you. -
how to get objects of pages which is added from wagtail under particular field name
Requirements select some pages from wagtail under a particular field(example: highlights) in one page(example:home page) and i want to show some objects of selected pages in home page Question How to get objects of only selected pages in context[highlights]=??? -
Django get system time is not correct
I am using diango to get current system time. I used `python manage.py shell` and then get wrong time from cmd. However , when I use python ,it is correct. [enter image description here][1] My timezone settings in django is TIME_ZONE = 'Asia/Shanghai' USE_TZ = False BTW: I run my app in docker container.The time in docker is correct! Somebody help me ,It drivers me crazy.