Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() -
Django Apps and Python Packages Dependencies
I am new to web development. I am not familiar with Django. I have written some Python scripts which do some intense calculations and graphs plotting using Python packages such as numpy, matlibplot and so on. I want to publish it as a web application on a server to be accessed by other computers. So I am wondering, do I need to copy all the required packages into the project directory before deploying the application to a server? Or Django will automatically handle the Python packages dependencies upon deploying? -
Why " <link href="{% static "css/base.css" %}" rel="stylesheet">" occurred? And my css cite is fail?
I use django to write a html and cite a css model,but i find it fail and the visuaulstudio remind me that " <link href="{% static "css/base.css" %}" rel="stylesheet">" Here is my html code {% load staticfiles %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/base.css" %}" rel="stylesheet"> </head> <body> <div id="header"> <span class="logo">Bookmarks</span> </div> <div id="content"> {% block content %} {% endblock %} </div> </body> </html> Could somebody tell my why? -
pdf not generated using django restframework
class GeneratePublisherPdf(APIView): #View def get(self, request, args, *kwargs): reviewer_id = request.GET.get("user") export_date = datetime.date.today() - datetime.timedelta(1) profile = UserProfile.objects.filter(user_id=reviewer_id).first() users = [profile.user.id, ] for up in UserProfile.objects.filter(publisher=profile.user, user__register_type='5'): users.append(up.user.id) if not len(users): result = { "status": False } return Response(data=result) queryset = ProductCertificate.objects.filter(user__id__in=users, created__date=export_date).order_by('-created') if queryset.count(): instance = PDFFile.objects.create(user_id=reviewer_id, export_date=export_date) obj = PDFFile.objects.get(id=instance.id) objes = [] for e in queryset: dict_rep = { "workflow_id": e.workflow_step.workflow.workflow_id, "step": e.workflow_step.step, "role": e.workflow_step.role, "organization": e.user.profile.organization if e.user.profile.organization else "-", "product": e.product.title if e.product else "-", "in_batch_id": e.in_batch_id, "out_batch": e.out_batch_id, "transaction_address": "<br>".join(textwrap.wrap(e.transaction_address, 13)), "trans_add":e.evidence } objes.append(dict_rep) data = { 'export_date': export_date, 'record': objes } pdf = render_to_pdf('pdf/invoice.html', data) filename = "%s.pdf" % (datetime.datetime.now().strftime("PDF%y%j%H%M%s%f")) obj.pdfurl.save(filename, File(BytesIO(pdf.content))) result = { "export": export_date, "id": str(instance.id), "pdf": str(obj.pdfurl).split("/")[-1], "status": True } else: result = { "status": False } return Response(data=result) plz help..i cannot able create pdf file .. -
like() got an unexpected keyword argument 'story_id'
Episode has GenericRelation with Like model class Episode(models.Model): likes = GenericRelation(Like) Viewset: class EpisodeViewSet(viewsets.ModelViewSet, LikedMixin): serializer_class = EpisodeSerializer permission_classes = (IsOwnerOrReadOnly,) def get_queryset(self): queryset = Episode.objects.filter(story=self.kwargs.get('story_id')) return queryset urls: router.register(r'(?P<story_id>\d+)/episodes', views.EpisodeViewSet, basename='episodes') LikedMixin has function for performing like action: @action(detail=True, methods=['POST']) def like(self, request, pk=None): obj = self.get_object() services.add_like(obj, request.user) return Response() When I try post request with url 0.0.0.0:3000/stories/1/episodes/1/like/, i recieve error like() got an unexpected keyword argument 'story_id'. -
JQuery Slider in django templates
I'm trying to add a JQuery slider in a Django template but it doesn't work... My main template: ... <div> <dt class="nav-header">Size</dt> <dd> {% include 'catalogue/slider_size.html' %} </dd> </div> ... The template slider_size.html : <link rel="stylesheet" href="slider.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $( "#slider-range" ).slider({ range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) ); } ); </script> <p> <label for="amount">Price range:</label> <input type="text" id="amount" readonly style="border:0; color:#f6931f; font-weight:bold;"> </p> <div id="slider-range"></div> The error in the console: Error in the console Any ideas? Thank you in advance. -
Save a charfield column with prefix and primary key combined in django model?
i created a model "PurchaseRequest". the pk is autocreated. Now, i created a charfield column which would store a value like "PR# + pk" during save process. def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.pr_number = 'PR #' + str(self.id) super(PurchaseRequest, self).save() BUT, it returns PR#None . once i edit and save it , it returns correct answer as obviously it fetches id now. -
Sys.path.insert inserts path to module but imports are not working
I want to import a module in a project and it gives me lots of troubles because of an import error. So I decided to write a little test to see where the problem lies. I add a folder to my sys path and try to import it. And I get an Import Error: no module found named xyz Like this: import sys import os sys.path.insert(0, os.path.abspath('../../myfolder')) import myfolder print(sys.path) The sys.path is ['/Users/myuser/myproject/mywebsitefolder/myfolder/', ...] myfolder contains an __init__.py file. Hardcoding the path to myfolder has same results. Other questions on the web solve the problem by either adding the correct path or by adding an init. But I have both I think and the problem remains. I was under the impression that python looks in the system path for importable modules or do I misunderstand how this is supposed to work? If I understand correctly, is there any way I can debug this further? Or could this be a problem with python versions? Help is very much appreciated. Thanks in advance! -
Weird behaviour of django REST APIs
We are having django application, which is hosted on AWS Elastic Beanstalk. It is connected to RDS. Application Server: c5.4xlarge RDS: postgreSQL 9.5 (m5.4xlarge) The issue is APIs are sometimes returning 500 and sometimes 200 even thought the request params are exactly same. That is causing Elastic Beanstalk to degrade every now and then. I tested the APIs with all possible requests on my local by connecting to Cloud database. But did not receive a single 500 error. Same app is there on Test environment and it is not causing a single 500. There is no load on the RDS when EB degrades. So, it seems application is not the issue here. Could it be due to Application Server resources? Please help. Cloudwatch References: -
Python IOError: push_notifications.apns in _apns_create_socket
We are using django-push-notifications==1.6.0. We confirmed that the file is existing in the docker container. The pem file is valid because we abled to sent device notification manually using the file. Below is the actual log: IOError: [Errno 2] No such file or directory File "demoapp/tasks_helpers/notification.py", line 216, in push certfile=apns_certfile File "push_notifications/models.py", line 167, in send_message **kwargs File "push_notifications/apns.py", line 113, in apns_send_message certfile=certfile, **kwargs File "push_notifications/apns.py", line 66, in _apns_send client = _apns_create_socket(certfile=certfile, application_id=application_id) File "push_notifications/apns.py", line 38, in _apns_create_socket use_alternative_port=get_manager().get_apns_use_alternative_port(application_id) File "apns2/client.py", line 41, in __init__ self.__credentials = CertificateCredentials(credentials, password) File "apns2/credentials.py", line 29, in __init__ ssl_context = init_context(cert=cert_file, cert_password=password) File "hyper/tls.py", line 131, in init_context context.load_cert_chain(cert, password=cert_password) Why is the system always looking for the pem file directory when in fact the actual file exist? -
verify FCM registration token using python
I have Firebase Cloud Messaging registration token from client. and i want to verify this registration token before I send push notification. btw, I have tried https://firebase.google.com/docs/auth/admin/verify-id-tokens but I think this is for Auth tokens not for push notification. how to verify registration token before send push notification ? -
Java installation error in Ubantu 18.4 LTS
I have to run Django CRM in my local machine.I followed all commands and tried to install every requirements. I stuck in the following command. sudo apt-get install oracle-java8-installer -y java -version I got the following error when i tried above command. E: Command line option 'e' [from -version] is not understood in combination with the other options. The link of Github CRM Django CRM Documentation Please someone help me.