Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use AppConfig.label to correctly import modules from an app
I have a third party app I have set up in a subdirectory: # myproject/vendor/rock_n_roll/apps.py from django.apps import AppConfig class RockNRollConfig(AppConfig): name = 'rock_n_roll' label = 'rockme' verbose_name = "Rock ’n’ roll" Now, when I import this I can use from vendor.rock_n_roll.models import .... However, I can't seem to use the label in the same way. E.g. from rockme.models import ... results in "module not found". Per the docs the AppConfig.label is unique across the whole project, and I assume is a shorthand way to access the app. Have I misunderstood the purpose? Is there a way to simply use the label as the import path? If not, what is the purpose of the label otherwise for? -
408 status code on checking access logs of django on apache using mod_wsgi in windows
one is php site and other is django project. Php site is working fine but not django project.It is working fine on local runserver but not on apache.I have followed https://www.codementor.io/@aswinmurugesh/deploying-a-django-application-in-windows-with-apache-and-mod_wsgi-uhl2xq09e tutorial for deployment. httpd-vhosts.conf: <VirtualHost *:8086> ServerName localhost ServerAlias localhost DocumentRoot "${INSTALL_DIR}/www" <Directory "${INSTALL_DIR}/www/"> Options +Indexes +Includes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory> </VirtualHost> <VirtualHost *:80> ServerName localhost WSGIPassAuthorization On ErrorLog "C:/Users/smac/fbextractor/fbextractor.error.log" CustomLog "C:/Users/smac/fbextractor/fbextractor.access.log" combined WSGIScriptAlias / "C:\Users\smac\fbextractor\fbextractor\wsgi_windows.py" <Directory "C:/Users/smac/fbextractor"> Require all granted </Directory> <Directory "C:\Users\smac\fbextractor\fbextractor"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /media "C:/Users/smac/fbextractor/media" <Directory "C:/Users/smac/fbextractor/media"> Require all granted </Directory> </VirtualHost> settings.py """ Django settings for fbextractor project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7(7=3n5ib%=@1i6qd!d&%z!!x0ij@yh3&yf#5400e(#%dl@z@)' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost','10.147.41.64','10.147.41.44','14.139.55.130','dj.localhost'] # Application definition INSTALLED_APPS = [ 'extract_friends.apps.ExtractFriendsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', … -
Getting FieldError on confirm_ password when trying to create a custom user form
I'm trying to create a custom user creation form for username, password, and confirm password but I'm getting FieldError for confirm_password. The error goes away when I remove it from fields. class RegForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password', 'confirm_password') widgets = { 'username': forms.TextInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Username'}), 'password': forms.PasswordInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Password'}), 'confirm_password': forms.PasswordInput( attrs={'class': 'form-control mb-4', 'required': True, 'placeholder': 'Confirm Password'}), } def clean(self): cleaned_data = super(RegForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError( "Passwords needs to match" ) -
Django get SUM of function result from all objects
Something tells me this question is going to be very obvious but I've been stuck on it since all the searching I've done basically ends on calculating the sum of all objects which is what context['all_trades'] does. However, I'm looking to calculate the sum of all object results calculated in a function. I hope this is properly worded. If I print out the context this is the result: {'view': <portfolios.views.StatsView object at 0x0000020CC8B0D188>, 'all_trades': 13, 'gross_profit': <function Trade.get_profit_loss_value at 0x0000020CC70598B8>} models.py class Trade(models.Model): class Meta: verbose_name = "Trade" verbose_name_plural = "Trades" user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) ... def get_profit_loss_value(self): ret = self.get_profit_loss_value_or_None() return 0 if ret is None else ret views.py class StatsView(TemplateView): template_name = 'dashboard/stats.html' def get_context_data(self, *args, **kwargs): context = super(StatsView, self).get_context_data(*args, **kwargs) # get # of trades user made context['all_trades'] = Trade.objects.filter(user=self.request.user).count() # get sum of all trades profit/loss context['gross_profit'] = Trade.get_profit_loss_value return context -
Django is showing a method object is not subscriptable when submitting email
I have a website and I would like to allow users to contact us. Thus, when I click on the submit button I am getting the error 'method' object is not subscriptable Bellow is the error: TypeError at /contact/ 'method' object is not subscriptable Request Method: POST Request URL: https://massiwatechnology.com/contact/ Django Version: 2.1.8 Exception Type: TypeError Exception Value: 'method' object is not subscriptable Exception Location: /home/massiwat/mysite/pages/views.py in contact, line 347 Python Executable: /home/massiwat/virtualenv/mysite/3.7/bin/python3.7 Python Version: 3.7.3 Python Path: ['', '/opt/alt/python37/bin', '/home/massiwat/mysite', '/home/massiwat/virtualenv/mysite/3.7/lib64/python37.zip', '/home/massiwat/virtualenv/mysite/3.7/lib64/python3.7', '/home/massiwat/virtualenv/mysite/3.7/lib64/python3.7/lib-dynload', '/opt/alt/python37/lib64/python3.7', '/opt/alt/python37/lib/python3.7', '/home/massiwat/virtualenv/mysite/3.7/lib/python3.7/site-packages'] Server time: Wed, 11 Mar 2020 09:12:21 +0000 #Contact view.py def contact(request): submitted = False if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # full_name=form.cleaned_data['Th'] mail=request.POST.get['email'] subject=request.POST.get['objet'] msg=request.POST.get['message'] send_mail(mail, subject, msg, settings.EMAIL_HOST_USER, ['med.abdillah@massiwatechnology.com'],fail_silently=False) return HttpResponseRedirect('/contact?submitted=True') else: form = ContactForm() if 'submitted' in request.GET: submitted = True return render(request, 'contact.html', {'form': form, 'submitted': submitted}) And bellow is the ContactForm.py: class ContactForm(forms.Form): # nom_complet=forms.CharField(max_length=100, required=True) email=forms.EmailField(required=True) objet=forms.CharField(widget=forms.Textarea( attrs={ "rows":1, "cols":80 } )) message=forms.CharField( widget=forms.Textarea( attrs={ "class":"message two", "rows":5,"cols":80 } ) ) I also would like to know if the configuration bellow for sending a professional email is correct, please. EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST='mail.massiwatechnology.com' EMAIL_PORT='465' EMAIL_HOST_USER='med.abdillah@massiwatechnology.com' EMAIL_USE_TLS=True EMAIL_HOST_PASSWORD='mypassord' Please assist -
Could not send email in djano rest framework
I am developing password reset part of the project. I am using django_rest_passwordreset to get the password reset. I am using mailjet smtp. I could not send the email to the user. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'in-v3.mailjet.com' # EMAIL_PORT = 465 EMAIL_PORT = 587 EMAIL_USE_TLS = True # EMAIL_USE_SSL = True EMAIL_HOST_USER = '5e4329460b3c88f1d24d19c3e7374548aa213da%asasd1asd' EMAIL_HOST_PASSWORD = 'a6c5ab2515d6ae761253a396453530ba$42asasdasdaasdasd' If I change the EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' to the EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' it is printing it to the console. I have no idea why it is not working. the part of the code where I am trying to send an email. @receiver(reset_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): # send an e-mail to the user context = { 'current_user': reset_password_token.user, 'username': reset_password_token.user.firstname, 'email': reset_password_token.user.email, 'reset_password_url': "{}?token={}".format(reverse('password_reset:reset-password-request'), reset_password_token.key) } # just checking if it works send_mail('Hello from something', 'hello there', 'abdukhashimov@yandex.ru', [reset_password_token.user.email, ], fail_silently=False) # render email text email_html_message = render_to_string('user_reset_password.html', context) email_plaintext_message = render_to_string( 'user_reset_password.txt', context) msg = EmailMultiAlternatives( # title: "Password Reset for {title}".format(title="Some website title"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: [reset_password_token.user.email] ) msg.attach_alternative(email_html_message, "text/html") msg.send() -
Why the field description of my django model is not null?
I have created a model like this, class fleets(models.Model): fleet_id = models.IntegerField(primary_key=True) fleet_name = models.CharField(max_length=20) description = models.CharField(max_length=40, null=True) And when I observe in the postgresql admin the table I see is like what I want, fleet_id as pk and not null fleet_name not null description null But, why when I want to add some fleet with the django-admin it says is not possible? I forget some parameter? Thank you very much!! -
Django Gunicorn ConnectionHandler has no attribute 'connection_pool'
I've installed https://github.com/zhangi/django_db_pooling with Django 3.0.4 to enable connection pooling with Gunicorn. Due to an error with compatibibility, I've applied the patch in this post https://adamj.eu/tech/2020/02/04/how-to-use-pymysql-with-django/: import pymysql ... DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "testapp", } } # Fake PyMySQL's version and install as MySQLdb # https://adamj.eu/tech/2020/02/04/how-to-use-pymysql-with-django/ pymysql.version_info = (1, 4, 2, "final", 0) pymysql.install_as_MySQLdb() As per the instructions of the django_db_pooling library I've applied the configuration as follows: import os import pymysql from django.core.wsgi import get_wsgi_application from django_db_pooling import pooling pymysql.install_as_MySQLdb() os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxxxx.settings") application = get_wsgi_application() pooling.set_pool_size(4) pooling.apply_patch() However, when my project is running in gunicorn and it tries to access the database I get the following errors: Traceback (most recent call last): File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 187, in handle_request respiter.close() File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/http/response.py", line 253, in close signals.request_finished.send(sender=self._handler_class) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send for receiver in self._live_receivers(sender) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp> for receiver in self._live_receivers(sender) File "/home/simernes/workspace/myproject/env/lib/python3.7/site-packages/django_db_pooling/pooling.py", line 121, in recycle_old_connections ConnectionHandler.connection_pool[alias].release(conn) AttributeError: type object 'ConnectionHandler' has no attribute 'connection_pool' -
in Vscode, RuntimeError: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'>
I use Ubuntu and Vscode. In my Django project, I've tried to run "python manage.py process_tasks" command and I got this error below. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/../venv/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/../venv/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/../venv/lib/python3.6/site-packages/background_task/management/commands/process_tasks.py", line 123, in handle self.run(*args, **options) File "/home/../venv/lib/python3.6/site-packages/background_task/management/commands/process_tasks.py", line 96, in run autodiscover() File "/home/../venv/lib/python3.6/site-packages/background_task/tasks.py", line 317, in autodiscover imp.find_module('tasks', app_path) File "/usr/lib/python3.6/imp.py", line 271, in find_module "not {}".format(type(path))) RuntimeError: 'path' must be None or a list, not <class '_frozen_importlib_external._NamespacePath'> How can I fix this? -
How to custom sort order in djnago like mysql FIELD Function
How to write django queryset custom sort order like mysql field function in django select status from comapnay order by FIELD(status, 'Follow Up', 'Interested - Call back scheduled', 'Need to send details', 'Quotation sent') Comapany.objects.all().order_by(?) -
'teamview' object has no attribute 'get_object'
I have a problem with UserPassesTestMixin, I want to restrict views from viewing people assigned for the manager. It's giving me an error of 'teamview' object has no attribute 'get_object'. Here is my views.py in question: from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView, CreateView, DetailView from .models import Job, Member from profiles.models import User from django.contrib.auth.decorators import login_required # Create your views here. class jobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/user_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(member__member=self.request.user) class createdjobs(LoginRequiredMixin,ListView): model = Job template_name = 'users/manager_jobs.html' context_object_name = 'jobs' def get_queryset(self): return Job.objects.filter(manager__manager=self.request.user) class teamview(LoginRequiredMixin,UserPassesTestMixin,ListView): model = Member template_name = 'users/manage_team.html' context_object_name = 'members' def test_func(self): return self.get_object().manager == self.request.user def get_queryset(self): return Member.objects.filter(manager__manager=self.request.user) class jobdetail(LoginRequiredMixin,DetailView): model = Job class createjob (LoginRequiredMixin,UserPassesTestMixin,CreateView): model = Job fields = ['member','title', 'description', 'file'] def form_valid(self,form): form.instance.manager=manager.objects.get(manager=self.request.user) return super().form_valid(form) def test_func(self): return self.get_object().manager == self.request.user Hope you cna help me out with this TIA. -
Django channels "ERROR Y of N channels over capacity in group subscriptions"
I'm doing load testing with my Django app providing GraphQL Subscriptions using Django channels and a redis Channels layer (django, graphene-django, channels, graphene-subscriptions, channels-redis). As ASGI server I'm using daphne right now. I use nginx as proxy. The periodicity with which the backend publishes messages via GraphQL Subscriptions depends on the periodicity of messages the backend receives via MQTT. I'm increasing the periodicity with which an external data provider publishes messages to the MQTT broker, means the periodicity with which the backend has to process these messages and publish messages via GraphQL Subscriptions. I'm facing the following error: 2020-03-11 08:33:58,464 ERROR 2 of 12 channels over capacity in group subscriptions It seems like this issue is caused by an overload. To me it's not clear what's the performance bottleneck. What's the root cause of this issue? Can I scale the infrastructure to workaround this issue? -
VSCode ignoring breakpoints during debug in python
I'm trying to debug a Django project with VSCode. Everything works fine, I get the output and VSCode footer goes purple (debug mode) but it just ignores the breakpoints. I'm working on WSL (vscode remote) Python 3.6.9 (virtualenv) VSCode 1.43 (using Python and Python for VSCode extensions) This is my launch.json file: { "version": "0.2.0", "configurations": [ { "name": "Django", "type": "python", "request": "launch", "stopOnEntry": false, "program": "${workspaceRoot}/bullfrogloader/manage.py", "args": [ "runserver", ] }, ] } This is an screenshot of vscode running it, just in case you see something weird there: thank you so much guys, I just don't know what else to do. -
How do I run a script every day at 00:00 hrs to hit an django API on Ubuntu machine?
I need information about how to hit a django API running on ec2 on every night 00:00 hours. Thanks in advance. -
Different error between port 80 and 5500 when running site
I'm working on a chat bot system. Every time I write a message and expect a message back, I get an error message. The weird part is that the error message depends whether I run the site on localhost port 80 or 5500. If I run it on localhost (port 80), I get the POST http://localhost/get-response/ 404 (Not Found) If I run it on localhost:5500 I get POST http://localhost:5500/get-response/ 405 (Method Not Allowed) chatbot.js fetch("/get-response/", { //<--- error body: JSON.stringify({'message': message['text']}), cache: 'no-cache', credentials: 'same-origin', headers: { 'user-agent': 'Mozilla/4.0 MDN Example', 'content-type': 'application/json' }, method: 'POST', mode: 'cors', redirect: 'follow', referrer: 'no-referrer', }) .then(response => response.json()).then((json) => { this.messages.push(json['message']) }) urls.py urlpatterns = [ url('', Index), path('get-response/', get_response), ] views.py @csrf_exempt def get_response(request): response = {'status': None} if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) message = data['message'] chat_response = chatbot.get_response(message).text response['message'] = {'text': chat_response, 'user': False, 'chat_bot': True} response['status'] = 'ok' else: response['error'] = 'no post data found' return HttpResponse( json.dumps(response), content_type="application/json" ) def Index (request): context = {'title': 'Chatbot Version 1.0'} return render(request, "AI.html", context) How do I know which error message to go for? -
Django rest framework partial update with where query
I just want to update two fields of table where id_payment = 1. How to do it? It showing me the error bellow. IntegrityError at /receivePendingPayment/ (1048, "Column 'bank_id' cannot be null") #View @permission_classes([IsAuthenticated]) @api_view(['PATCH']) def receivePendingPayment(request): id_payment = request.data['id_payment'] data = {'accountant_received_by': request.user.id, 'accounts_status': 'Received'} BankPaymentHistory.objects.filter(id=id_payment) serializer = BankPaymentUpdateSerializer(data=data, partial=True, many=False) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Serializer class BankPaymentUpdateSerializer(serializers.ModelSerializer): class Meta: model = BankPaymentHistory fields = ('accounts_status','accountant_received_by') #Model class BankPaymentHistory(models.Model): activation_enum = (('Active', 'Active'), ('Deactive', 'Deactive')) accounts_status_enum = (('Pending', 'Pending'), ('Received', 'Received')) bank = models.ForeignKey(Bank, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) file = models.ForeignKey(File, on_delete=models.CASCADE) salesperson = models.ForeignKey(SalesPerson, on_delete=models.CASCADE) paymentmode = models.ForeignKey(PaymentModes, on_delete=models.CASCADE) amount = models.PositiveIntegerField() chequeno = models.CharField(max_length=50, unique=True) chequedate = models.DateField() paymentdate = models.DateField() remark = models.TextField(blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) accountant_received_by = models.ForeignKey(User, related_name='%(class)s_accountant_received_by', on_delete=models.CASCADE, null = True) accountant_received_date = models.DateTimeField(default=datetime.now) create_date = models.DateTimeField(default=datetime.now) activation_status = models.CharField(max_length=20, choices=activation_enum, default='Active') accounts_status = models.CharField(max_length=20, choices=accounts_status_enum, default='Pending') -
What value should I pass for the current user to my API - Django
I am having trouble connecting the currently logged in user to an Item object I'm storing in the database in an auction app I'm building. Item model class Item(models.Model): title = models.CharField(max_length=100) timestamp = models.DateTimeField(default=now, editable=False) condition = models.CharField(max_length=50) description = models.TextField() owner = models.ForeignKey( User, on_delete=models.CASCADE, related_name='owner' ) owner_email = models.CharField(max_length=100) owner_telephone = models.CharField(max_length=20, blank=True) location = models.CharField(max_length=200) def __str__(self): return self.title View for creating a new auction item def new_auction_view(request): form = ItemForm() if 'token' in request.session: token = request.session['token'] if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): item_obj = { "title": form.cleaned_data.get('title'), "condition": form.cleaned_data.get('condition'), "description": form.cleaned_data.get('description'), # I'm not sure what to pass in for 'owner' "owner": request.user.id, "owner_email": form.cleaned_data.get('owner_email'), "owner_telephone": form.cleaned_data.get('owner_telephone'), "location": form.cleaned_data.get('location'), } item_response = requests.post( f'{server}/api/items/', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, data=json.dumps(item_obj) ) item = item_response.json() auction_response = requests.post( f'{server}/api/auctions/', headers={ 'Authorization': f'Bearer {token}', 'Content-Type': 'application/json' }, data=json.dumps({ "item": item['id'], "starting_price": float(form.cleaned_data.get("price")), }) ) messages.info(request, 'Item successfully created') form = ItemForm() else: print(form.errors) for error in form.errors: messages.info(request, error) context = { 'page_header': 'Register Item', 'page_title': 'New Auction', 'form': form } return render(request, 'forms/auction-form.html', context) else: return redirect('/login/') I've tried a number of things: The request.user object raises a User is … -
How to start django project from other python script
How can I start my django project from another python file? Directory structure |-- interface |-- ... |-- manage.py |-- script.py How can I start my interface django project from script.py -
how do i add django language translater to my project
i am trying this command to my ubuntu terminal as virtualenv e.g django-admin makemessages -l fi but its giving an command error (env3) mosestechnologies@mosestechnologies-HP-ProBook-640-G1:~/Documents/mosess projects/fourtyq/fourtyq$ python manage.py makemessages --all CommandError: errors happened while running xgettext on ./env3/bin/activate_this.py ./env3/bin/django-admin.py setting.py LOCAL_PATHS = ( os.path.join(BASE_DIR, "locale"), ) LANGUAGES = [ ('en', 'English'), ('ru', 'Russian'), ] directories assets tempplate locale myproject projectapp manage.py -
How do you pass a UserCreationForm field into input field by just using template?
I'm trying to use bootstrap's input style and wondering if I can pass user creation form fields onto input without having to create a custom class. I've tried this which didn't work: <div class="form-group"> <label for="username">Username</label> <input name="{{ form.username }}" type="text" class="form-control"> </div> -
How to handle accordion in Django,
I set all thins in models, views and template but I don't know how to handle the accordion when I click it, open all tab. Please help me -
Populating drop down list from a database
Want to retrieve data from the database in this department ID field which is on another model. -
Django - Annotating multiple Sum() object gives wrong result
models.py looks like this class Channel(Model): name = CharField() class Contract(Model): channel = ForeignKey(Channel, related_name='contracts') fee = IntegerField() class ContractPayment(Model): contract = ForeignKey(Contract, related_name='payments') value = IntegerField() When I query a model: Channel.objects.annotate(pay=Sum('contracts__fee')) It returns: 75000. And Its correct but when I query like this: Channel.objects.annotate(pay=Sum('contracts__fee')) .annotate(paid=Sum('contracts__payments__value')) And it returns: pay: 96000, paid: 33000. As you can see the pay is changed. What is going on here? I read the ticket #10060 but no luck. -
Internal Server Error: Django, uWsgi, Nginx, Pyenv
I am trying to serve a Django application using Nginx and uWsgi I followed https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04 https://serverfault.com/questions/775965/wiring-uwsgi-to-work-with-django-and-nginx-on-ubuntu-16-04 for same. platforms.ini file [uwsgi] project = platforms base = /home/ubuntu chdir = /home/ubuntu/platforms/ home = /home/ubuntu/.local/share/virtualenvs/platforms-hQBv-BwK/ module = platforms.wsgi:application master = true processes = 5 logger = file:/home/ubuntu/platforms/logs/uwsgi.log socket = %(base)/%(project)/%(project).sock chmod-socket = 666 uwsgi.service file [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/home/ubuntu/.pyenv/versions/3.7.6/bin/uwsgi --emperor /etc/uwsgi/sites Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target vacuum = true When I run the application using below command uwsgi --http :8000 --home /home/ubuntu/.local/share/virtualenvs/platforms-hQBv-BwK --chdir /home/ubuntu/platforms -w platforms.wsgi it works fine. python manage.py runserver 0.0.0.0:8000 works fine But when i run using ini file I get internal server error also in the logs i am getting --- no python application found, check your startup logs for errors --- [pid: 6752|app: -1|req: -1/7] xx.xxx.xxx.xx () {44 vars in 904 bytes} [Wed Mar 11 07:12:50 2020] GET /admin/ => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0) announcing my loyalty to the Emperor... I am unable to figure out what could be issue. Please Help. -
how to change "" in json to python
i have a json data like this: { "@context": "http://schema.org", "@type": "NewsArticle", "mainEntityOfPage":{ "@type":"WebPage", "@id":"https://cafef.vn/cuu-ceo-fpt-nguyen-thanh-nam-cac-chuyen-gia-smart-city-sao-khong-phat-ro-len-vi-co-co-hoi-giai-bai-toan-nuoc-song-da-20191108064344921.chn" }, "headline": "Cựu CEO FPT Nguyễn Thành Nam bật mí về tổ chức "từ thiện cho người sắp giàu"", but in the headline has "" which not allowed in python , so when i import json and get this data , i have an error JSONDecodeError at /scrape/ Expecting ',' delimiter: line 9 column 70 (char 404) how can i change "" in json data to python ??