Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Http Request between two dockers and nginx
I'm tryin to build and aplication made of containers with a djanjo server, a REST API an an nginx server, but I'm not able to send a post HTTP request from django to rest api. In local everythong works fine, and in the conteinari This is my request, it always get a 400 error code: headers = {'content-type': 'application/json'} r = requests.post('http://brokkr:5000/action', params=data, headers=headers) And this is my docker-compose file: version: '3.7' services: loki: build: context: ./Loki dockerfile: Dockerfile.prod command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 ports: - 8000:8000 networks: - my-network depends_on: - brokkr brokkr: build: context: ./Brokkr dockerfile: Dockerfile command: gunicorn -b 0.0.0.0:5000 api:api ports: - 5000:5000 networks: - my-network nginx: build: ./nginx ports: - 80:80 networks: - my-network depends_on: - loki - brokkr networks: my-network: driver: bridge All of the containers start with out problem and both servers(django and falcon) pront that they are both listening. I think that the problem has to do with my nginx conf: upstream server{ server loki:8000; } server { listen 80; location / { proxy_pass http://server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/server/web/staticfiles/; } } -
Django: ImportError cannot import name Comment
Environment: Request Method: GET Django Version: 1.8.5 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'home', 'payment', 'newsletter', 'orderApp', 'log', 'rest_framework', 'rest_framework.authtoken', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 367. sub_match = pattern.resolve(new_path) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 239. return ResolverMatch(self.callback, args, kwargs, self.name) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in callback 246. self._callback = get_callable(self._callback_str) File "/usr/local/lib/python2.7/dist-packages/django/utils/lru_cache.py" in wrapper 101. result = user_function(*args, **kwds) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in get_callable 105. mod = import_module(mod_name) File "/usr/lib/python2.7/importlib/init.py" in import_module 37. import(name) File "/var/newsletter/views.py" in 30. from .models import Comment Exception Type: ImportError at /frequently-asked-questions/ Exception Value: cannot import name Comment -
What is the equivalent of this query in Django Filter
What is the equivalent of this query in Django Filter I need to get email address of the people having birthday today. select email from lp7ms_coworker_data where Extract(month from dob)=EXTRACT(month FROM CURRENT_DATE) and Extract(day from dob)=EXTRACT(day FROM CURRENT_DATE) -
How did a hacker produce this GET request?
I am just about to go live with a website and am addressing security issues. The site has been public for some time but not linked to the search engines. I log all incoming requests and today noticed this one: GET /home/XXXXX/code/repositories/YYYYY-website/templates where XXXXX is a sudo user on my server and YYYYY is my company name. This is actually the structure of my Django project code. My website is coded using Django and runs under Apache2 on Ubuntu. My question is how can this guy possibly know the underlying code/directory structure on my server, in order to create this request? Their IP is : 66.249.65.221. They come up as 100% a hacker on https://ip-46.com Any contributions welcome. -
Configure Apache for Django REST backend and React frontend on same domain
How to configure Apache for Django REST backend and React frontend on same domain One domain (for solve crossdomain problems). Urls: example.com/ example.com/api/ where: example.com/ - React-based frontend example.com/api/ - Django-based REST backend How implement it with Apache ? I think some like a: <VirtualHost *:80> ServerName ${DOMAIN} DocumentRoot ${SITE_FOLDER} CustomLog /var/log/apache2/${DOMAIN}_access.log common ErrorLog /var/log/apache2/${DOMAIN}_error.log WSGIDaemonProcess ${DOMAIN} user=${APACHE_USER} group=${APACHE_GROUP} python-path=${SITE_FOLDER}:${VENV_PACKAGES_PATH} WSGIProcessGroup ${DOMAIN} WSGIScriptAlias / ${SITE_FOLDER}/core/wsgi.py Alias /static/ ${SITE_FOLDER}/static/ <Directory ${SITE_FOLDER}/static> Require all granted </Directory> <Directory ${SITE_FOLDER}/core> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> is the backend, it serve /api ...but, how to implement frontend ? -
How to upload multiple images with one value in Django
i'm trying to upload multiple images with one value(e.g image_id is 1 and number of images are 5, images_id is 1 it holds 5 images). How to do this. upload.html <form action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="image_id" placeholder="Image Id"> <input type="file" name="file" multiple> <button type="submit"> Upload </button> </form> views.py def multi_image(request): if request.method == 'POST': img_id = request.POST.get('image_id') file = request.FILES.getlist('file') data_save = Res(image_id = img_id ) data_save.save() filter_data = Res.objects.filter(image_id= img_id) if len(filter_data) > 0: for i in file: print(i) Res.objects.create(image= i) return render(request, 'upload.html', {}) models.py class Res(models.Model): image_id= models.CharField(max_length=10, blank=True, null=True) image = models.FileField(upload_to='images', blank=True, null=True) forms.py class FileForm(forms.Form): class Meta: model = Res fields = '__all__' -
Add button in django admin site
how to put button like in the picture? and it will link in my html? this is my admin.py @admin.register(gradingPeriodsSetting) class gradingPeriodsSettingAdmin(admin.ModelAdmin): list_display = ('School_Year', 'Education_Levels', 'Courses', 'NumberOfGradingPeriods', 'Status') ordering = ('pk',) models.py class gradingPeriodsSetting(models.Model): School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, blank=True, null=True) Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True) NumberOfGradingPeriods = models.IntegerField(blank=True, null=True) -
Can I display the SerializerMethodField in Django admin
I am creating a custom field in my serializers file new_field= serializers.SerializerMethodField(read_only=True) def get_new_field(self,obj): # do something Is there a way I can display this field in the django admin panel? -
Extract values from object in django
I'm looking to extract the '35' and '34' values from this object: [<FriendshipRequest: 35>, <FriendshipRequest: 34>] These are primary keys which i would like to use as parameters to get information about the specific user the primary key relates to but I am unsure on how to separate the values from the rest of the object attributes to substitute into User.objects.get(pk=pk) as at the moment pk=<FriendshipRequest: 35> whereas i'd like pk=35. I am just wondering if anyone has any ideas on how to approach this problem? Cheers -
How do I retrieve data from field that is in a class meta(object)
I have a class in a models.py file : class classname(models.Model): and within this class is class meta (object) examplefield I am trying to retrieve data from a field that is within this class meta object via the following command: classname._meta.get_field('examplefield') Instead of getting the actual all the data within this field I keep getting the type: <django.db.models.fields.FloatField: examplefield> How can I retrieve the actual data and print to screen? -
Is there any method to query mongo db views with pymongo or mongoengine?
I want generate a user Report. For that I have created a view by combining data from two collections. Now I want to query this view and fetch data, is there any method to do this by pymongo or mongoengine. My application is written with django. -
Can't use manage.py when ENGINE is set to postgresql_psycopg2
I have an application written in django which I'm trying to run. Here's a snippet from the configuration: elif STAGE == 'TEST': DEBUG = False DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'username', 'USER': 'dbname', 'PASSWORD': 'passwd', 'HOST': 'localhost', 'PORT': '', } } else: DEBUG = True REGISTRATION_ENABLED = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, '../../location' if STAGE == 'STAGING' else 'db.sqlite3'), } } When I set STAGE to TEST I can't use manage.py at all since any attempt at running it (even ./manage.py with no arguments gives me an error: Traceback (most recent call last): File "/project_location/venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "auth_group" does not exist LINE 1: ...ELECT "auth_group"."id", "auth_group"."name" FROM "auth_grou... now, when I set STAGE to anything but TEST it works flawlessly, but doesn't use postgres which I want it to use. Postgres is installed, I created the database and I can log in to it using the username and password. What's the problem here and how can I fix it? -
Select from choices in ModelForm is not displayed in template Django
I want to create a ModelForm for creating an instance of the class Doctor in the template. However, options for the CharField with choices (Gender) are not displayed. I tried to specify widgets and choices in the ModelForm, however it still does not work. What can i do to display list with options for the field with choices? Screenshot of the template I have the following class: class Doctor(models.Model): GENDER_CHOICES = [('F', 'Female'), ('M', 'Male')] doctor_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=70, blank=False, null=False) last_name = models.CharField(max_length=70, blank=False, null=False) gender = models.CharField(choices= GENDER_CHOICES, max_length=15, blank=False, null=False) specialization = models.CharField(max_length=50, blank=False, null=False) And ModelForm created from this class class DoctorForm(ModelForm): #gender = forms.ChoiceField(choices=Doctor.GENDER_CHOICES) not working class Meta: model = Doctor fields = ['doctor_id', 'first_name', 'last_name', 'gender', 'specialization', 'email', 'phone', 'education', 'experience', 'birth_date', 'address'] #widgets = { # 'gender': forms.Select(choices=Doctor.GENDER_CHOICES) #} also not working Method in views for creating an instance of the form: def add_doctor(request): if request.method == "POST": form = DoctorForm(request.POST or None) if form.is_valid(): form.save() # Do something. return redirect('doctors') messages.error(request, "Invalid form") return redirect('manage_doctor') else: form = DoctorForm() context = { 'form': form } return render(request, 'manage_doctor.html', context) -
How to check token in django-oauth-toolkit?
I want to check user token in oauth2 how to do. I want to import all tokens but i can not check.Please help me to solve this -
Python Django: Preview images in the admin add/change form (NOT list_display)
I know how to preview images inside Django Admin with list_display, but since I have about 10 different images in one model, I also need to preview them inline, inside the add / change form, in fact I need to preview them next to the Choose File button (see screenshot): I tried this apporach, but it doesn't work: Display thumbnail in Django admin inline Does anyone know a current solution? -
Django sphinx documentation does not read environment variables in settings file
I want to document my cookiecutter django project with sphinx. The problem is that when running make html sphinx gives me problems reading the config file. It says django.core.exceptions.ImproperlyConfigured: Set the USE_DOCKER environment variable When not calling django.setup() it also throws me an error with my envs: django.core.exceptions.ImproperlyConfigured: Set the POSTGRES_DB environment variable When I hardcode them, the error goes on to complain about the next environment variable. I can't hardcode them all into the config file, that is not an option. My environment variables are properly configured. When I print them out running my localhost they are there. It seems that somehow sphinx cannot process them. I am also using docker, so maybe that could interfere but I don't know. Here are parts of my sphinx config: sys.path.insert(0, os.path.abspath('..')) os.environ['DJANGO_SETTINGS_MODULE'] = 'config.settings.local' Here are parts of my local settings: INTERNAL_IPS = ['127.0.0.1', '10.0.2.2'] if env('USE_DOCKER') == 'yes': import socket hostname, _, ips = socket.gethostbyname_ex(socket.gethostname()) INTERNAL_IPS += [ip[:-1] + '1' for ip in ips] # django-extensions # ------------------------------------------------------------------------------ # https://django-extensions.readthedocs.io/en/latest/installation_instructions.html#configuration INSTALLED_APPS += ['django_extensions'] # noqa F405 # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { # 'default': env.db('DATABASE_URL'), # This was the default value, but modification below seemed necessary 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': … -
Created oauth2 provider, needed to create oauth2 login credentials when user login using facebook through python social auth
So i managed to create my own oauth2 provider(django oauth toolkit) in order to use my django app as a mobile application backend. Then when user needed to login using facebook i used python social auth's social-app-auth-django package. The user logged in successfully. Now the question is when a mobile user tried to login i have to use facebook response and create my own token as a response. I don't know it is the right approach. -
i want to create a url that will direct the link to a login function in my view in django i tried everything and it didn't work
from django.conf.urls import url from . import views from django.urls import path,include app_name = 'shop' urlpatterns = [ url(r'^$', views.product_list, name='product_list'), url(r'^(?P[-\w]+)/$', views.product_list, name='product_list_by_category'), url(r'^(?P\d+)/(?P[-\w]+)/$', views.product_detail, name='product_detail'), ] -
--- Logging error --- Python and Django 2.2
Python Script from django.conf import settings import django import sys import json sys.path.append("/srv/vhosts") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') django.setup() import logging logger = logging.getLogger("project") logger.error("saveLog Error: ") Setting LOG_ROOT = "/srv/volume1/logs/project" LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, "formatters": { "simple": { "format": "[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s", "datefmt": "%y %b %d, %H:%M:%S", } }, "handlers": { "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, "project": { "level": "DEBUG", "class": "logging.FileHandler", "filename": LOG_ROOT + "/project.log", }, "file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": LOG_ROOT + "/debug.log", }, "django_file": { "level": "DEBUG", "class": "logging.FileHandler", "filename": LOG_ROOT + "/django.log", }, "console": {"class": "logging.StreamHandler"}, "celery": { "level": "DEBUG", "class": "logging.handlers.RotatingFileHandler", "filename": LOG_ROOT + "/celery.log", # 'formatter': 'simple', "maxBytes": 1024 * 1024 * 100, # 100 mb }, }, "loggers": { "project": {"handlers": ["sia"], "level": "DEBUG", "propagate": True}, }, } after running script python Script.py getting an error: --- Logging error --- Traceback (most recent call last): File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/__init__.py", line 992, in emit msg = self.format(record) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/__init__.py", line 838, in format return fmt.format(record) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/__init__.py", line 578, in format s = self.formatMessage(record) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/__init__.py", line 547, in formatMessage return self._style.format(record) File "/opt/rh/rh-python36/root/usr/lib64/python3.6/logging/__init__.py", line 391, in format return self._fmt % record.__dict__ … -
Django Channels2 - after power failure of system crash channel_name persists
I am using Django Channels2 an a project. When there is a power failure or system crash channel_name persists for some time (1 day) , but the system will send messages to non existing channel_name. How do we handle this in Django Channels2? BR -
Which model use to show path to files and show it in django
I have a django project and lots of media files on server, how to show path on server to file in django admin, to show file in page. I want it to don't upload 2 times to server. Example: Movie with size 10GB in server If I will use "FileFied", I will upload it to server again. Can I show just a path and show in page -
Where is Django's files installed
I'm from php, Laravel. I just start learn python and Django I use pip installed Django but I can't find any files from this folder C:/desktop/test/ It's very different from Laravel framework. Laravel has content all framework files inside of folder. If I want to move to different machine, I just need to copy all files. My questions are Where is Django installed? what if move to different machine (ex: move to server) If I start another new project, do I have to install Django again? -
Test case failed for django generic CreateAPIView?
Here I am writing the TestCases for my CreatePackage view.However the test got failed.The response status is 400 BadRequest.What might be the reason for this ? AssertionError: 400 != 201 class CreatePackageTest(APITestCase): def setUp(self): self.client = Client() def test_create(self): url = reverse('package:create_package') data = {'name':'package','package_description':'description', 'package_start_date':'2019-11-12 11:11'} response = self.client.post(url,data) print(response.status_code) self.assertEqual(response.status_code, status.HTTP_201_CREATED) views.py class CreatePackage(generics.CreateAPIView): serializer_class = PackageSerializer queryset = Package.objects.all() -
whet i upload image to save in database with foriegn key 'username' but i get an error
models.py class UploadImg_Model(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE, default=None) Image = models.ImageField(upload_to='users_files/uplaods/images') uploaded_Date = models.DateTimeField(auto_now_add=True, auto_now=False) def __str__(self): return self.username views.py def UploadImg(request, usrnm): Data = UploadImg_Model() Fields = UploadImg_Form(request.POST, request.FILES) #print('FILES : ', request.FILES) #print('POST : ', request.POST) if Fields.is_valid(): Data.Image = Fields.cleaned_data['Image'] #print('IMAGE : ', Data.Image) Data.save() return render(request, 'profile.html', {'User': usrnm}) return render(request, 'upload_images.html', {'User': usrnm, 'Form': UploadImg_Form}) ERROR IntegrityError at /oneapp/myaccount/AnonymousUser/upload/ NOT NULL constraint failed: oneapp_uploadimg_model.username_id -
Django Rest Framework Price being returned to 1 decimal place
When a price is e.g. 213.30 it is being returned as 213.3, not a huge problem but something that needs sorting, below is my Model and my Serializer. Have already tried looking online for more information but cant see anyone else having the same issue "price": { "HighSell": 213.3 } My Model class Product(models.Model): itemno = models.CharField(max_length=100) HighSell = models.DecimalField(max_digits=10, decimal_places=2, null=True) def __str__(self): return self.itemno My Serliazer class ProdListSerializer(ModelSerializer): price = SerializerMethodField() class Meta: model = Product fields = [ 'id', 'itemno', 'price' ] def get_price(self, obj): customerNo = self._context['view'].request.query_params.get('customerNo', '') if customerNo: customerPrice = CustomerPrices.objects.filter( Q(customerNo=customerNo) & Q(itemno=obj.itemno) ).values('price').first() if customerPrice: return customerPrice else: return Product.objects.filter(itemno=obj.itemno).values('HighSell').first() else: return Product.objects.filter(itemno=obj.itemno).values('HighSell').first()