Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best tool for implementing soap web service via django
forgive me if this question is naive. i'm new on django and i want to serve a soap web service. what is the best way for that? every answer or link would be appreciated. -
Cannot render chartit-django chart example
Im trying to build a dashboard in django framework using chartit. But the documentation seems to be for advanced people. Im a beginner trying to learn, so sorry. Im having a problem that i can render the chart in my dashboard. What i really dont understand in the docu was this, <!-- code to include the highcharts and jQuery libraries goes here --> <!-- load_charts filter takes a comma-separated list of id's where --> <!-- the charts need to be rendered to --> {% load chartit %} {{ weatherchart|load_charts:"container" }} i really dont understand those comments. What to put. Where to put it. Im rendering the chart to an extended html so i really dont know where to put it. Sorry im just a beginner im still learning. This is my base html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dashboard - Dark Admin</title> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'font-awesome/css/font-awesome.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'css/local.css' %}" /> <script type="text/javascript" src="{% static 'js/jquery-1.10.2.min.js' %}"></script> {% load chartit %} <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <!-- you need to include the shieldui css … -
Django form ImageField
I'm trying to establish CreateView for the model which holds ImageField. I can successfully upload and display images from django admin page. But, when I upload images from my own form, django doesn't upload images to "upload_to" folder. I'm writing my codes below: models.py from django.db import models class Album(models.Model): title = models.CharField(max_length=127) artist = models.CharField(max_length=63) release_date = models.DateField() logo = models.ImageField(blank=True, upload_to='album_logos', default='album_logos/no-image.jpg') def __str__(self): return self.title forms.py from django import forms from .models import Album class AlbumCreateForm(forms.ModelForm): class Meta: model = Album fields = [ 'title', 'artist', 'release_date', 'logo' ] views.py class AlbumCreateView(CreateView): form_class = AlbumCreateForm template_name = 'music/album_create.html' success_url = '/albums/' album_create.html {% extends 'base.html' %} {% block content %} <form method="post">{% csrf_token %} {{ form.as_p }} <button type="submit">Create</button> </form> {% endblock %} When I try to create album using "album_create.html" and upload image with django's default form, logo image isn't uploaded to "album_logos" folder and takes default value. Where am I doing wrong? -
Django: deleting a one-to-one related field in post_delete causes recursion
I have a model, say Model1 that has a OneToOne related field Model2. There is a post_delete signal connected method of Model1 that calls instance.model2.delete(), and very infrequently, this causes a recursive call back to the Model1.post_delete(). I've followed the stack trace, here is the recursion on Django 1.8 (most recent last): File "myapp/models.py", line 645, in post_delete instance.model2.delete() File "django/db/models/base.py", line 896, in delete collector.delete() File "django/db/models/deletion.py", line 314, in delete sender=model, instance=obj, using=self.using File "django/dispatch/dispatcher.py", line 189, in send response = receiver(signal=self, sender=sender, **named) File "myapp/models.py", line 645, in post_delete instance.model2.delete() File "django/db/models/base.py", line 896, in delete collector.delete() File "django/db/models/deletion.py", line 314, in delete sender=model, instance=obj, using=self.using File "django/dispatch/dispatcher.py", line 189, in send response = receiver(signal=self, sender=sender, **named) After following it many times in debug, and testing extensively with automation, I have come to the conclusion that the problem is that File "django/dispatch/dispatcher.py", line 189, in send response = receiver(signal=self, sender=sender, **named) is erroneously being called from File "django/db/models/deletion.py", line 314, in delete sender=model, instance=obj, using=self.using somehow. What could possibly be going on? -
error in template rendering django and bootstrap
I am using a bootstrap index file in the header.html in a django project. Can anyone point out a fix or the easiest method to link the bootstrap file to the static folder. In what places does it need to be done, and how? Also, for use of bootstrap, could I just use the index file rather than header? I can see the error (below) but do not know the syntax to fix it. The route i've tried is using Jinja logic and it is on that line that the first error arises. (line 14) Current error: Error during template rendering In template C:\Users\User\Desktop\pythonsite\mysite\aboutme\templates\aboutme\header.html, error at line 14 Invalid block tag on line 14: 'static'. Did you forget to register or load this tag? 4 <head> 5 6 <meta charset="utf-8"> 7 <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 8 <meta name="description" content=""> 9 <meta name="author" content=""> 10 11 <title>Freelancer - Start Bootstrap Theme</title> 12 13 <!-- Bootstrap core CSS --> 14 <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> 15 16 <!-- Custom fonts for this template --> 17 <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> 18 <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> 19 <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> 20 21 <!-- Plugin CSS --> 22 <link href="{% static 'vendor/magnific-popup/magnific-popup.css' … -
Django Admin Site-Wide CSS and JS
I'm wondering if there is an efficient way to add custom css and js to Django Admin in order to include in all pages through whole admin site. For example adding some options to settings.py or some useful packages which compatible with Grappelli Admin. I'm using Django 1.11 with Grappelli Admin 2.10.1 Thanks for the help. -
fix invalid geometries in django (without database)
I have polygon that I'm getting from external source. The polygon is not valid. In [36]: p Out[36]: <Polygon object at 0x7fec6bea6ac0> In [37]: p.valid [12/Dec/2017 19:13:19] WARNING [django.contrib.gis:85] GEOS_NOTICE: Hole lies outside shell at or near point 260561.40600000042 776052 I know that I can fix the polygon in the DB using the MakeValid() django function. Is there a way to fix the polygon before it is inserted to the DB, just using geos API? Thanks. -
Django show unique together fields in one model in another model's template
A Django newbie here. I have searched but couldn't find an answer to my question (or I didn't know the right keywords to look up) I have a model with a unique together columns in addition to a PK- class RegEntry(models.Model): id = models.AutoField(primary_key=True) product = models.ForeignKey('data.Product', on_delete=models.PROTECT) account_id = models.CharField(max_length=64) nominee_name = models.CharField(max_length=128) nominee_id = models.CharField(max_length=128) nominee_account_id = models.CharField(max_length=64, null=True) address = models.CharField(max_length=255, null=True objects = RegisterQuerySet.as_manager() class Meta: unique_together = (('date', 'product', 'nominee_id'),) index_together = ( ('nominee_id', 'date'), ('product', 'date'), ) ordering = ['date', 'product', 'nominee_id'] I have another model that is based on the previous model and has it's own PK - class Attribute(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(db_index=True) product = models.ForeignKey('data.Product', on_delete=models.PROTECT) nominee_id = models.CharField(max_length=255) beneficiary_name = models.CharField(max_length=128) class Meta: unique_together = (('date', 'product', 'nominee_id', 'beneficiary_name'),) index_together = ( ('date', 'product', 'nominee_id'), ('is_processed',) ) ordering = ['date', 'product', 'nominee_id', 'beneficiary_name'] I need to display the manualatrribution model using ModelForm and associated template, but also need to display the product name and nominee name. I got to the part where I could render Model Form but couldn't figure out the linking part. Will be very grateful for any advice from the experts here. -
django collectstatic with template processor
Is it possible to use templates for static files? I would like django could process the static files with template processor before copying them in the static folder when manage collectstatic is issued. Of course the context would not contain request information but it could be useful to use such information as: urls from url names to be used in javascript code settings to be used to customize css or static html pages What is the simpler way to accomplish this? -
PostgreSQL with Django: transaction is aborted error
I have PostgreSQL and Django 1.8. When I try to create an MyModel object via Django ORM, I get InternalError current transaction is aborted, commands ignored until end of transaction block. My code look like: MyModel.objects.get_or_create(client=client, defaults={ 'email': client.user.email, 'name': client.name, 'phone_number': '77644017513' }) But when I modify MyModel via psql (I tried to delete a record) everything is just fine. When I try to create object from another model (not MyModel) everything is fine too. What is wrong with MyModel? -
POST request not behaving as intended
I've been trying to get my button to send a POST request to the submitted URL, which does a write back to the database. The application looks like the POST request gets sent, but after hitting the button my URL never changes and the print at the submitted URL appears to be an empty set. This is my jquery/ajax call for the button: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <button class="btn btn-primary my_select" type="submit">Request Access</button> <script> $(document).ready(function () { $('form').on('submit', function (e) { e.preventDefault(); var phi = $('#phi').val(); var accesslevelid = $('#accesslevelid').val(); $.ajax({ url: "{% url 'submitted' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' }, data: { phi: phi, accesslevelid: accesslevelid, }, type: 'POST', success: function (result) { // do something with result }, }); }); }); </script> I'm expecting my POST of the Application List, PHI flag, and Access Level gets sent as a POST to my submitted URL. My view for submitted is the following: def submitted(request): owner = User.objects.get (formattedusername=request.user.formattedusername) checkedlist = request.POST.getlist('report_id') coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername) facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True) divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True) print (checkedlist) selectedaccesslevel = request.POST.get('accesslevelid') … -
Add object to to manytomany relationship
i'm trying to add ticker values to a currency object using a custom command, but i can't seem to be able to add the ticker to the CurrencyTickerSerializer? i get following error TypeError: 'QuerySet' object does not support item assignment. I run this command in a specific interval that is suppose to add the ticker into the specific currency, but i guess i need to add something in order to being able to add the ticker into TickerSerializer? Command class Command(BaseCommand): def handle(self, *args, **options): comparison='DKK' url = 'URL' page = requests.get(url) data = page.json() response_data = {} for ticker in data: currency = Currency.objects.filter(symbol=ticker['symbol'], is_active=True) if currency.exists(): currency['tickers'] = ticker serializer = CurrencyTickerSerializer(data=currency) if serializer.is_valid(): serializer.save() serializers class TickerSerializer(serializers.HyperlinkedModelSerializer): currency = serializers.PrimaryKeyRelatedField(many=False, queryset=Currency.objects.all()) class Meta: model = Ticker fields = ('currency', 'rank', 'price_dkk', 'market_cap_dkk', 'percent_change_1h', 'percent_change_24h', 'percent_change_7d',) class CurrencyTickerSerializer(serializers.HyperlinkedModelSerializer): tickers = TickerSerializer(many=True) class Meta: model = Currency fields = ('id', 'name','symbol', 'tickers', ) Models class Ticker(models.Model): rank = models.IntegerField() price_dkk = models.DecimalField(max_digits=20, decimal_places=6) market_cap_dkk = models.BigIntegerField() percent_change_1h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_24h = models.DecimalField(max_digits=4, decimal_places=2) percent_change_7d = models.DecimalField(max_digits=4, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = _('Ticker') def __str__(self): return self.id class Currency(models.Model): symbol = models.CharField(max_length=4, default='BTC', unique=True) name = … -
Can we serve angular 4 in django server?
I'm trying to integrate Django and Angular 4 in the same app . Like in angularjs we could include cdn and serve. How to do in angular v4? -
Django not finding custom user model in settings when migrating
I've created a custom User model in models.py: class User(AbstractUser): pass Then, I've set AUTH_USER_MODEL to that model, in settings.py: AUTH_USER_MODEL = 'workoutcal.User' workoutcal is included in INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'workoutcal', 'rest_framework', 'rest_framework_mongoengine', ] And I've included this in admin.py: admin.site.register(User, UserAdmin) Then, I've ran makemigrations and migrate, and on the latter, I get this long error traceback: (workout) sahands-mbp:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying admin.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/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 "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/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 "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 97, in database_forwards schema_editor.create_model(model) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 254, in create_model definition, extra_params = self.column_sql(model, field) File … -
adding multiple markers on GoogleMaps
I am trying to retrieve the lat long values from my db and visualise them on googlemap. I'm not sure how do I access those fields using for loop models.py import json from django.db import models from django.utils.translation import ugettext_lazy as _ class LocateGoose(models.Model): class Meta: app_label = 'My Goose' verbose_name = _('Where is the Goose?') external_id = models.IntegerField(unique=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) name = models.TextField(max_length=250, null=True, blank=True) address = models.TextField(max_length=25, null=True, blank=True) views.py from edrive.mygoose.models import LocateGoose from django.shortcuts import render def testgmap(request): data = LocateGoose.objects.all() template = 'hereismygoose.html' return render(request, template, {"data": data}) hereismygoose.html function initMap() { var myLatLng = {lat: 52.0116, lng: 4.3571}; var map = new google.maps.Map(document.getElementById('map'), { zoom: 10, center: myLatLng }); var marker = new google.maps.Marker({ position: myLatLng, map: map, title: 'stringLocate me!' }); map.setOptions({ minZoom: 4, maxZoom: 10 }); } -
How to enable DRF throttling after too many 403 responses?
I have an API endpoint that has a permission class which may throw 403 in some cases. I wonder how to enable throttling after some number of 403 responses to this endpoint? Suppose a user made 10 unsuccessful requests and I want to rate limit the endpoint for him. I see that DRF comes with throttling module that enables to filter requests before making them, but I am not sure how to do what I am willing to do. -
Update already existing data in database
I am trying to use the "update ()" to update existing data in the data base of the "ModelC". Models: from django.db import models class ModelA(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return '%s' %(self.id) class ModelB(models.Model): observation = models.CharField(max_length=30) status = models.BooleanField() relation = OneToOneField(ModelA) def __str__(self): return '%s' %(self.relation) class ModelC(models.Model): relationA = models.ForeignKey('ModelA', null=True, blank=True) date_relationA = models.CharField(max_length=10, null=True, blank=True) user_relationA = models.CharField(max_length=15, null=True, blank=True) relationB = models.ForeignKey('ModelB', null=True, blank=True) date_relationB = models.CharField(max_length=10, null=True, blank=True) user_relationB = models.CharField(max_length=15, null=True, blank=True) def __str__(self): return str(self.id) Views of the ModelA: def RegModelA(request): form = "" user = None if request.method == "POST": form = ModelAForm(request.POST) if form.is_valid(): save = form.save() date = time.strftime("%d - %m - %Y") user = request.user.username create = ModelC.objects.create(relationA=save, date_relationA=date, user_relationA=user, relationB=None, date_relationB=None, user_relationB=None) return redirect('/') else: form = ModelAForm return render(request, "ModelA.html", {"form":form}) **Result when registering ModelA:** In ModelA: Image of the result In ModelC: Image of the result Views of the ModelB: def RegModelB(request): form = "" user = None if request.method == "POST": form = ModelBForm(request.POST) if form.is_valid(): save = form.save() date = time.strftime("%d - %m - %Y") user = request.user.username update = ModelC.objects.filter().update(relationB=save, date_relationB=date, user_relationB=user) return redirect('/') else: form … -
Django URLs file error
I have the following urls.py file in a Django project, and I am getting an error which I assume is relating to the latest syntax relating to urls and paths. The code I have in the urls file which is url.py in the mysite (outermost directory) is: from django.urls import path from django.conf.urls import url, include urlpatterns = [ path(r'^$', include('aboutme.urls')), ] The error message is: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^$ The empty path didn't match any of these. In the actual app (website folder) which is called 'aboutme', the urls.py file looks like this: from django.urls import path from django.conf.urls import url, include from .import views #this is the main thing we are going to be doing ....returning views! urlpatterns = [ path(r'^$', views.index,name='index'), ] Can anyone shed any light on the correct syntax or what I am doing wrong? -
Celery tasks are not always getting executed in the right order
I have several periodic tasks that run every few minutes/hours along with many more event-driven tasks. Sometimes an event-driven task will be received by a worker that is already busy executing one of the longer periodic tasks, and then the event-driven task will not run until the longer periodic task is completed. I checked using celery flower, and there ARE available workers, so I don't understand why the busy worker claimed the task. I would like the event-driven task to go to an available worker. I have a machine with 16 workers and celery beat running. I am running Celery 4.1.0 with Django 1.8.16. I am also using Redis as my broker. Here are the commands used to start all the celery workers: celery beat -A proj & celery multi start 16 -A proj -l info -c1 -Ofair -
ImproperlyConfigured: Error loading psycopg2 module: No module named cffi
I developed a platform with django + wsgi + pypy + postgresql + postgis, everything works fine in development environment, but in production it sends error 500 and in the apache log it says ImproperlyConfigured: Error loading psycopg2 module: No module named cffi my config apache: <VirtualHost *:80> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIScriptAlias / /home/user/plataform/project/project/wsgi.py WSGIDaemonProcess project python-path=/home/user/plataform/project:/home/user/env/site-packages WSGIProcessGroup project WSGIPassAuthorization On <Directory /home/user/plataform/project/project> <Files wsgi.py> Require all granted </Files> </Directory> Alias /media /home/user/plataform/project/media/ Alias /static /home/user/plataform/project/static/ <Directory /home/user/plataform/project/static> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /home/user/plataform/project/media> Require all granted </Directory> my pip freeze cffi==1.6.0 Django==1.11.7 django-cors-headers==2.1.0 django-filter==1.1.0 djangorestframework==3.7.3 greenlet==0.4.9 Markdown==2.6.9 olefile==0.44 Pillow==4.3.0 psycopg2cffi==2.7.7 python-stdnum==1.7 pytz==2017.3 readline==6.2.4.1 six==1.11.0 uWSGI==2.0.15 Log Apache: [Tue Dec 12 11:15:49.727998 2017] [wsgi:warn] [pid 4975:tid 139854422423424] mod_wsgi: Compiled for Python/2.7.11. [Tue Dec 12 11:15:49.728151 2017] [wsgi:warn] [pid 4975:tid 139854422423424] mod_wsgi: Runtime using Python/2.7.12. [Tue Dec 12 11:15:49.729853 2017] [mpm_event:notice] [pid 4975:tid 139854422423424] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Dec 12 11:15:49.729893 2017] [core:notice] [pid 4975:tid 139854422423424] AH00094: Command line: '/usr/sbin/apache2' [Tue Dec 12 11:15:59.608678 2017] [wsgi:error] [pid 4978:tid 139854259615488] [remote ::1:30039] mod_wsgi (pid=4978): Target WSGI script '/home/user/plataform/project/project/wsgi.py' cannot be loaded as Python module. [Tue Dec 12 11:15:59.608785 … -
Avoid concurrent access to same queue element
I'm reviewing/refactoring a queue that's going to be used internally by up to 20 people simultaneously but as of now, multiple people can access the first element ( We tried it locally clicking on the link at the same time. ) The flux is similar to this: views.py [GET] def list_operator(request, id): if request.POST: utilitary = Utilitary(id) pool = ThreadPool(processes=1) async_result = pool.apply_async(utilitary.recover_people, (id, )) return_val = async_result.get() person = People.objects.get(pk=return_val) return redirect('people:people_update', person.pk) utilitary.py This file has the method recover_people which performs around 4-5 queries (where people have flag_allocated=False) across multiple tables and sorts a list, to return the first element. The final step is this one: for person in people: p_address = People_Address.objects.get(person_id=person.id) p_schedule = Schedules.objects.get(schedules_state=p_address.p_state) if datetime.now() > parse_time(p_schedule.schedules_hour): person = People.objects.get(pk=person.id) person.flag_allocated = True person.date_of_allocation = datetime.now() person.save() return person.pk Perhaps something in the Utilitary method's logic is wrong? Or I should be expecting this problem with this amount of people simultaneously calling this method? Could using a cache help? I'm sorry, I'm new to django and mvc. -
Django application not running with Gunicorn and Supervisor
I am trying to run a Django application from gunicorn and supervisord. I have configured bash script to run application from gunicorn which is working fine and I am able to see the GUI but when I was trying to start this application from supervisorctl. I am not able to see the GUI. However, Gunicorn processes are running. gunicorn_start2 #!/bin/bash export ANALYTICS_ENV="dev" NAME="analytics" # Name of the application DJANGODIR=/home/ubuntu/code/current/analytics/analytics/analysis/ # Django project directory SOCKFILE=/home/ubuntu/code/current/analytics/analytics/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=analytics.settings # which settings file should Django use DJANGO_WSGI_MODULE=analytics.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR echo $DJANGODIR source /home/ubuntu/code/current/analytics/analytics/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE #export PYTHONPATH=$DJANGODIR:$PYTHONPATH #export PYTHONPATH=/home/ubuntu/code/analytics/bin/python # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/ubuntu/code/current/analytics/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=all \ --log-file=- gunicorn_start.conf [program:analytics] command … -
Como puedo hacer para que servicio Rest con DRF me retorne un archivo csv como respuesta.
Estoy intentado que mi servicio rest con DRF me devuelva un archivo csv descargable. y me codigo es el siguiente : class OperationsReportOrders(APIView): def post(self, request): if request.method == "POST": #Aqui va toda la logica donde obtengo toda la data que necesito para mi csv y lo almaceno en file_rows file_rows.append(row) # Creo file_rows donde se encuentra toda la data a escribir en csv #Escribo el archivo CSV with open('orders.csv', 'wb') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerows(file_rows) #Armo el response csv_file = open('orders.csv', 'rb') response = HttpResponse(FileWrapper(csv_file), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % 'orders.csv' return response else: return Response("Metodo no autorizado", status=status.HTTP_405_METHOD_NOT_ALLOWED) Mi Defaul render class esta asi: 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), Luego le agrego otro render: 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework_csv.renderers.CSVRenderer', ), y a mi clase le agrego: renderer_classes = (r.CSVRenderer, ) pero al momento de hacer un request con con Content-Type igual A text/csv Me retorna la siguiente: { "detail": "Unsupported media type \"text/csv\" in request." } -
maintain HTTP Response headers after redirect from django application using apache
I am trying to do something like this Django set headers on redirect() The solution I see here to set 'token' it in cookie.However I don't want to keep it in a cookie as I think cookie might still be there in browser in case user does not logged out. I am using Apache web server . Is there any configuration in apache through which I can retain my 'token' which I set in HTTP headers? -
template doesnt exist "django 2.0"
please can anyone help me i cant figure out what is the error while rendering template in djano 2.0 i created a app and and in the views.py section i added all thoe code lines of manange.py imported urls(directly in the views ) tried to run the server (python views.py runserver) here is my complete code from views.py import os import sys from django.conf import settings DEBUG = os.environ.get('DEBUG', 'on') == 'on' SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(32)) ALLOWED_HOSTS = os.environ.get( 'localhost','127.0.0.1').split(',') BASE_DIR = os.path.dirname(__file__) settings.configure( DEBUG=DEBUG, SECRET_KEY=SECRET_KEY, ALLOWED_HOSTS=ALLOWED_HOSTS, ROOT_URLCONF=__name__, MIDDLEWARE_CLASSES=( 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ), ) INSTALLED_APPS=( 'django.contrib.staticfiles', 'django.contrib.contenttypes', 'django.contrib.auth', ), TEMPLATE_DIRS=( os.path.join(BASE_DIR, 'templates'), ), STATICFILES_DIRS=( os.path.join(BASE_DIR, 'static'), ), STATIC_URL='/static/', #############################views & urls###############################s from django import forms from django.urls import path,include from django.core.cache import cache from django.core.wsgi import get_wsgi_application from django.http import HttpResponse, HttpResponseBadRequest from django.shortcuts import render from django.views.decorators.http import etag # Create your views here. application = get_wsgi_application() def home(request): return render(request,'index.html') urlpatterns=[ path('',home,name='home'), ] ###################################### ############################################# if __name__ == "__main__": from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) and i tried placing templates in the same directory where views exist and also in outside of the app folder i should be getting a basic template as explained in the book lightweight django …