Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django turns absolute filepaths into relative, forcing the server to be run from the project folder
I'm trying to create a website where you can add images to models, which will then be in turn loaded on the homepage. However, I've noticed that when I run my server, it tries to get images from my /home folder. Here's my models.py: image_directory = join(settings.STATICFILES_DIRS[0], "website/images") class Item(models.Model): image = models.FilePathField(path=image_directory, recursive=True) Here's my home.html (I'm just abbreviating it, item is passed in OK: <img src="{{ item.image }}"> I run the migrations and run the server, and I'm able to select the image in /admin. The images look like: "sub_img_folder/img.jpg" Then I go to /home and I get the following errors: Not Found: /home/...absolute-path-to-project.../static/website/images/sub_img_folder/img.jpg Not Found: /home/static/website/images/sub_img_folder/img.jpg Any help would really be appreciated. -
Calendar validations for appointment using django and sqlite
I was making one dental appointment web app, was wondering how would i make validations for appointment using a db. I made one date selector input type as calendar to select date and add time. I need to know if there are any built in functions for date time object? -
How to add data to nested serializers?
I'm trying to add data to my database by rest api and i have some problems with adding the data. So basically i have added this data from the admin page, but i want to add this from my other python by using requests. When i'm sending post request it shows me that it's has been added, but sensor array is empty models.py from django.db import models class Sensor(models.Model): name = models.CharField(max_length=20, default='null', blank=True) type = models.CharField(max_length=20, default='null', blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) value = models.FloatField(null=True) index = models.IntegerField(null=True) def __str__(self): return str(self.name) + ' ' + str(self.type) + ' ' + ' index:' + str(self.index) + ' value:' + str(self.value) class Station(models.Model): name = models.CharField(max_length=20, default='null', blank=True) delay_time = models.IntegerField(null=True) sensor = models.ManyToManyField(Sensor, null=True, default='null', blank=True) serializers.py from rest_framework import serializers from .models import Sensor, Station class SensorSerializer(serializers.ModelSerializer): class Meta: model = Sensor fields = '__all__' class StationSerializer(serializers.ModelSerializer): class Meta: model = Station fields = '__all__' depth = 1 adddata.py import json import requests import time import serial ser = serial.Serial( port='/dev/ttyS0', baudrate = 9600, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=1, ) payload={ "username":["xxxxx"], "password":["xxxxxxxxxx"] } while 1: x = ser.readline() try: r = requests.post('http://192.168.1.16/api/token/', data=payload) jsondata = r.json() headers = … -
Django ManyToMany relationship, filter options of modelmultiplechoicefield
I am currently rewriting a web app that is utilizing a hierarchy of relationships which is making it extremely painful to create a reliable work flow for the creation of objects. The current set up is as follows: Customer Hierarchy: Organization -> Location -> Room Contacts can belong to one or many of these entries at any level of the hierarchy. Ex Jim can be assigned to Organization and location. With this I need to filter the django many to many field that is populated with any contact that doesn't belong anywhere OR belongs to a parent or child level of the customer hierarchy. I have attempted inline formsets which fails on the many to many model as well as limit_choices_to={'Organization':_get_self_pk} . This works but doesn't allow for the use of django admin style on the fly creation of contacts. I have also attempted to use a queryset in the init function for create, but my form has a nested inline formset that doesn't allow me to use the self.field['contact'] to inject the queryset. (Key Error, contacts doesn't exist as a field) Models.py class Organization(AbstractExclusions, AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractOrganizationLocationCommonInfo, AbstractAcvitivyInfo): .... contact = models.ManyToManyField('Contact', blank=True) class Location(AbstractManyToManyCommonInfo, AbstractCommonInfo, AbstractOrganizationLocationCommonInfo, AbstractLocationRoomCommonInfo, AbstractAcvitivyInfo, … -
django static file - 404
First of all: I know there are a lot of user issues but all of them did not solve my issue, so im hoping for the best here. My django is unable to access the static files and im getting the 404. Infrastructure: Public accesible server with django installed and apache reverse proxy to localhost:8000. (Its no apache Problem. When Local Forwarding of the 8000 Port this issue is still present). Directory Listing: /var/twirps . |-- assets | |-- admin | | |-- css | | | `-- vendor | | | `-- select2 | | |-- fonts | | |-- img | | | `-- gis | | `-- js | | |-- admin | | `-- vendor | | |-- jquery | | |-- select2 | | | `-- i18n | | `-- xregexp | |-- css | | `-- images | |-- js | |-- sass | | `-- libs | `-- webfonts |-- blockmatrix | |-- __pycache__ | `-- migrations |-- static | |-- css | | `-- images | |-- js | |-- sass | | `-- libs | `-- webfonts |-- templates `-- twirps `-- __pycache__ settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, … -
Django forms is_valid is working without parenthesis
At line 6 of my code I forgot to add the parenthesis to is_valid() but my code works fine without the parenthesis. Why is this? I'm still able to access form.cleaned_data. After filling out a form, the info is saved to my database and the terminal displays the print functions. SignUp() is a ModelForm. views.py def signup(request): form = SignUp() context = {'form': form} if request.method == 'POST': form = SignUp(request.POST) if form.is_valid: form.save() note = "Thanks {} for joining!".format(form.cleaned_data['firstname']) print("Name: {}".format(form.cleaned_data['firstname'])) print("Age: {}".format(form.cleaned_data['age'])) return render(request, 'one_app/sign_up.html', {'form': form, 'note': note}) return render(request, 'one_app/sign_up.html', context) models.py class Members(models.Model): firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) age = models.SmallIntegerField() sex = models.CharField(max_length=10, choices=SEX_CHOICES) employeed = models.BooleanField() start_date = models.DateField(auto_now_add=True) def __str__(self): return f"{self.firstname} {self.lastname}" forms.py class SignUp(forms.ModelForm): class Meta: model = Members fields = '__all__' labels = { 'firstname': 'First Name:', 'lastname': 'Last Name:' } -
is it possible to know the status a process in django views?
I have a file that gets processed for a long time like 5+ minutes. i would like the user to know what the processing status e.g. which row the app is processing. Is it possible to use a StreamingHttpResponse or something and print statements to achieve this? Thanks! -
Cant't get related models in django
My class: class Image(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=30); date = models.DateTimeField(auto_now_add=True); image = models.ImageField(default='default.png', blank=True) def __str__(self): return self.title; class Comment(models.Model): id = models.AutoField(primary_key=True) title = models.TextField(max_length=500); image=models.ForeignKey(Image, on_delete=models.CASCADE) From Admin I add related comment to Image. But when I watn get comments for Image, i get notfing images = Image.objects.get(id=pk) comments = images.comment_get.all() return render(request, 'images/image_view.html', {'image': images,'comments':comments}) {% for comment in comments %} comment.title {% endfor %} -
How to create color themes for a Django app?
I need to apply a different main color to the whole app depending on what user is logged. I have extended the user model and according to a selected value the color of the app must change. Any ideas...? -
hiding can_delete field in a django formset
I have a formset that I created using formset_factory() with the can_delete option set to true In my html template each form is displayed with the form.as_p function so I don't have access to each html element the can delete field is displayed by the template as a check box and I would like to hide it. I could render the form manually a modify the appropriate tag but since there is a lot of fields in that form that seems to be a lot of code just to hide an element I could also use javascript or css on the client side as explained here However I suspect there might be a neater way to do it. I read in the doc that there is also a can_order field which is similar to can_delete and that can also be activated when creating a form set. This can_order field can be hidden by creating a formset class with the appropriate attribute : from django.forms import BaseFormSet, formset_factory from myapp.forms import ArticleForm class BaseArticleFormSet(BaseFormSet): ordering_widget = HiddenInput ArticleFormSet = formset_factory(ArticleForm, formset=BaseArticleFormSet, can_order=True) I am wondering if it is possible to do something similar with the can_delete field. Something like : can_delete_widget … -
How to serialize a simple Dict using django-marshmallow?
I tried all the ways and when I validate the serializer by calling is_valid(), I always get an error. class KVSFileMapSerializer(Schema): kv_map = fields.Dict() kvs_result = { 'trial': 'Config', 'trial_1': 'Congig', } kvs_serializer = KVSFileMapSerializer(data=kvs_result) kvs_serializer.is_valid() The last line always returns 'False', I tried raising an exception and this is what I get, {'trial': [ErrorDetail(string='Unknown field.', code='invalid')], 'trial_1': [ErrorDetail(string='Unknown field.', code='invalid')]} This is the package that I use - django-marshmallow -
Docker Compose doesn't work when I have "volumes", otherwise it works. Why?
The following docker-compose.yml works: version: "3.8" services: my_db: container_name: my_db image: postgres environment: - POSTGRES_DB=ArborMetrix - POSTGRES_USER=postgres - POSTGRES_PASSWORD=753951456852 # volumes: # - type: volume # source: my_db_volume # target: /my_project web_app: container_name: web_app build: . command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" # volumes: # - type: volume # source: web_app_volume # target: /my_project ports: - "8000:8000" depends_on: - my_db #volumes: # my_db_volume: # web_app_volume: When I un-comment the comments above, I get the following error: Starting my_db ... done Starting web_app ... done Attaching to my_db, web_app my_db | my_db | PostgreSQL Database directory appears to contain a database; Skipping initialization my_db | my_db | 2020-06-26 18:47:07.281 UTC [1] LOG: starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit my_db | 2020-06-26 18:47:07.282 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 my_db | 2020-06-26 18:47:07.283 UTC [1] LOG: listening on IPv6 address "::", port 5432 my_db | 2020-06-26 18:47:07.314 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" my_db | 2020-06-26 18:47:07.448 UTC [25] LOG: database system was shut down at 2020-06-26 18:46:48 UTC my_db | 2020-06-26 18:47:07.484 UTC [1] LOG: database system is … -
Setting the Superuser with email as the username field in Django with PostgresSQL
I've been following a tutorial and reading the documentation from here but for some reason every time I set up the database it still asks me for a username instead of an email for registering. I've no idea what I'm doing wrong, I even dropped and recreated the database but that didn't change anything. Here's my code from models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, first_name,last_name, password=None): if not email: raise ValueError('Must have an email') if not first_name: raise ValueError('Must have first name') if not last_name: raise ValueError('Must have last name') user = self.model( email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, first_name='John', last_name = 'Smith' ) user.is_admin = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) first_name = models.CharField(max_length = 30) last_name = models.CharField(max_length = 30) #these are mandatory #username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have … -
How can I use Routers in rest_framework to render images
After uploading my images, my image don't display because of bad routing. The URL of my image skips the base directory. For example, it renders http://localhost:8000/media/profile_pic/Screenshot_from_2020-05-30_16-54-45.png instead of : http://localhost:8000/blog/media/profile_pic/Screenshot_from_2020-05-30_16-54-45.png This is my first time using router, and I don't really understand how this works. router.register('users', UserViewSet, basename='users') router.register('posts', PostViewSet, basename='posts') router.register('comments', CommentViewSet, basename='comments') router.register('prayer_request', PrayerRequestViewSet, basename='prayer_request') router.register('category', CategoryViewSet, basename='category') urlpatterns = router.urls + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Passing json array of array in django to javascript google charts
I have an actuals array of array coming from django queryset as a json. I am having trouble feeding it to the google charts.js Below is the code. views.py def historicals(request): actuals= serializers.serialize("json",Del.objects.all()[1:10]) json_object = json.loads(actuals) actuals=[] i=1 for element in json_object: dt=element['fields']['Date'] dt=datetime.datetime.strptime(dt,'%Y-%m-%dT%H:%M:%S%z') dt=dt.date() dt=datetime.datetime.strftime(dt,'%Y-%m-%d') Vol=str(element['fields']['Volume']) print (dt) cn=str(element['fields']['Customer']) cn = str(cn) actuals.append([pxn,Vol,dt]) print (actuals) context['actuals']=actuals return render(request,'customer.html',context) var actuals = "{{ actuals | safe }}"; will shows the following in page source. [['001', '5155', '2020-01-14'], ['001', '57.0', '2020-02-13'], ['001', '510', '2020-02-25'], ['001', '5760', '2020-03-23'], ['001', '46.625', '2020-03-30'], ['001', '910', '2020-04-01'], ['001', '435300.0', '2020-03-20']] console.log(actuals); //Would show the above array of arrays for (i = 0; i < actuals.length; i++) { for (j = 0; j < actuals[i].length; j++) { var dt = i; actual = actuals([i][j]); //tried parseFloat too didnt work //data.addRow([i,actual[i][1]); console.log(actuals[i][j]); //--> this shows individual characters in the array [ , 0 0 0 0 1 } } I am trying to iteratively add a row using the data.addRow line. My problem is actuals[i][j] is showing an individual character instead of whole string or numbers or dates. I was expecting the console.log(actuals[i][j]) to show ['0001','515',datetime.date(2019, 1, 14)] in the browser console. Can you help? -
Python - unexpected token '<newline>'<dedent>'
I've just made a function but I keep getting these two errors & I'm not too sure what the issue is - unexpected token '<newline>'Python(parser-16) unexpected token '<dedent>'Python(parser-16) Here's the def code - def get_user_membership(request): user_membership_qs = UserMembership.objects.filter(user=request.user) if user_membership_qs.exists(): return user_membership_qs.first() return None -
Can't fix migration conflict in Django
I am having an issue resolving a migration conflict. Normally when these things happen we've been able to merge the files together using "python manage.py makemigrations --merge". However, this time we're getting a Could not find common ancestor of {'0001_initial', '0005_removed_custom_form_model_changed_name_to_staff_reports'} error. Several hours later and we've made no progress in repairing this. The issue arose after we deleted an app and created a new one to replace it. Here are the things I've tried already: Returning to a previous migration using "python manage.py <app_name> <older_migration>". (Doing this displays the same merge conflict I'm trying to avoid) Restoring the apps.py file for the deleted app and adding the app back into installed_apps, and then to backtrack using "python manage.py <app_name> <older_migration>" again. (Doing this causes the same merge conflict error) I'm not too familiar with migrations myself, so I'm quickly running out of ideas, and unfortunately dropping the database is not an option in this scenario. Here are the migration files in question: 0001_intial.py: import django.contrib.postgres.fields.jsonb import django.core.serializers.json from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('properties', '0001_initial'), ] operations = [ migrations.CreateModel( name='CustomFormDeclarations', fields=[ ('deleted', models.DateTimeField(editable=False, null=True)), ('date_entered', models.DateTimeField(auto_now_add=True)), ('last_update', models.DateTimeField(auto_now=True)), ('id', … -
Django Swagger Using CoreAPI Schema: Object of type Boolean is not JSON serializable
I am working on a custom schema and got an error saying Object of type Boolean is not JSON serializable on the Swagger documentation page. import coreapi import coreschema from rest_framework.schemas import AutoSchema class CustomSchema(AutoSchema): def get_manual_fields(self, path, method): manual_fields = [] if method == "POST": manual_fields.extend( [ coreapi.Field( "custom_field", required=False, location="form", description="custom field", type=coreschema.Boolean() ) ] ) return manual_fields I noticed that using location="query" would not yield the error above, but I need it in the form for Swagger. Is there any workaround? Thanks in advance! -
Django JsonResponse with safe=False to D3
Developing a project with Django which involves serving JSON data to templates for use in javascript using the D3 framework. A pattern I am using quite a bit is to return a JsonResponse object from a Django view with an array of data. As I start to link up apps in the project, I am also starting to use this idea to pass data between views in different apps. To get this working, I also need to set a safe flag as False. e.g. def my_view(request): data = [{'foo':'bar'}, {'but':'should'}, {'i':'care?'}] return JsonResponse(data, safe=False) This works fine and I think I want to be passing arrays because it makes life easier in D3. But it perturbs me a bit to be using this flag. I am somewhat reassured by the description in the Django documentation, but cannot say I have much understanding of the risk. django docs - jsonresponse Any thoughts on how much of a security issue this potentially is, and what might be the best alternative approach if they are significant? -
Django - can't run server as sudo
I'm creating a soft AP in order to configure my raspberry wireless from it. I alread have an script to create a hotspot, a dhcp server and now i need to run a django app using sudo. (Yes, using sudo. I'm waking up my django server from my python script, and the script needs to run as sudo) I'm getting the following error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/urls/conf.py", line 17, in include urlconf_module, app_name = arg ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.7/dist-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/r unserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.7/dist-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.7/dist-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/usr/local/lib/python3.7/dist-packages/django/urls/resolvers.py", line 4 07, in check for pattern in self.url_patterns: File "/usr/local/lib/python3.7/dist-packages/django/utils/functional.py", line 48, in … -
how to use filter inside annotate django
i grouped by a value then sum of a field , but now i want to only summation happen if a column inside annotate greater that or equal to 1 ! MyModel.objects.values('name').annotate( income=( Sum(((F('price')*F('order')) - ( (F('product__price')+F('product__cost'))*F('order')) ),output_field=IntegerField()))) sometimes happen income smaller than 0 (negative values) , i dont want summation of those products which their incomes smaller than 0 , i want to use something like this inside the annotate or Sum income__gte=1 !? is it possible only add to income column if the new income greater than or equal to 1? -
application error while deploying django app on heroku
My Django apps works well locally but when deployed on heroku gives this error: Application error An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command Some solutions on net said too run: heroku run python manage.py createsuperuser But this gives the error: django.db.utils.ProgrammingError: relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... Also: You have 26 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): Finance, admin, auth, checklist, contenttypes, sessions, tasks. Run 'python manage.py migrate' to apply them. However I already ran the below lines multiple time on command prompt. > python manage.py makemigrations > python manage.py migrate I have also added these lines to settings.py as some other solutions said: import django_heroku django_heroku.settings(locals()) I also tried deleting the app and setting it up again but the error persists. Also tried to delete all migrations and make new one, still the error persists. Also to note that it ran initially for 2-seconds properly even then i was unable to access even the admin login page. … -
PHP Curl request to django web project
I have a Django project on a VPS using Apache2 and mod_wsgi. It's working fine. Now I want to send a request to the VPS. The request is sent from a shared hosting webserver. Here is the code: <?php function getResponse($url, $get, $post, $cookies) { $request_url = $url.'?'.http_build_query($get); $ch = curl_init($request_url); if ($_SERVER['REQUEST_METHOD'] === 'POST') curl_setopt($ch, CURLOPT_POST, true); else if ($_SERVER['REQUEST_METHOD'] === 'GET') curl_setopt($ch, CURLOPT_GET, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_COOKIE, http_build_query($cookies, '', '; ')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); return !isset($response) ? null : $response; } $c = $_COOKIES; $c['csrftoken'] = '...'; echo getResponse('http://ip.to.vps/', $_GET, $_POST, $c); ?> The problem is that although I send the CSRF token I get the error: Forbidden (403) CSRF verification failed. Request aborted. What do I have to change that Django accepts the token and sends a valid response? -
Can't run crontab django commangd
I have a bash script crontab --- -rwxrwxr-x (I did chmod +x run.sh) When i run ./run.sh script works fine (appended data to the file) #!/bin/bash export DJANGO_SETTINGS_MODULE=eda_parser.settings # eda_parser -- name of the project and the main app cd /home/alex/root_folder/projects/5_eda_parser/eda_parser source ../venv/bin/activate # run venv python manage.py delete_old # main django command eda_parser/ ├── manage.py ├── eda_parser # main app ... ├── run.sh # script to run ├── scraper # django commands app │ ... │ ├── management │ │ └── commands │ │ ├── delete_old.py # code of the command -
Custom error message on Create User on DRF ModelViewSet
I'm writing a Django Rest API using Django Rest Framework and in it I have a base custom user User and two kinds of user that inherit from User, Doctor and Pacient. Each one has a different endpoint, so to create a Doctor we make a POST request to /api/v1/doctor and to create a Paciente, a POST to api/v1/pacient/. If I try creating a user (using those endpoints) but with an e-mail that is already registered (I have changed Django to use e-mail instead), I get the following. { "email": [ "user with this email already exists." ] } What I'm trying to achieve is to change this error message, but not only change, I need to verify if the e-mail if from a Pacient or Doctor regardless of which endpoint I'm using, so I can display different messages for each case. PacientViewSet (DoctorViewSet is basically the same) : class PacientViewSet(viewsets.ModelViewSet): serializer_class = PacientSerializer queryset = Pacient.objects.all() permission_classes = (AllowAny, ) Serializer: class PacientSerializer(serializers.ModelSerializer): def create(self, validated_data): user = Paciente.objects.create_paciente_user( nome_completo=self.validated_data['full_name'], password=self.validated_data['password'], email=self.validated_data['email'], ) return user class Meta: model = Pacient fields = ('id', 'email', 'password', 'full_name', ...) extra_kwargs = { 'password': { 'write_only': True, } } Please let me …