Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What Happens When Django-Rest-Framework Receives a Request?
I'm trying to understand how DRF works, specifically the GenericViewSet view. What is the sequence of actions upon request retrieval? Which component receives the request? To where the request is passed? When does validation happen? Context: All of my field-choices enums are lowercased, so I was trying to lowercase all values that arrive (from uncontrolled 3rd parties). Django's model validation fails before any of the exposed GenericViewSet methods are called. How can I process request data before model validation? Can anyone shed some light on the topic? -
django aws error while creating in elastic benstack
errors: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 635, in _build_master ws.require(__requires__) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 943, in require needed = self.resolve(parse_requirements(requirements)) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 834, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (urllib3 1.24.1 (/home/soubhagya/.local/lib/python3.5/site-packages), Requirement.parse('urllib3<1.23,>=1.21.1'), {'awsebcli'}) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/bin/eb", line 5, in <module> from pkg_resources import load_entry_point File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2927, in <module> @_call_aside File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2913, in _call_aside f(*args, **kwargs) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 2940, in _initialize_master_working_set working_set = WorkingSet._build_master() File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 637, in _build_master return cls._build_from_requirements(__requires__) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 650, in _build_from_requirements dists = ws.resolve(reqs, Environment()) File "/usr/lib/python3/dist-packages/pkg_resources/__init__.py", line 834, in resolve raise VersionConflict(dist, req).with_context(dependent_req) pkg_resources.ContextualVersionConflict: (requests 2.9.1 (/usr/lib/python3/dist-packages), Requirement.parse('requests!=2.18.0,>=2.14.2'), {'docker'}) i am trying with below command: eb init -p python-3.6 eb-django below is my project tree. Here i am trying to deploy django in aws-elasticbeanstalk but, it is showing above error. -
Django on a single server. Web and Dev environments with web/dev databases
In a couple of months, I'm receiving a single (physical) Ubuntu LTS server for the purpose of a corporate Intranet only web tools site. I've been trying to figure out a framework to go with. My preference at this point would be to go with Django. I've used RoR, CF and PHP heavily in the past. My Django concern right now is how to have both a separate '/web/' and '/dev/' environment, when I'm only getting a single server. Of course this would include also needing separate 'web' and 'dev' databases (either separated by db name or having two different db instances running on the single server). Option 1: I know I could only setup a 'web' (production) environment on Ubuntu and then use my corporate Windows laptop to develop Django tools. I've read this works fine except that a lot of 3rd party Django packages don't work on Windows. My other concern would be making code changes and then pushing to the Ubuntu server where I might introduce problems that didn't show up on the local Windows development environment. Option 2: Somehow setup a separate Django 'web' and 'dev' environment on the same server. I've seen a lot of … -
Django + Multiprocessing argument passing failure
I've got a function which spins off a separate Process and passes some arguments to it. When I call this function testing locally, everything is fine. When I call this function from a Django view, the variables passed don't make any sense. Specifically, when I am passing a string, what comes through on the other side, no matter what string I put in, is __path__. Simplified example: views.py: handler = Handler() @csrf_exempt def my_view_func(request) str1 = request.POST['str1'] # passed value is e.g. 'my string' return HttpResponse(handler.do_work(str1)) handler.py from multiprocessing import Process class Handler: def do_work(str1): # str1 is still 'my string' p = Process(target=self.do_work_help, args=(str1)) p.start() # str1's value is again in this context def do_work_help(str1): print str1 # value will be '__path__' From what I've read I should probably be using Celery for this, but I'd prefer not to refactor everything just yet, so if anyone has any idea what's going on here I'd greatly appreciate a short-term fix. -
Client side encryption Django
I just finished an app and, for safety reasons, I would like the content of some fields of the db to be readable only by the user. This involves client side encryption and I think that I found a decent pure js implementation. Typically, I would go for an AES 256 CBC using parts of the user's password hash (client side computation) as key an vi (stored as cookies) to feed the encrypt and decrypt functions. Here comes the thing. The decryption is pretty straightforward. Spontaneously, I would call the function directly in the templates using the objects passed in context as inputs for my function. It would look like: <div class=whatever_the_class> decrypt_function({{ patient.first_name }}, key, vi) decrypt_function({{ patient.last_name }}, key, vi) </div> However, I am not sure how to deal with encryption in forms. I think that I need to bypass somehow the way my forms work (in this example form_add) to take the output of my encrypt function as data but I really do not know how/where to do it. In the widget section of my form? In the template? Any thoughts? Any clean way to do it? (I am also interested in similar questions/posts/projects to get a … -
Pagination are not working with filtering Django
I had a Listview that worked perfectly with pagination it looked like: class BranchListView(ListView): model = Branch paginate_by = 10 Now I need to change it to Filterview and used django_filters, I'm trying to create pagination in a FilterView this way class BranchListView(FilterView): model = Branch paginate_by = 10 filter_class = BranchFilter template_name = 'erp_system/branch_list.html' filterset_fields = ['id', 'name'] And this how I use pagination part in the template {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}"><button class="btn-success">الصفحة السابقة</button> </a> {% endif %} <span class="page-current"> صفحة رقم {{ page_obj.number }} من {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}"><button class="btn-success">الصفحة التالية</button> </a> {% endif %} </span> </div> {% endif %} Now the filtering is working perfectly. But there is no pagination at all. -
how to delete django relation and rebuild model
ive made a mistake with my django and messed up my model I want to delete it & then recreate it - how do I do that? I get this when I try to migrate - i just want to drop it relation "netshock_todo" already exists Thanks in advance -
Get json data from url and insert data into the model with verification
I am using python package requests for getting json data from remote url. Json data should be entered to my model with verification. If object id exists update data in the model else create. I can not make a check. How can i put a check? This is for getting data from remote url. Data in the remote url will be updated every hour so I have to write a function that needs to take data from the server and insert my model. Also function must to check. I've tried fooloop json data from server and insert it to my model, but I think this is not the best way. import requests from requests.auth import HTTPBasicAuth from main.models import Acceptor def sync_data(): response = requests.get('https://94.158.53.183:9443/apipp/acceptors', auth=HTTPBasicAuth('user', 'password'), verify=False).json()['acceptor_list'] for r in response: Acceptor.objects.update_or_create( login=r.login, password=r.password, sync_tm=r.sync_tm ) sync_data() class Acceptor(DeleteModel, BaseModel): login = models.CharField(max_length=255) password = models.CharField(max_length=255) sync_tm = models.IntegerField() I expected the data to appear in my database, in the Acceptors table, but there is no data from the server in the database -
Django - Disabled field in CreateView empty after ValidationError
My model Sprint has two DateFields "start" and "end". I defined a clean-method "start < end". Now, I have disabled my ModelForm field 'project' with this solution. Link. And I provide an initial value for it. class Sprint(models.Model): project = ForeignKey start = DateField end = DateField def clean(self): if start > end: raise ValidationError() class SprintCreate(LoginRequiredMixin, CreateView): model = Sprint form_class = SprintCreateForm def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['pk'] = self.kwargs['pk'] kwargs['initial'] = {'project': Project.objects.get(id=self.kwargs['pk'])} return kwargs class SprintCreateForm(forms.ModelForm): class Meta: model = Sprint fields = ['project', 'start', 'end'] def __init__(self, *args, **kwargs): pk = kwargs.pop('pk') project = Project.objects.filter(id=pk) super().__init__(*args, **kwargs) self.fields['project'].queryset = project self.fields['project'].widget.attrs['disabled'] = True def clean_project(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.project else: return self.cleaned_data['project'] I expect that field 'project' is still filled with the correct instance upon reload and validationerror. -
Django structure base on different type of projects
I couldn't find the best answer for this question that what is the Django solution about different kind of project, for example, what is the difference between Django solution for enterprise [rojects vs medium scale projects -
Pandas to_sql in django
I am trying to use Django's db connection variable to insert a pandas dataframe to Postgres database. The code I use is df.to_sql('forecast',connection,if_exists='append',index=False) And I get the following error Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': relation "sqlite_master" does not exist LINE 1: SELECT name FROM sqlite_master WHERE type='table' AND name=?... I think this happens because the Django connection object is not an sqlalchemy object and therefor Pandas assumes I am using sqlite. Is there any way to use .to_sql other than make another connection to the database? -
Using HTML, how to print objects from inside Postgresql?
In the application I started using Django and postgresql, whenever I upload a file, it'll be recorded into database. I've confirmed this is working by checking the database using pyadmin. However, now I need to print out the file onto a html document. The code I have below belongs to a SQLite database. Most of the names remained the same except for the obj part which I assumed is not supposed to be there for postgresql. Mainly, I'm looking the the Postgresql equivalent of the 'obj' in the code below. {% extends 'base.html' %} {% block content %} <p>Uploaded files:</p> <ul> {% for obj in documents %} <li> <a href="{{ obj.document.url }}">{{ obj.document.name }}</a> <small>(Uploaded at: {{ obj.uploaded_at }})</small> </li> {% endfor %} </ul> {% endblock %} The image URL shows the way my database is setup. https://i.stack.imgur.com/ao8TV.png If it's possible, I would prefer not to involve using PHP as I'm still fairly new to this. -
I get an integrity error when deleting a user in django admin
So I am creating a social medial app with Django and I have made a lot of model connections with users and profiles and now I am confused. When Ii try to delete a user, I get an error. IntegrityError at /admin/auth/user/ FOREIGN KEY constraint failed I am not so sure but I think the error has to do with something about the followingin the `model below. I tried creating a new user that is not following anyone and tried deleting it too, it worked! But the ones already follwing each other won't get deleted and raise the error above class Profile(models.Model): # creating a one to oe rel with a user model user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='default.jpg', upload_to='profile_pics') dob = models.DateField(blank=True, null=True) bio = models.TextField(max_length=400, blank=True) following = models.ManyToManyField('self', related_name='follows', symmetrical=False) joined_at = models.DateField(auto_now_add=True) Here is my post model class Post(models.Model): title = models.CharField(max_length=50) content = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) date_posted = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, blank=True, related_name='post_likes') image = models.ImageField(null=False, blank=False, upload_to='post_images') -
Django admin select box options from model
I have language category, tags and questions models. When adding question I want to select category and multiple tags in multiselect dropdown/checkbox from the admin panel Here is my question model: from django.db import models from datetime import datetime from languages.models import Language from categories.models import Category from tags.models import Tag class Question(models.Model): language = models.ForeignKey(Language, on_delete=models.DO_NOTHING) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING) tags = models.CharField(max_length=200, blank=True) def __str__(self): return self.title How can I achieve this in Django admin panel? -
VirtualEnv apache2 server No module named 'django'
I am running a virtual environment for my apache2 server from inside /home/myname/myproject/venv I activate my virtual environment with source venv/bin/activate Running which django-admin Returns the correct file from inside my virtual environment. Running import django django.__file__ Returns /home/myname/myproject/venv/lib/python3.6/site-packages/django/__init__.py Running pip freeze Returns all of my needed packages. I also have my apache2 config file pointing to the venv directory with the python-path argument However, after restarting the server I'm still getting a ModuleNotFoundError for django. What's the issue here? -
mod_wsgi cannot be loaded as Python module http 500 error
I am trying to deploy mod_wsgi with apache to run a django application but I am getting an error 500 internal server error. This is what apache log shows: [Sun Dec 30 12:46:44.179450 2018] [mpm_event:notice] [pid 21350:tid 139933131320256] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Sun Dec 30 12:46:44.179649 2018] [core:notice] [pid 21350:tid 139933131320256] AH00094: Command line: '/usr/sbin/apache2' [Sun Dec 30 12:46:45.681614 2018] [wsgi:error] [pid 21353:tid 139933017503488] [remote 109.8.128.207:52109] mod_wsgi (pid=21353): Target WSGI script '/home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py' cannot be loaded as Py$[Sun Dec 30 12:46:45.687031 2018] [wsgi:error] [pid 21353:tid 139933017503488] [remote 109.8.128.207:52109] mod_wsgi (pid=21353): Exception occurred processing WSGI script '/home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py'. And this is my virtual host conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/betourne/tonnerrekalaraclub/static <Directory /home/betourne/tonnerrekalaraclub/static> Require all granted </Directory> Alias /media /home/betourne/tonnerrekalaraclub/media <Directory /home/betourne/tonnerrekalaraclub/media> Require all granted </Directory> WSGIScriptAlias / /home/betourne/tonnerrekalaraclub/tonnerrekalaraclub/wsgi.py WSGIDaemonProcess django_app python-path=/home/betourne/tonnerrekalaraclub python-home=/home/betourne/tonnerrekalaraclub/venv WSGIProcessGroup django_app <Directory /home/betourne/tonnerrekalaraclub/tonnerrekalaraclub> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> I'm not sure what else to try, I've been looking for a solution for 2 days now, considering each thread on the forum. WWW-DATA has every rights to access directory, I checked that there's no mispelling... I am on Ubuntu 18.04.1 -
Django admin custom form submission force to select action from dropdown list
I want to add a custom form to a django admin-site change list view. As soon as I add a submit button it asking to select the custom action from the drop-down list. I created a separate form with a unique id. Still it look for a action be select. How can I overcome this? Here is my template code. {% extends "admin/change_list.html" %} {% load staticfiles %} {% block content %} <div align="right"> <form id="generate-form" method="POST"> {% csrf_token %} <select> <option value="">-- section name --</option> {% for section in sections %} <option value="{{ section.short_name }}">{{ section.name }}</option> {% endfor %} </select> <input type="text" name="from_date" class="vTextField" placeholder="from"> <input type="text" name="to_date" class="vTextField" placeholder="to">&nbsp; <input type="submit" value="Generate" class="default" id="gen-schedules" style="margin:0; height: 30px; padding-top: 5px;"> <form> </div> {{ block.super }} {% endblock %} -
Django templates not executed in a container and no errors displayed in the logs
I'm running django 2.1.3 in to a python3 container based on alpine image, I create my own image by following this guide: https://docs.docker.com/compose/django/ (with other project works) this time the templates are not showed, the page I receive is the render of the called template the extends part are not present. I try to run code in a bind folder instead docker volumes and had no change. Dockerfile: FROM python:3-alpine ENV PYTHONUNBUFFERED 1 RUN mkdir -p /code/ WORKDIR /code/ ADD requirements.txt / RUN apk update && \ apk add postgresql-libs && \ apk add --virtual .build-deps gcc musl-dev postgresql-dev && \ python3 -m pip install -r /requirements.txt --no-cache-dir && \ apk --purge del .build-deps docker-compose (django image section): django: build: "./django" image: registry.gitlab.com/vaschetto.marco/project-docker-File/django:v0.1 container_name: Project_django restart: always command: python3 manage.py runserver 0.0.0.0:8000 env_file: - ./django/.env volumes: - django:/code/ - django_static:/code/static/ depends_on: - psql Template structure: . ├── db.sqlite3 ├── Dockerfile ├── project ... │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt ├── sito #app │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations ... │ ├── models.py │ ├── __pycache__ ... │ ├── templates │ │ └── sito │ │ ├── body.html … -
Not able to use two models in the same django view
I'm quite new to django, and can't seem to make two models in the same view work. I have tried the guide in the djano docs, but can't seem to be able to use two different models templates in the html. Is it possible that i've misunderstood how the OneToOneField works? The html just renders an empty div. The account templates works fine. Models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User from django import template import phonenumbers # Create your models here. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) site = models.CharField(max_length=50, choices=(('all', 'all'), ('danielk', 'danielk')), blank=True) phoneNumber = models.IntegerField() birthDate = models.DateField() streetAdress = models.CharField(max_length=255) zipCode = models.CharField(max_length=4) city = models.CharField(max_length=255) def formatedPhone(self, country=None): return phonenumbers.parse(Account.phoneNumber, "NO") def __str__(self): return "%s %s" % (self.user.first_name, self.user.last_name) def get_absolute_url(self): return reverse("account-detail", kwargs={"pk": self.pk}) class Meta: verbose_name = "Account meta" verbose_name_plural = "Accounts meta" class Notes(models.Model): userNoted = models.OneToOneField(User, on_delete=models.CASCADE) note = models.TextField() date = models.DateTimeField((""), auto_now=False, auto_now_add=True) active = models.BooleanField(default=True) def get_absolute_url(self): return reverse("note-detail", kwargs={"pk": self.pk}) class Meta: verbose_name = "Note detial" verbose_name_plural = "Notes details" Views.py from django.shortcuts import render from django.http import HttpResponse from django.views import generic from django.views.generic.detail import DetailView from django.views.generic.edit import * … -
django-rest-framework and http to https redirect
I want to redirect all http requests to https in my django app. The app has also an api through which I make request to database. Those requests are made through http protocol and I want to redirect them to https as well . Below configuration works well with requests made in web browser (http are correctly redirected to https and the website displays). However, the requests through api cause 301 error (Moved Permanently). Am I missing something here? This is my nginx configuration: server { listen 80; server_name myurl.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl; server_name myurl.com; ssl_certificate /path_to_cer; ssl_certificate_key /path_to_key; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_redirect off; #proxy_buffering off; } Django settings: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True -
FloatField returns str object instead of Float in Django
While working on something in Django, I stumbled upon this wierd error (cuz it never happened before). If in a FloatField I saved a float value as string i.e. '245.4' instead of actual float value i.e. 245.4, then on accessing the value it returns back the string instead of float! the reason why abs(modelname.floatfield) threw TypeError today. On research found this old thread in Django's forum (https://code.djangoproject.com/ticket/19565). Is it decided and implemented yet or should I typecast values manually from now on or anyone has a better solution? -
organization and departments hierarchy database schema
I have a database design in django that have the following tables: organization table id name contact department table name parent (another department self referencing ) organization (referencing the organization table if this is the top department only) How to inherit the organization relationship instead of having to set it every time i am creating a new department? -
Filtering by Field on Foreign Key
I've got two models that are related to one another class IndustryService(models.Model): title = models.CharField(max_length=120) pricingisarate = models.BooleanField(default=False) class UserService(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.ForeignKey(IndustryService, on_delete=models.CASCADE, null=True, blank=True) Within a view, I'm trying to develop a queryset of UserService instances that a) belongs to a user b) on the foreign key, has pricingisarate == True I've tried the following query, but it doesn't work: services = UserService.objects.filter(user=user, industryservice__pricingisarate__is=True) Thanks for your help!!! -
How to fix ValueError: Expecting property name: line 4 column 1 (char 43)
when I tr to run python manage.py runserver code is giving error . And its traceback is strange , I tried JSON ValueError: Expecting property name: line 1 column 2 (char 1) and all similar questions but didn't get what exactly I am facing. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/tousif/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/tousif/.local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/tousif/.local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/tousif/Desktop/ITP/ITP/itpcrm/itpcrm/settings.py", line 55, in <module> cfg = json.loads(open('/home/tousif/Desktop/ITP/ITP/itpcrm/config.json', 'r').read()) File "/usr/lib/python2.7/json/__init__.py", line 339, in loads return _default_decoder.decode(s) File "/usr/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 4 column 1 (char 43) Project should run. -
django: custom code integration into django project
Noob here with django. I have the following folder structure for a dhango app, which is inside the main project folder. my_app/ __init__.py admin.py apps.py migrations/ __init__.py models.py tests.py views.py I have a command line python script I wrote to fetch a json file and parse it to displays very specific information. it's using requests library for JSON and data parsing. My question is how do I integrate my script into django app. specifically how to bring the logic of it and to place under which file? My thinking is to create another file and import them into views. and pass them into render function - this may be not the right and django way, but kinda stuck there. Oh and I don't use any DB, the script uses a text file and writes to it as well.