Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'encodings' in Django on NGINX / uWSGI
Django 2.2 running on Ubuntu 16.04 / NGINX / uWSGI / Python 3.6 I keep getting: ModuleNotFoundError: No module named 'encodings' in the uWSGI error logs when trying to reload uWSGI. Also, uWSGI will restart without an error message, but it won't reload. Even when it restarts, however, the problem app is not started. uWSGI configuration file: [uwsgi] chdir = /var/sites/mysite module = mysite.wsgi virtualenv = /opt/virtualenvs/mysite_venv processes = 5 vacuum = True -
No schema supplied error when creating user but it gets created anyway
I'm following this tutorial to implement an API using Django RestFramework. I've implemented the OAuth2 API and now I'm getting this error when creating a user. I'm not sure if it's related to the OAuth2 API, I think it does because the error says: Exception Type: MissingSchema at /authentication/register/ Exception Value: Invalid URL '127.0.0.1/o/token/': No schema supplied. Perhaps you meant http://127.0.0.1/o/token/? And the URL /authentication/register/ was implemented when implementing the OAuth API. When using the following command to create a user I get an error, but even with this error, the user is created in data base. $ curl -d "username=halfsping&password=1234abcd" "http://127.0.0.1:8000/authentication/register/" part of the error: Exception Type: MissingSchema at /authentication/register/ Exception Value: Invalid URL '127.0.0.1/o/token/': No schema supplied. Perhaps you meant http://127.0.0.1/o/token/? It does not matter if I use this instead: $ curl -d "username=halfsping&password=1234abcd" "http://127.0.0.1:8000/authentication/register/" proyect's urls.py: from django.contrib import admin from django.urls import path, include from rest_framework import routers from core.views import * from unicorns.views import UnicornViewSet router = routers.DefaultRouter() router.register(r'customers', CustomerViewSet) router.register(r'professions', ProfessionViewSet) router.register(r'data-sheet', DataSheetViewSet) router.register(r'document', DocumentViewSet) router.register(r'unicorn', UnicornViewSet) urlpatterns = [ path('admin/', admin.site.urls), # Authentication path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), path('authentication/', include('users.urls')), # API path('api/', include(router.urls)), path('api-auth/', include('rest_framework.urls')), ] Complete error: Internal Server Error: /authentication/register/ Traceback (most … -
Django responds with file contents but does not prompt for download
I am working on a Django app where the user clicks a button, calling a python script to do work, and then downloads a .zip file created by said work. I have checked that the file is created successfully, and in javascript I used an alert to print the response from the server. The file's contents are returned, but there is no file download appearing in browser/anywhere on my computer. Here is the code I am using for downloading : if os.path.exists(zip_file_location_server): with open(zip_file_location_server, 'rb') as zip_file: response = HttpResponse(FileWrapper(zip_file), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="foo.zip"' return response I have tried: Removing the FileWrapper (leaving just the file object as the first argument to HttpResponse) Changing the filename argument to zip_file_location_server Changing the content_type argument to application/force-download All to no avail. What am I missing to download the returned .zip file? -
Rendering a FormSet in Django
I want to create a FormSet which allows users to add forms as needed. However, when I render the page, I am receiving a ValueError: The view website.views.presales didn't return an HttpResponse object. It returned None instead. I would like to always render the form blank. Please let me know if any other information is needed, thanks! Note: cwObj.get_opportunities() is an API call to create an object from a JSON response to populate the select_opportunity dropdown. Lastly, I am using AJAX to dynamically calculate the value of the span Total using data-total-url="{% url 'presales_total' %}". forms.py class PresalesForm(forms.Form): class Meta: model = Presales fields = ('selected_opportunity', 'task_description', 'hours', 'selected_engineer_level', 'total_cost') views.py def presales(request): my_opportunities = cwObj.get_opportunities() PresalesFormSet = formset_factory(PresalesForm, extra=1) if request.method == 'POST': presales_formset = PresalesFormSet(request.POST) if presales_formset.is_valid(): for presales_form in presales_formset: selected_opportunity = request.POST.get('selected_opportunity') task_description = request.POST.get('task_description') hours = request.POST.get('hours') select_engineer_level = request.POST.get('select_engineer_level') else: presales_formset = PresalesFormSet(initial="None") context = {'presales_formset': presales_formset, 'my_opportunities': my_opportunities} return render(request, 'website/presales.html', context) presales.html <form action="{% url 'presales' %}" method="post" name="presalesForm" id="presalesForm" data-total-url="{% url 'presales_total' %}"> {% csrf_token %} {{ presales_formset.management_form }} {% for presales_form in presales_formset %} <div class="field"> <label class="label is-large">Create Task</label> </div> <div class="section"> <div class="field"> <label class="label">Opportunity</label> <div class="select"> <select … -
Django Custom User Login
I created a cumstom user by inhering 'AbstractBaseUser' class AppUser(AbstractBaseUser, PermissionsMixin): """ Custom User """ username = None email = models.EmailField(_('email address'), unique=True) name = models.CharField(max_length=100) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] objects = UserManager() def __str__(self): return self.email I am able to register new user but facing problem to login using: path('api-auth/', include('rest_framework.urls')) I can login in admin portal but not able to login by api - shared the screen -
Why should a self-modifying method not return its self?
I recently found in this accepted answer, "It's generally considered good practice in Python to have functions that primarily affect existing objects not return themselves. " Why? (Both in general, and with particular reference to an ORM .save() method, which can only fail by raising an exception, not by returning some failure code). -
Right settings for uwsgi.ini file with Django and pipenv
Usually, I don't use pipen and working with virtualenv, virtualenvwrapper and requirements.txt with my django projects. In this case my uwsgi.ini file looks like: [uwsgi] project = cv-base uid = cvc base = /home/%(uid) chdir = %(base)/%(project) home = %(base)**/Env**/%(project) <----!!!!!!! module = %(project).wsgi:application master = true processes = 5 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):www-data chmod-socket = 660 vacuum = true Where values home have links to my virtualenv thrue folder Env. But now I cant have this folder, and cant unrestand what to substitute here. At log file I got an error !!! Python Home is not a directory: /home/cvc/Env/cv-base !!! Jun 26 13:48:55 CV-base uwsgi[12482]: Set PythonHome to /home/cvc/Env/cv-base -
Parse a dictionary in django template
I have a dictionary A A: {<truck_name: Tempo 407 1500>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>], <truck_name: Tempo 407 1500>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBat ch: Iphone>], <truck_name: Tempo 407 2000>: [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>]} Can I parse this dictionary in django template? views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dispatch_plans = DispatchPlan.objects.filter(owner_id=self.request.user.pk) idict = {} print("dispatch_plans", dispatch_plans) for i in dispatch_plans: t = i.truck_name idict[t] = [get_object_or_404(ItemBatch, id=v_id) for v_id in i.items] context['items'] = idict return context html {% for x,v in items.items %} <tr> <td>{{ v }}</td> </tr> {% endfor %} I have tried the above but it doesn't show anything on the HTML page, What do i need to change to parse it ? -
Django foreignkey mismatch error not allowing classes to have relation in database
I am trying to add a foreign key to the posts class so that each person can have multiple posts, I keep getting a foreign key mismatch error. The tables are empty. I don't understand what the problem here is. """ Definition of models. """ from django.db import models # Create your models here. class Users(models.Model): name = models.CharField(primary_key=True, max_length=30) class Posts(models.Model): priority = models.CharField(max_length=30) client = models.CharField(max_length=30) title = models.CharField(max_length=150) assigned_to = models.ForeignKey(Users, on_delete=models.CASCADE) exp_comp_time = models.FloatField(max_length=4) percent_comp = models.FloatField(max_length=4) post_date = models.CharField(max_length=20) due_date = models.CharField(max_length=20) latest_mod = models.CharField(max_length=20, null=True) When I go to migrate I get this error: django.db.utils.operationalError: foreign key mismatch - "app_posts" referencing "app_users" -
Date subtraction from two date column Django ORM for filter
I have two keys/columns in MongoDB. I am using Django ORM to get data from mongo using a connector called djongo. I need a apply a filter. I have to take a difference from the column date and check if the difference is less than 24 hours. This is my query - time_threshold = datetime.datetime.now() - timedelta(days=1) total_count = ArticleFeed.objects.annotate( diff=ExpressionWrapper(F('crawled') - F('published'), output_field=DurationField()) ).filter(diff__lte=time_threshold, crawled__lte=report_start_ISO, crawled__gte=last_ISO, data_source="TOI").exclude( reject='repeat').count() But I am getting the following exception - File "/home/embed/inmobi/content_curation_project/ccp_env/lib/python3.7/site-packages/django/db/backends/base/operations.py", line 621, in subtract_temporals raise NotSupportedError("This backend does not support %s subtraction." % internal_type) django.db.utils.NotSupportedError: This backend does not support DateTimeField subtraction. Please help. Thanks -
django + gunicorn + virtualenv + supervisor + nginx. click home issue
my website (blog) use django + gunicorn + virtualenv + supervisor + nginx. when my website didn't add nginx ,everything works fine. after i add nginx in my website, i click my blog 'home',url show 'mydjangoblogserver' and result is not found, but other functions work fine except 'click home'. i think nginx and gunicorn set is problem, just guess. here is my settings. ngnix conf --------------------------------------------------------------------- user root; worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream mydjangoblogserver { server unix:/home/blog/dev/DjangoBlog/run/gunicorn.sock fail_timeout=0; } server{ server_name www.xxx.club; root /home/blog/dev/DjangoBlog; listen 80; keepalive_timeout 70; location /collectedstatic/ { expires max; alias /home/blog/dev/DjangoBlog/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; if (!-f $request_filename) { #proxy_pass http://xxx.club; proxy_pass http://mydjangoblogserver; break; } } } django_start file ------------------------------------------------------------ #!/bin/bash NAME="djangoblog" # Name of the application DJANGODIR=/home/blog/dev/DjangoBlog # Django project directory SOCKFILE=/home/blog/dev/DjangoBlog/run/gunicorn.sock # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=DjangoBlog.settings # which settings file should Django use DJANGO_WSGI_MODULE=DjangoBlog.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source … -
Migrate existing database fields.E340 error on run
Hey everyone I'm fairly new to Python Anywhere, I'm running a django app on python 3.7, I've manually added the tables and fields I need via SSH in MySQL Workbench and ran [migrate.py inpectdb > /app/models.py] then makemigrations then when I run Migrate I get this: ERRORS: auth.Group.permissions: (fields.E340) The field's intermediary table 'auth_group_permissions' clashes with the table name of 'app.AuthGroupPermissions'. auth.User.groups: (fields.E340) The field's intermediary table 'auth_user_groups' clashes with the table name of 'app.AuthUserGroups'. auth.User.user_permissions: (fields.E340) The field's intermediary table 'auth_user_user_permissions' clashes with the table name of 'app.AuthUserUserPermissions'. If I remove the auth tables from the models.py and try to migrate I get: File "/usr/lib/python3.7/site-packages/MySQLdb/connections.py", line 276, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') From what I've read it is conflicting with the settings.py [INSTALLED_APPS] but I'm not sure where to go from here to get the migration to work properly. -
my local python server don't know my static css file to run
i inserted a css file to my django project (in 'static' directory) and set address of this css to my index.html file (in 'template' directory) according to django dacumentation but my css dosn't work! this is my addresses: myproject/myapp/templates/html/index.html myproject/myapp/static/css/index.css this is my html: {% load static %} <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head lang="eng"> <link rel="stylesheet" type="text/css" href={% static "myapp/index.css" %}/> </head> <body onload="myFunction()"> ----some code---- </body> </html> this is my setting.py file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') but my css dosn't work! please help me to run myproject completely -
Any tool to create graphs from data of a tree?
is there any simply and easy to use tool for Django (or for python) which is going to create a nice graphicon from the datas of a tree? Of course i can format the datas in any way, i just need a program which can process it and create a graphicon for it, like: https://en.wikipedia.org/wiki/Tree_(data_structure)#/media/File:Binary_tree.svg . It' s only a tree, no circle inside. Actually i' m using django-treenode . Thanks for any tip, idea. -
Is there a way i can submit my a registration form and show the flash message?
im creating a registeration form in django and i want to submit the form and redirect me to the home page with the flash message. i have created the register view and the form and set the flash message as well. views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') base.html <div class="col-md-8"> <!--for flash message--> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </div> i expect it to submit the form and register a user and redirect me to the home page and show the flash message as well -
elastic-Search Aggregation [python]
I indexed the post and community models, post = Index('posts') post.settings( number_of_shards=1, number_of_replicas=0 ) @post.doc_type class PostDocument(DocType): community = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'description': fields.TextField(), 'name': fields.StringField(), }) I want to search posts and aggregate the communities (returns communities of the posts in the result) I may need to use aggregation, I had difficulties while implementing it, the documentation was not clear for me. q = Q("multi_match", query=query, fields=['title', 'content']) document.query(q) document.aggs.bucket('per_tag', 'terms', field='community') -
Celery django tasks ModuleNotFoundError
I am running into a strange ModuleNotFoundError. I am making a docker-compose network where tasks are shared between containers by a shared volume. the volume looks like this: celery_use │ celery_config.py │ tasks.py │ __init__.py # celery_config.py import os from celery import Celery app = Celery(include=('celery_use.tasks',)) # tasks.py from celery.utils.log import get_task_logger from .celery_config import app import os logger = get_task_logger(__name__) @app.task(bind=True, name='process_availability', queue='availability') def process_availability(self, message): print(os.getcwd()) print(os.listdir()) from avail.models import AvailabilityConfirmation my docker-compose file looks like this: version: '3.3' services: pas-gateway: build: context: ./ dockerfile: Dockerfile.pas command: bash -c "python appserver.py" environment: &env - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672 depends_on: - rabbitmq ports: - 18000:8000 restart: 'no' volumes: - ./pas_gateway:/pas_gateway - ./celery_use:/pas_gateway/celery_use/ django: build: context: ./ dockerfile: Dockerfile.django command: python manage.py runserver 0.0.0.0:8001 ports: - 18001:8001 environment: *env depends_on: - rabbitmq - postgres volumes: - ./ops_interface:/code django-celery: build: context: ./ dockerfile: Dockerfile.django command: bash -c "celery worker --app=celery_use.celery_config:app --concurrency=20 --queues=availability --loglevel=INFO" environment: *env depends_on: - rabbitmq - postgres volumes: - ./ops_interface:/code - ./celery_use:/code/project/celery_use postgres: image: postgres ports: - "15432:5432" volumes: - postgres-data:/var/lib/postgresql/data rabbitmq: image: rabbitmq:3.7.8 volumes: postgres-data: Dockerfile.django looks like this FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY ./requirements.txt /code/ RUN pip install -r requirements.txt COPY ./ops_interface/ /code/ … -
Django Rest Framework save to a model with an ImageField
I have the following model: class ProgressImage(TimeStampedModel): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='progressimages') image = models.ImageField( upload_to=obfuscate_filename, storage=storage, null=True) This is the serializer class: class ProgressImageSerializer(serializers.ModelSerializer): class Meta: model = ProgressImage fields = ('image', 'created') And this is the view set class: class ProgressImageViewSet(viewsets.ModelViewSet): serializer_class = ProgressImageSerializer queryset = ProgressImage.objects.all() filter_backends = (IsOwnerFilterBackend,) http_method_names = ['get', 'post'] permission_classes = (IsAuthenticated,) def perform_create(self, serializer): serializer.save(user=self.request.user) What I don't understand is how to perform the image save. Probably somewhere in the view set, but I don't know how. Anyone knows? -
DRF: Do not expost API
I am using Django with Django Rest Framework. I have disabled the browseable api in the settings.py file, however, when I visit http://mysite.api I get this response: {"api/projects":"http://example.com/api/projects/"} I don't want it to print that, it shouldn't print anything. I didn't define that endpoint. How can I tell DRF not to expose any information about my API unless I specifically tell it to? REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } -
How to run nodejs server as a background task in jenkins and restart the server on autobuild?
I'm currently working on nodejs application. I need to make frequent changes to it. I have a job set up in jenkins which automatically builds if changes are made. The job runs django and node api concurrently as background tasks but severs do not restart after autobuild. I've tried using nohup , forever start and pm2 start. commands used - nohup python3 manage.py runserver ...:**** & pm2 start app.js How to run django and nodejs servers as background tasks in jenkins and automatically restart if changes are pushed? -
Django build efficiency with API
I have silly question about efficiency of django. I will build application based on templates and using API. Which option will be better? 1) 1 server, 1 django (template+djangorestframework in one running framework) 2) 1 server, 1 djangorestframework or flask api, 1 django template -
Save Django Form wizard data to three models with related fields
I am working on a project that requires use of form wizard to populate three related models. The first model has general data which has a OneToOneField relationship with the second model. The first model also has a moany to many relationship with the third model. In general, I am using 4 forms in the wizard. Here is the models definition models.py class Listing(models.Model): listing_type_choices = [('P', 'Property'), ('V', 'Vehicle'), ('B', 'Business/Service'), ('E', 'Events')] listing_title = models.CharField(max_length=255) listing_type = models.CharField(choices=listing_type_choices, max_length=1, default='P') status = models.BooleanField(default=False) featured = models.BooleanField(default=False) city = models.CharField(max_length=255, blank=True) location = PlainLocationField(based_fields=['city'], zoom=7, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) expires_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, editable=False, null=True, blank=True ) listing_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='list_owner' ) def __str__(self): return self.listing_title def get_image_filename(instance, filename): title = instance.listing.listing_title slug = slugify(title) return "listings_pics/%s-%s" % (slug, filename) class ListingImages(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE) image_url = models.ImageField(upload_to=get_image_filename, verbose_name='Listing Images') main_image = models.BooleanField(default=False) class Meta: verbose_name_plural = "Listing Images" def __str__(self): return f'{self.listing.listing_title} Image' class Property(models.Model): sale_hire_choices = [('S', 'Sale'), ('R', 'Rent')] fully_furnished_choices = [('Y', 'Yes'), ('N', 'No')] listing = models.OneToOneField(Listing, on_delete=models.CASCADE) sub_category = models.ForeignKey(PropertySubCategory, on_delete=models.CASCADE) for_sale_rent = models.CharField(choices=sale_hire_choices, max_length=1, default=None) bedrooms = models.PositiveIntegerField(default=0) bathrooms = models.PositiveIntegerField(default=0) rooms = models.PositiveIntegerField(default=0) land_size … -
Replace Django Objects in a list with their corresponding id
i have a list of django objects a = [<ItemBatch: Iphone>, <ItemBatch: Iphone>, <ItemBatch: Iphone>] Can I replace the objects with their id in ORM? What I need: a = [3,5,6] How can I do that? -
Exchanging token on localhost rather than using http://django-oauth-toolkit.herokuapp.com/consumer/exchange/ for the same
I am trying to integrate Oauth to security module, for that I am using django-oauth-toolkit. For during application registration I the tutorial says to put http://django-oauth-toolkit.herokuapp.com/consumer/exchange/ for exchanging authorization code with access token.But instead of using Heroku application provided in the tutorial I want to exchange the codes on a different port on LocalHost.I cant find the codes of the OAuth toolkit Playground or Heroku application to include it in a different program.Can Anybody Help?? P.S: I am a newbie in Django and missing something Obvious I guess. -
Django Rest Filefield saved under wrong URL
Simplyfied, I have a model with an attached Filefield: models.py def uploadpath(instance, filename): return os.path.join('uploads/record/', filename) class Measurement(models.Model): data = models.FileField(null=True, upload_to=uploadpath) with MEDIA_URL = '/media/' MEDIA_ROOT = '/vol/web/media' and the django rest serializer serializers.py class MeasurementDataSerializer(serializers.ModelSerializer): class Meta: model = Measurement fields = ('id', 'data',) read_only_fields = ('id',) If I upload a file, say data.dat, with with the browser and the djange rest interface, it correctly returns the url of data: "data": "http://localhost:8000/media/uploads/record/data.dat" However, sometimes I create a model manually in the shell: with NamedTemporaryFile() as tmp_file: filepath = "/vol/web/media/uploads/record/data.dat" some_measurement.data.save(filepath, tmp_file, save=True) and list all measurements in the browser, it returns the wrong URL: http://localhost:8000/media/vol/web/media/uploads/record/data.dat" How do I have to adjust the manual creation of the file, such that the correct url, in this case "data": "http://localhost:8000/media/uploads/record/data.dat" is returned?