Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't deploy EB Django Application
Here's my full error after I run eb deploy: Creating application version archive "app-210816_201313". Uploading: [##################################################] 100% Done... 2021-08-17 01:13:46 INFO Environment update is starting. 2021-08-17 01:13:51 INFO Deploying new version to instance(s). 2021-08-17 01:14:06 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2021-08-17 01:14:10 ERROR [Instance: i-0995f885df1f382cb] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2021-08-17 01:14:10 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-08-17 01:14:10 ERROR Unsuccessful command execution on instance id(s) 'i-0995f885df1f382cb'. Aborting the operation. 2021-08-17 01:14:10 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. Here's my requirements.txt file: asgiref==3.4.1 autopep8==1.5.7 awsebcli==3.20.1 backports.entry-points-selectable==1.1.0 botocore==1.21.22 cement==2.8.2 certifi==2021.5.30 charset-normalizer==2.0.4 colorama==0.4.3 distlib==0.3.2 Django==3.2.6 filelock==3.0.12 future==0.16.0 idna==3.2 jmespath==0.10.0 pathspec==0.5.9 pipenv==2021.5.29 platformdirs==2.2.0 pycodestyle==2.7.0 pypiwin32==223 python-dateutil==2.8.2 pytz==2021.1 pywin32==301 PyYAML==5.4.1 requests==2.26.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.1 termcolor==1.1.0 toml==0.10.2 urllib3==1.25.11 virtualenv==20.7.0 virtualenv-clone==0.5.6 wcwidth==0.1.9 I tried pip3 install -r requirements.txt and then deploying again, but same error as shown above. How do I fix this? How do I access my logs? thanks in … -
Conditionally require password when creating user in Django Admin page
I am using LDAP for authentication in my Django app so when adding a user in the admin page I don't need to set a password since the user will be authenticated against the LDAP backend. I'd like to modify the 'Add user' page in the admin views to have a boolean selector to identify when I am trying to add an LDAP user so that the password field is not required. I'd like to retain the option of supplying a password in case I need to add a local user that authenticates against Django's backend. Here is what I've cobbled together so far: models.py Modified the save method so that the user gets populated in the CustomUser model if isLdap is True. class CustomUser(AbstractUser): pass isLdap = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.isLdap: user = LDAPBackend().populate_user(self.username) else: super().save(*args, **kwargs) def __str__(self): return self.username admin.py I successfully added a check box to identify if the new user is an LDAP user but the value isn't being saved to the CustomUser model and I need to change save_model so it saves the actual password if it is valid otherwise set_unusable_password(). class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm add_fieldsets = ( (None, { … -
Django ModuleNotFoundError: No module named 'PIL'
I looked at a lot of SO posts for this error and none of the answers address or resolve the error. Here is the pipfile: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" boto3 = "*" psycopg2 = "*" pillow = "*" django-storages = "*" django-crispy-forms = "*" django-s3-storage = "*" zappa-django-utils = "*" psycopg2-binary = "==2.8.6" django-environ = "*" django-mptt = "*" djangorestframework = "*" mortgage = "*" stripe = "*" django-phonenumber-field = "*" phonenumbers = "*" django-mathfilters = "*" image = "*" [dev-packages] mock = "*" model-mommy = "*" django-debug-toolbar = "*" [requires] python_version = "3.8" As you can see, I have both the pillow and image packages installed. But, when I run py manage.py shell, I get this error: import PIL ModuleNotFoundError: No module named 'PIL' In my user_profile app, I have the following: import PIL from PIL import Image ... -
eb : The term 'eb' is not recognized as the name of a cmdlet, function, script file, or operable program
I'm trying to deploy my Django Application with AWS beanstalk following this documentation: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html Everything works up till this point: ~/ebdjango$ eb init -p python-3.6 student-archive When I run that line of code I get this error: eb : The term 'eb' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + eb init -p python-3.6 studentarchive + ~~ + CategoryInfo : ObjectNotFound: (eb:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException What could be some causes of this? Here's my django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: StudentArchive/wsgi.py Here's my requirements.txt: asgiref==3.4.1 autopep8==1.5.7 backports.entry-points-selectable==1.1.0 certifi==2021.5.30 distlib==0.3.2 Django==3.2.6 filelock==3.0.12 pipenv==2021.5.29 platformdirs==2.2.0 pycodestyle==2.7.0 pytz==2021.1 six==1.16.0 sqlparse==0.4.1 toml==0.10.2 virtualenv==20.7.0 virtualenv-clone==0.5.6 -
login_required decorator gives "object has no attribute 'user'" error
New to Django. I have a view that works well without @login_required decorator. urls.py urlpatterns = [ path('play/', play.as_view(), name='play'), view.py with @login_required commented out from django.contrib.auth.decorators import login_required . . class play(View): #@login_required def get(self, request, *args, **kwargs): print("GET request: ", request) return render(request, 'play.html', {}) The page load correctly in the browser and the request is printed on the console as follows GET request: <WSGIRequest: GET '/play/'> [16/Aug/2021 23:17:23] "GET /play/ HTTP/1.1" 200 3591 [16/Aug/2021 23:17:23] "GET /static/css/home.css HTTP/1.1" 200 96 [16/Aug/2021 23:17:23] "GET /static/js/home.js HTTP/1.1" 200 3544 [16/Aug/2021 23:17:23] "GET /static/js/main.js HTTP/1.1" 200 1451443 [16/Aug/2021 23:17:23] "GET /static/images/BlankPicture.png HTTP/1.1" 200 16272 Not Found: /favicon.ico [16/Aug/2021 23:17:24] "GET /favicon.ico HTTP/1.1" 404 7793 OTOH, if I uncomment the @login_required line, I get following error. AttributeError at /play/ 'play' object has no attribute 'user' Request Method: GET Request URL: http://127.0.0.1:8000/play/ Django Version: 2.2.12 Exception Type: AttributeError Exception Value: 'play' object has no attribute 'user' Exception Location: /usr/lib/python3/dist-packages/django/contrib/auth/decorators.py in _wrapped_view, line 20 Python Executable: /usr/bin/python3 Python Version: 3.8.10 Python Path: ['/home/<username>/workspace/djangoapp/src', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Mon, 16 Aug 2021 23:20:17 +0000 play.html is a vanilla html page with only static html in it. The error happens even if … -
django-allauth No module named 'django.core.email'
I installed django-allauth and I'm able to login and logout with my admin superuser account. However, when I try to sign up, I get the following error: ModuleNotFoundError at /accounts/signup/ No module named 'django.core.email' Included config in my settings.py: SITE_ID = 1 # django-allauth configuration LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT = 'home' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False # configure email EMAIL_BACKEND = 'django.core.email.backends.console.EmailBackend' I don't have a urls.py or views.py file for the accounts since this is taken care of by the allauth plugin. The full traceback is: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 3.2.6 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_select2', 'crispy_forms', 'rest_framework', 'allauth', 'allauth.account', 'accounts', 'gradebook'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\allauth\account\views.py", line 230, in dispatch return super(SignupView, self).dispatch(request, *args, **kwargs) File "C:\Users\Doug\.virtualenvs\upgradetools-YX5Y8vBO\lib\site-packages\allauth\account\views.py", line 74, in dispatch … -
Django error: 404 Page not found on get method
I am trying to get serialized data from endpoint localhost:8000/v1/test/uuid, but hitting a 404 error - what is wrong with below? views.py from uuid in response, get site object class Test(APIView): def get(self, request, *args, **kwargs): uuid = kwargs.get('uuid') resp = {'site': None} site = Site.objects.get(uuid=uuid) resp['site'] = SiteSerializer(site).data return Response(resp) urls.py urlpatterns = [ re_path(r'^v1/', include(router.urls)), re_path(r'test/', views.Test.as_view(), name='test'), ] models.py site id as the pk class Site(models.Model): """ Model that represents a Site """ uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) domain_name = models.CharField(max_length=255, unique=True) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) serializers.py class SiteSerializer(serializers.ModelSerializer): class Meta: model = Site fields = [ 'uuid', 'domain_name' ] -
How to encrypt or Obfuscate REST API URL in Django
Hello Django REST API Experts, We are building University Course portals where app offers various user types like Professor, Students and Admins using DJANGO/REACT. We are using REST API to connect between backend and frontend. So, far we are able to perform some basic operation and it really works great. However now I need help from this group to do following: When students enrolled in course it generates an acknowledge document stating course description, and its prerequisite which needs to get signed by students to ensure student acknowledge they fulfill these requirements. In order to do this we have following: Model for each course which contains the Content, Description and Prerequisite for each course. StudentCourseAck Model which has FK to Course, Signed Boolean field, Binary field to store signed doc. User flow: Student logins to portal, Select the Course, which generate StudentCourseAck entry. Let Student review document and signed the document (on client side using sign pad). The Signature gets stored in PDF (as binary field). So far so good… Now we want to enhance the featureset which allows admin to email student the link of studentcouseack document incase its not signed before course start. Also this link should only … -
For a query set of a single element, indexing 0th element of a (query_set[0]) and and query_set.first() give different values - Django 2.2.7
I am running this code: city_state_location = ( Location.objects.filter(city=city, state=state) .values_list("city") .annotate(long=Avg("longitude"), lat=Avg("latitude")) ) print( city_state_location, city_state_location[0], city_state_location.first(), len(city_state_location), ) Which outputs: <QuerySet [('New York', -73.9422666666667, 40.8382)]> ('New York', -73.9422666666667, 40.8382) ('New York', -73.9501, 40.8252) 1 Why does this happen? The query set only contains one element so I'm confused why indexing the first element is any different then calling .first() This is running on Django 2.2.7 -
create tether wallet on django sites
I have decided to set up a store website for myself. On this website, my customers buy products with Tether(USDT). The customer charges his wallet and every time he buys a product, it is deducted from his wallet. This wallet is for the site itself and has nothing to do with currency wallets. framework : Django 3.2 how could i do that -
Django - How to iterate comlicated JSON object?
I have json object like [{'Group Name': 'asdfasdf', 'inputs': [{'DataType': 'data2', 'DataName': 'asdfasdf'}, {'DataType': 'data1', 'DataName': 'asdfasd'}, {'DataType': 'data2', 'DataName': 'asdfas'}]}, {'Group Name': 'asdfasdf', 'inputs': [{'DataType': '', 'DataName': 'asdfasdf'}]}] Data type and data name fields can be multiple in one group name. Group name can be multiple with at least one data type and data name field. This multiplication is dynamical due to user's choice. However, I am new in python and django. I didn't understand loop mechanism of them. How can I build a loop mechanism for group name count and data inputs count? -
How to run a function in django within a specified time?
views.py from django.shortcuts import render, redirect from .models import Product from .tasks import set_firsat_urunu from datetime import datetime # Create your views here. def index(request, id): product = Product.objects.get(id=id) if request.method == 'POST': product.name = request.POST.get('name') product.description = request.POST.get('desc') product.deadline_at = request.POST.get('deadline_at') product.firsat_urunu = [False, True][bool(request.POST.get('check'))] product.save() set_firsat_urunu.apply_async(args=[id],eta=datetime(2021,8,17,0,10)) return redirect(request.META.get('HTTP_REFERER')) return render(request, 'product.html', {'product':product}) tasks.py from celery import shared_task,current_task from .models import Product @shared_task(bind=True) def set_firsat_urunu(id=1): p = Product.objects.get(id=id) if p.firsat_urunu == True: p.firsat_urunu = False return 'done' I want to run a task with celery and make changes to a record in the database when the time I specify comes. When I run the code blocks I mentioned above, although the celery states that the relevant function has been received, I can't see anything in the django admin Celery Result section and at the same time, the celery task does not work even if the specified time has passed. Also, when I give apply_async ' args=[id] with @shared_task(bind=True), set_firsat_urunu gives an error because you gave 2 parameters but it takes only 1. -
widgets for ChoiceField in modelform
I'm using a modelform for my form Post and I'm using a bootstrap starter code as my base.html but because I use the {% csrf_token %} {{form.as_p}} on my add_blog page, bootstrap doesn't work and because of that it needs class='form-control', I have managed to do that on all of my fields but Choice input, if I do include my author(choicefield) in the widgets I get a TypeError: init() got an unexpected keyword argument 'attrs' class PostForm(forms.ModelForm): class Meta: model = Post fields = ("title", "title_tag", "author", "body") widget = forms.Select(attrs={"class": "form-control"}) widgets = { 'title': TextInput(attrs={'class': 'form-control'}), 'title_tag': TextInput(attrs={'class': 'form-control'}), 'body': Textarea(attrs={'class': 'form-control'}), 'author': ChoiceField(attrs={'class': 'form-control'}) } -
Creating a simple form using django and searching a SQL database
I am trying to create a form that will allow users to search a database. The intended language is django. I have created the backend database for a simple student schema, and I will eventually have a stored procedure that takes different parameters, if any of the parameters are provided a search will be done on the database and results returned. For the purposes of this exercise, a simple table will also suffice for searching. I did some reading up and I have been able to come up with the below, however it feels like a log way from what I am trying to achieve, a prototype can be seen below of what I am trying to achieve. The back end database is SQL server, I have configured the database with django and created the table/tables. I would also like to understand how to play with stylesheets to create nice looking yet simple pages. On my views.py. This is what I have. from django.shortcuts import render from reporting_project.models import sqldbconnection import pyodbc def connsql(request): conn=pyodbc.connect('Driver={sql server};' 'server=localhost\DEV2;' 'Database=django_reporting;' 'Trusted_connection=yes;') cursor = conn.cursor() cursor.execute("select student_id, firstname, lastname, fullname, gender , enrollment_date from tbl_students") result = cursor.fetchall() return render(request, 'index.html',{'sqldbconnection':result}) if 'searchfield' … -
Issue with dropped decimals in JavaScript with Django template
I'm consulting with a small business using a POS software that runs javascript with Django template. I don't have control on what is in the Sale.TaxClassTotals.Tax array, but I'm trying to add the values to group taxes together. This is the code I'm trying to modify {% for Tax in Sale.TaxClassTotals.Tax %} {% if Tax.taxname and Tax.rate > 0 %} <tr><td data-automation="receiptSaleTotalsTaxName" width="100%">T.P.S : {% if options.tps_number != '' %}[{{ options.tps_number }}]{% endif %} ({{Tax.subtotal|money}} @ {{Tax.rate}}%)</td><td data-automation="receiptSaleTotalsTaxValue" class="amount">{{Tax.amount|money}}</td></tr> {% endif %} {% if Tax.taxname2 and Tax.rate2 > 0 %} <tr><td data-automation="receiptSaleTotalsTaxName" width="100%">T.V.Q : {% if options.tvq_number != '' %}[{{ options.tvq_number }}]{% endif %} ({{Tax.subtotal2|money}} @ {{Tax.rate2}}%)</td><td data-automation="receiptSaleTotalsTaxValue" class="amount">{{Tax.amount2|money}}</td></tr> {% endif %} {% endfor %} I've attempted to modify it to the following: {% set tps_total = 0 %} {% set tvq_total = 0 %} {% for Tax in Sale.TaxClassTotals.Tax %} {% if Tax.taxname and Tax.rate > 0 %} {% set tps_total = tps_total + Tax.amount %} {% endif %} {% if Tax.taxname2 and Tax.rate2 > 0 %} {% set tvq_total = tvq_total + Tax.amount2 %} {% endif %} {% endfor %} T.P.S : {% if options.tps_number != '' %}[{{ options.tps_number }}]{% endif %} ({{Tax.subtotal|money}} @ {{Tax.rate}}%){{tps_total|money}} T.V.Q : {% … -
Django form wont change to html format
I am trying to apply a ModelChoiceField as a Field, which seems to work as intended, but for some reason It wont match the format of the template. The image on the left is how its suppose to look, and image on the right is how it looks. I created a Form but still it wont ammend these changes. It usually works when i assign a form to the field, and it worked with other methods. Here is my Forms.py class dv_Form(ModelForm): class Meta: model = dv_model fields = '__all__' Metric_name_dv = forms.ModelChoiceField(queryset=dv_model.objects.values_list('Metric_name_dv', flat=True),widget=forms.Select) My views.py (Just incase) def Auditor(request): model = auditsModel.objects.filter(qs_login=request.user) dv_models= dv_model.objects.all() form = auditForm() form_dv = dv_Form() if request.method == "POST": form = auditForm(request.POST) form_dv = dv_Form(request.POST) if form.is_valid() and form_dv.is_valid(): form.save() form_dv.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form, 'dv': form_dv} return render(request, "main/auditform.html", context) HTML PAGE {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>QS Tool Demo 1</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"/> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/> <!-- Lightbox --> <link href="path/to/lightbox.css" rel="stylesheet"/> <!-- Stylesheets --> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" … -
Close Window button doesn't work on my website
Hey i am using the freelancer bootstrap from https://startbootstrap.com/previews/freelancer If you scroll down, click on some portfolio and then if you try to press the "close window" button nothing happens. How can i fix that? -
Using Waitress yields "This page isn’t working" for django project however works fine with python manage.py runserver
I am working on uploading my django project to heroku for beta testing, however am encountering an issue using waitress. $ waitress-serve --listen=*:8000 mysite.wsgi:application I used this line of code on the gitbash to test if waitress was working - got this as a result: INFO:waitress:Serving on http://[::]:8000 INFO:waitress:Serving on http://0.0.0.0:8000 I clicked on both of the links, but both of them result in "The Page isn't working" and an "ERR_EMPTY_RESPONSE" However, when I run python manage.py runserver, it works totally fine, and my django project gets pulled up and functions properly. I was wondering if anyone could provide any advice on how to fix this? -
Accessing the values of a ManyToManyField in Django
I've created a Many to Many relationship in my project like this: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Address'), unique=True) user_name = models.CharField(_('User Name'), max_length=150, unique=True) # and a lot of other fields and stuff class Course(models.Model): user = models.ManyToManyField(CustomUser, related_name="enrollments", blank=True, null=True) course_name = models.CharField(_("Course Name"), max_length=200) In Django Admin site, I created some courses and added users to it. What I need is to get a list of courses that a unique user is enrolled and a list of users enrolled in a unique course. I know that I can access the Related Manager like this: user.enrollments <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7f4df159c0a0> And I know also that I can access the intermediate m2m class using: user.enrollments.through <class 'core.models.Course_user'> What I could not get (or find in the docs or even in internet at all) is how I can access the values contained in this relation (courses a user is enrolled and users enrolled in a course). Any help will be appreciated. -
django-graphql-jwt JWT_COOKIE_SAMESITE not working
I'm using Django GraphQL JWT Library and Django GraphQL Auth I keep getting this error google chrome error With this react code (trimmed for relevancy) on both http://localhost:3000/ and https://localhost:3000/ const [login] = useMutation(LOGIN_MUTATION, { variables: { email: email, password: password }, onCompleted: ({ tokenAuth }) => { if (tokenAuth.success) { setToken(tokenAuth.token); } } }); Now when I run this mutation from the graphiql page it works and I end up with a JWT cookie but not on the react site mutation { tokenAuth( email:"********" password:"*********" ){ token refreshToken success errors } } This doesn't work GRAPHQL_JWT = { "JWT_COOKIE_SAMESITE": 'None', "JWT_ALLOW_ARGUMENT": True } Adding these didn't work "CSRF_COOKIE_SECURE": True, "SESSION_COOKIE_SECURE": True, "CSRF_COOKIE_SAMESITE": 'None', "SESSION_COOKIE_SAMESITE": 'None', "JWT_VERIFY_EXPIRATION": True, Adding these to django settings also didn't work SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' I've been stuck on this for about 3 days now and am about ready to throw myself in a river and go build tables. Please help. -
Deploying Django error: Failed with result 'exit-code'. Gunicorn and VPS
I'm trying to set up a VPS server with ubuntu for my Django project. However, I am running into some trouble when running gunicorn status. sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Web ExecStart=/home/ubuntu/Web/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock project.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2021-08-16 19:38:28 UTC; 8min ago Main PID: 10466 (code=exited, status=1/FAILURE) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: self.stop() Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 393, in stop Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: time.sleep(0.1) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 242, in handle_chld Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: self.reap_workers() Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: File "/home/ubuntu/Web/env/lib/python3.9/site-packages/gunicorn/arbiter.py", line 525, in reap_workers Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) Aug 16 19:38:28 vps-bdd44ecc gunicorn[10466]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Aug 16 19:38:28 vps-bdd44ecc systemd[1]: gunicorn.service: Main process exited, code=exited, status=1/FAILURE Aug 16 19:38:28 vps-bdd44ecc systemd[1]: gunicorn.service: Failed with result 'exit-code'. I believe the error lies within ExecStart=/home/ubuntu/Web/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Slide-Hackers-Web/src/project.sock project.wsgi:application, but I am not sure, any help? -
Customize One-To-One Relation Dropdown in Django Admin
I have a One-To-One relation on my users that connects them to their account how do i go about editing this dropdown that is provided by Django so as it will provide me with more detailed information directly in the dropdown box. right now it says Profile Object(1035) I would like it to say something like Username(ID) -
Django dynamic installed apps
I'm trying developing an app where basically represents plugin architecture. Each plugin consist an app where can be developed separatelly and builded in a tar.gz file. This file then uploads to the server and gets installed via pip (I'm using this tutorial). I'd like to know if there is a way that django can load the app after it's installed. Here are the methods that I used in my views.py def upload(request): if request.method == 'POST': app_file = request.FILES['app'] #gets the builded zip name = request.POST['name'] #gets the name of the app path = _save_file(app_file) #save the file and return the path _install_file(path) #install the tar via pip _add_app(name) #try to load in installed apps return render(request, 'upload.html') return render(request, 'upload.html') def _save_file(file): path = f'/usr/src/mysite/plugins/{file.name}' with open(path, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) return path def _install_file(path): code = subprocess.check_call([sys.executable, '-m', "pip", "install", path]) print(code) def _add_app(name): installed = settings.INSTALLED_APPS + [name] # apps.unset_installed_apps() apps.set_installed_apps(installed) management.call_command('migrate', name, interactive=False) When I execute the code and upload the tar.gz file, it outputs: ... web-mysite | File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready web-mysite | raise AppRegistryNotReady("Apps aren't loaded yet.") web-mysite | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I'm using the dev … -
Saving the query object of one Django-Model into another
I am new to Django. I want to save the queried instance of Model-A,'Q' into Model-B. Model-A corresponds to Database D1 and Model-B to D2. In simple terms something like: Q=queryset(A).using('D1') Q.save(database='D2',model='Model-B') How can I do it? -
Ajax request to Django returns 500 Internal Server Error
Im pretty new in Django and Im trying to collect data with Ajax. Additionally, I would like to add Im trying to make and edit quiz app from tutorial(so Im doing it by tutorial, not from the scratch. After clicked button I got an error console.log('hello world quiz') const url = window.location.href console.log(url) $.ajax({ type: 'GET', url: `${url}data`, success:function(response){ console.log(response) }, error: function(error){ console.log(error) } }) I see that path is wrong, it should be: http://127.0.0.1:8000/1/, not http://127.0.0.1:8000/1/data. But changing from: url: `${url}data`, to: url: `${url}`, not collecting information about amount of arrays etc. I have also error from terminal: Traceback (most recent call last): File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/ad/Documents/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ad/Documents/test01/src/quizes/views.py", line 20, in quiz_data_view for q in quiz.get_questions(): File "/home/ad/Documents/test01/src/quizes/models.py", line 22, in get_questions return self.question_set.all[:self.number_of_questions] TypeError: 'method' object is not subscriptable But really no idea what could I change in quizes/models.py: from typing import Text from django.shortcuts import render from .models import Quiz from django.views.generic import ListView from django.http import JsonResponse # Create your views here. class QuizListView(ListView): model = Quiz template_name …