Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving Django static and media files using Docker and Nginx
I have a system which I am trying to Dockerize and set up a CI/CD pipeline for but it is not serving static or media files in production (does on local). The production docker-compose file looks as such: version: "3.8" services: backend: build: context: ./backend dockerfile: Dockerfile.prod image: "${BACKEND_IMAGE}" volumes: - static_volume:/backend/assets - media_volume:/backend/media expose: - 8000 env_file: .env depends_on: - db nginx: build: context: ./nginx dockerfile: Dockerfile.prod image: "${NGINX_IMAGE}" restart: unless-stopped ports: - 80:80 - 443:443 volumes: - ./nginx/certbot/conf:/etc/letsencrypt - ./nginx/certbot/www:/var/www/certbot - static_volume:/backend/assets - media_volume:/backend/media depends_on: - backend - db volumes: static_volume: media_volume: nginx.prod.conf: upstream backend { server backend:8000; } server { listen 80; listen [::]:80; location / { proxy_pass http://backend; proxy_set_header Host $http_host; } location /api/ { proxy_pass http://backend; proxy_set_header Host $http_host; } location /admin/ { proxy_pass http://backend; proxy_set_header Host $http_host; } location /static/ { alias /backend/assets/; } location /media/ { alias /backend/media/; } } Django settings.py: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets/') STATICFILES_DIRS = [STATIC_DIR, ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' I am getting a 404 Not Found for both static and media files. Help on identifying what I am doing wrong would be appreciated... -
ZoneInfoNotFoundError: 'No time zone found with key utc'
While trying to load my webpage on the browser, I got the message. A server error occurred. Please contact the administrator and when I go back to check my termimal, I see the message zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC' I have checked but don't know what's wrong. I even tried changing the UTC to my original timezone, but it still didn't work. P.S: I started getting this error after I tried working on templates inheritance Here's what my settings.py file looks like INSTALLED_APPS = [ 'newapp.apps.NewappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'new.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'new.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # … -
Trying to run a django project and getting errors
So I am about to start working on a project with Python Django (never worked with these before). However, before starting I want to run the application. My manager gave me the files on which I should be working and there is the manage.py file already created. Now I have installed Python, pip and django and am trying to run this with the command python manage.py runserver And I get this long error which I am not sure what is all about considering that this whole project is already working on the computer of my manager and is even uploaded to a host. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\Program Files\Python310\lib\importlib\__init__.py", line … -
Unkown string showing up on rendered HTML page
A random string "b b b b b" gets inserted between two HTML components which doesn't exist in my code to begin with. I currently have a js script to find this garbage string and just remove it manually. Was wondering if anyone knew why this was happening so I could actually fix it instead of this workaround This is how the relevant part of the code looks on my local machine (look at the start of the table tag) - <div class="row"> <div class="col-1"></div> <div class="col-10"> <div class="row answers"> <table class="part2"> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td>1. {{form.question_1.label_tag}}</td> {% for choice in form.question_1 %} <td><span class="radio">{{ choice.tag }}</span></td> {% endfor %} </tr> </tbody> </table> </div> </div> <div class="col-1"></div> </div> This is how the rendered HTML Code looks. I copied this from the browser inspect element (Notice how the random b \n b \n b\n is inserted right before the table tag without it being in the code)- <div class="row answers"> b b b b b b <table class="part2"> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td>1. <label>When this student is feeling happy, they can control their happiness.</label></td> </tr> </tbody> </table> </div> This is a Python-Django project being … -
Django raw SQL as Models
I'm working on a project where some database queries are complex enough to need raw SQL. How to organise these queries? Most advice seems to be to put them in a view but I would like them implemented as Models to support reuse. I want to be able to call them: Model.objects.all() in any view that needs them. I have seen some stuff where a custom Manager is added to an existing model but some of the queries don't touch any database tables that are implemented as Models so it is not obvious which model to add the custom Manager to. What I would like is to set up a library of these queries and pull them into views as needed. Is there a Django approach that I should employ for this? TIA -
Have only hours and minutes in durationfield Django
I would like to have a duration field expressed just as hours and minutes. I post you my code: views.py log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft)) total_flight_hours = log_entry_dual.aggregate(eet=Sum(ExpressionWrapper( F('ata') - F('etd'), output_field=IntegerField()), output_field=DurationField()))['eet'] Now, total_flight_hours is printed in my template as (for example) 03:00:00 which states for 3 hours. Since I just need hours and minutes and I don't care about seconds, is there a way to get rid of the seconds? Thank you very much in advance -
Django: How i can make space or makethe things go to the next line if needed in the view.py
I have did some calculation on 2 fields and then i want to display the result recursively Here is the Django code View: @login_required def calcul_resultat(request): resultat = Decimal(0) charge_per = request.POST.get('charge_per', False) charge_exp = request.POST.get('charge_exp', False) calcul="" if not (charge_per): return HttpResponse({"result" :resultat}) else: float_charge_per = float(charge_per) resultat = 1.5 * float_charge_per calcul += "calculation of deadweight" calcul += " " calcul += str(resultat) float_charge_exp = float(charge_exp) resultat = 1.35 * float_charge_exp calcul += " " calcul += "calculation of operating load" calcul += " " calcul += str(resultat) return render(request,'pages/result.html',{'calcul':calcul}) when i press the button calculate , here is the result in the picture , it seems that the(br tag) ""it doesn't work enter image description here How i can resolve that is there any example can help me.Thanks to make space in django if needed -
Get Spotify access token with spotipy on Django and Python
I'm new to Django and I'm trying to link Spotify to my webapp. I'm using Spotify to do it and it correctly access to Spotify. To do it I have a button that opens the view below views.py @authenticated_user def spotify_login(request): sp_auth = SpotifyOAuth(client_id=str(os.getenv('SPOTIPY_CLIENT_ID')), client_secret=str(os.getenv('SPOTIPY_CLIENT_SECRET')), redirect_uri="http://127.0.0.1:8000/", scope="user-library-read") redirect_url = sp_auth.get_authorize_url() auth_token = sp_auth.get_access_token() print(auth_token) print("----- this is the AUTH_TOKEN url -------", auth_token) return HttpResponseRedirect(redirect_url) If I don't use auth_token = sp_auth.get_access_token() everything works fine and I got redirected to the correct. Unfortunately, if I add that line of code to access the access token, instead of staying on the same page, it opens another tab on the browser with the Spotify auth_code and lets the original page load forever. Is there a way to retrieve the access token in the background without making my view reload or open another tab in the browser? -
How to get only selected items from admin CheckboxSelectMultiple Django
I am trying to display only selected participants from admin panel but ending up getting all of them. My admin panel looks like this: These are the team captains so when they are joining the tournament the template shows their team my template looks like this: {% for team in teams %} {% for player in tournament.participants.all %} {% for member in team.members.all %} {{ member.username }} {% endfor %} {% endfor %} {% endfor %} And admin.py class TournamentAdminForm(ModelForm): class Meta: model = Tournament fields = '__all__' widgets = { "participants": CheckboxSelectMultiple(), "broadcast_talents": CheckboxSelectMultiple(), } -
Maintain Two Types Of User
So I have a requirement where I have to maintain two types of users. A company and all of its users, to manage day-to-day work. And also create public data like showing a few items and related images and set availability for meetings and more. Public user who can see the items, images. and can book the meetings. Now for the first case, every user is created by official email and password as registeruser endpoint from rest-framework. there is user profile and other company data. For the second type of user (public), I have to give access for social login as well as login by email/mobile (maybe). I am confused as how to configure this in the best possible way. the company datas' are important. Should I create both user types in the same database (differentiating by user types)? or should I use a seprerate database then how to fetch data from two databases (never done this)? Also to keep my datas safe from unauthorized access. Or is there a better way to manage all of my requirements which I'm totally unaware of? Like a better approach. Looking for an explanation from an experienced person. Thanks -
Access Json data key name
I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIVIEW. Below is my viewsets and generics code: class TestList(viewsets.ViewSet): queryset = Test.objects.all() def list(self,request): serializer = TestSerializer(self.queryset, many = True) return Response({'columns': serializer.data}) class TestList(generics.RetriveAPIView): queryset = Test.objects.all() serializer_class = TestSerializer -
django and react, simplest way to integrate
I have a react app created using "create-react-app" that I would like to connect to a backend, now due to the fact I already use django and like how it simplifies many of the redundant tasks, I chose it as my backend. In many articles the recommended way of using it is using django_rest_framework and making api calls from the react app, I neglected a very important point here as I thought I could have django serve the simple static pages and use react only for the js heavy tasks (which in my case is only one page and the main point of the website). my questions are, can I keep user logged in if he navigates from the simple html pages to the app (in case they live on separate servers) ? If not possible how can I integrate a create-react-app project with django ? -
Is it possible to have flexible decimal_places for a model in django?
I am working in a model that i would like to use for diferent kinds of investmensts. So i am wondering if is it possíble to have flexible decimals. For example: This is the class class Asset(models.Model): portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, default=1) category = models.ForeignKey(Category, on_delete=models.CASCADE) shares_amount = models.DecimalField(max_digits=18, decimal_places=0, default=0) If i leave it blank i get the error: "DecimalFields must define a 'decimal_places' attribute." Maybe what i am trying is not possíble, probably i need to find another solution. I would like to know if is possíble to have this decimal places fleixible. Something like: shares_amount = models.DecimalField(max_digits=18, decimal_places=x) if category == cryptocurrency x=18 else x=0 -
Need help running an existing django project on a new machine
Im just starting to do some work with an already existing python django project. I just installed python in my machine and Im trying to figure out how to install django and as I see I am supposed to use pip for this. However, in all tutorials people are firstly creating a virtual environment for it. Now my question is since the project already exists do I need to create a virtual environment from scratch? I can see that there is already a env folder which includes bin and lib folders. Can I somehow use this environment? And if so are there some specific commands for that? I am on windows by the way. -
Django - Pass a dropdown Item value from the template to the view
I have a Django template that looks like this <td>{{ row.column1 }}</td> <td>{{ row.column2 }}</td> <td>{{ row.column3 }}</td> <td> <select name="dropdown_menu_option" id="dropdown_menu_option"> <option selected="selected" disabled>--SELECT--</option> <option value="10">10</option> <option value="50">50</option> <option value="100">100</option> <option value="256">256</option> <option value="512">512</option> <option value="1">1</option> </select> </td> <td><a href="{% url 'exampleurl' row.column1 row.column2 row.column3 dropdown_menu_option %}" class="action-button-small shadow animate grey">Take Action</a></td> I have my URLs set up like this - url(r'exampleurl/(?P<column1>.+)/(?P<column2>.+)/(?P<column3>.+)/(?P<dropdownvalue>)$', viewName, name='exampleurl'), My view is set up like this - def viewName(request, directory, column1, column2, column3, dropdownvalue): print(column1) print(column2) print(column3) print(dropdownvalue) The problem I am having is, dropdownvalue is NULL. This is one of the reasons I have removed the regex from the URL.py file for dropdownvalue. How do I pass this value from my template to the view? -
Formtools does not display my formsets, only the forms
hi i am using formtools to submit a multistep form. The problem is that I haven't found many tutorials about it. And it is that I was able to create the form but the formset does not appear. What am I doing wrong or what am I missing? if I stopped using formtools if the formset is seen but not with formtools, I think that I am not generating the view correctly so that it displays the formset and saves the data throughout the multi step form views.py class PresupuestoWizardView(SessionWizardView): file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'files')) form_list = [PresupuestosClientesForm, PresupuestosVehiculosForm,PresupuestosParteForm,PresupuestosManoObraForm,PresupuestosPagosForm,PresupuestosFotosForm] template_name = "Presupuestos/new-customer.html" def done(self, form_list, **kwargs): return render(self.request, "Presupuestos/new-customer.html", { 'form_data': [form.cleaned_data for form in form_list], }) forms.py ParteFormSet = formset_factory(PresupuestosParteForm, extra=extra_forms, max_num=20) ManoObraFormSet = formset_factory(PresupuestosManoObraForm, extra=extra_forms, max_num=20) PagosFormSet = formset_factory(PresupuestosPagosForm, extra=extra_forms, max_num=20) extra_forms = 1 DESCUENTO = ( ('Quantity', 'Quantity'), ('Percentage', 'Percentage'), ) DISCOUNT= ( ('Quantity', 'Quantity'), ('Percentage', 'Percentage'), ) class PresupuestosClientesForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { 'titulo': forms.Select( attrs={ 'class': 'form-select' } ), 'nombre': forms.TextInput( attrs={ 'class': 'form-control' } ), 'apellido': forms.TextInput( attrs={ 'class': 'form-control' } ), 'correo': forms.EmailInput( attrs={ 'class': 'form-control' } ), 'telefono': forms.TextInput( attrs={ 'class': 'form-control' } ), 'tel': forms.TextInput( … -
How to render multiple update forms in Django
here is my problem. I have a list of objects that I display in a table and all works just fine except that I would like to edit them inside a modal and submit them using AJAX. I though that it was a simple idea to render, for each row, a form with the inputs pre-filled and then submit the selected form with AJAX. I wonder if there is a relatively simplified way to render the UpdateForm without writing manually all the input fields. Something like this: <table> {% for transaction in transactions %} <tr> <td>{{ transaction.date|date:"d.m.Y" }}</td> <td>{{ transaction.amount }}</td> <td> <a href="#" data-bs-toggle="modal" data-bs-target="#edit{{ transaction.id }}">Edit</a> <div class="modal" id="edit{{ transaction.id }}"> {{ transaction_form }} </div> </td> <tr> {% endfor %} </table> But how can I pass the form from the view? The way I'm currently doing it is that when the user click on edit the page refresh and the modal is displayed with the form prefilled but it is (a) slow to open and (b) I don't think it is a nice way to do it. This is my current code views.py class ProjectDetailView(DetailView): model = Project template_name = "template.html" context_object_name = "project" def get_transactions(self): transactions = … -
Invalid encoding ISO-8859-1 : in django webhook for stripe
I found an error Invalid encoding: ISO-8859-1 , 404 Error during the test a webhook event named payment_intent.succeeded. Below is the views.py code for the webhook:(maybe I have errors in the code) img -
Django-debug-toolbar not showing error 403 forbidden
I was trying to use django-debug-toolbar but it doesnt show up at all, so i tried inspecting my page and i found out theres actually a erro 403 forbidden that is hiding the toolbar. I've tried everything i knew and searched on the internet like a maniac but what solved someone elses problem wasnt working for me. Sorry if the code is hard to understand, i'm still a novice programmer. If any other information is required pelase let me know settings.py: import mimetypes from functools import partial import dj_database_url from primeiraAplicacaoDjango import base # noqa from pathlib import Path from decouple import config, Csv import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = config('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) AUTH_USER_MODEL = 'base.User' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'collectfast', 'django.contrib.staticfiles', 'primeiraAplicacaoDjango.base', ] 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', ] ROOT_URLCONF = 'primeiraAplicacaoDjango.urls' TEMPLATES = [ { … -
Get the next seven days of the week in views - Django
How to get seven consecutive days of the week in views using Django. I try this, but it returns an error. from datetime import datetime day = datetime.now() day_1 = datetime.now() + datetime.timedelta(days=1) day_2 = datetime.now() + datetime.timedelta(days=2) day_3 = datetime.now() + datetime.timedelta(days=3) day_4 = datetime.now() + datetime.timedelta(days=4) day_5 = datetime.now() + datetime.timedelta(days=5) day_6 = datetime.now() + datetime.timedelta(days=6) day_7 = datetime.now() + datetime.timedelta(days=7) It returns: type object 'datetime.datetime' has no attribute 'timedelta' -
Django server not refreshing pages after reloading
When I start the Django server it gives me proper output at first but the next time I make changes to code it does not reflect the changes even after reloading. I am usin react at the frontend. -
Django Beautiful Soup Parsing Data
Here is the XML data that I am trying to retrieve values from with Beautiful Soup. <students> <alerts> <medical> <description>All Nuts, Environmental allergies (rash): Sublingual Immunotherapy- Epi-Pen Asthma</description> <expires_date>NEVER_EXPIRES</expires_date> </medical> </alerts> </students> That value you I am trying to get is description . However, anytime I go over 3 instances of the .find() command it doesnt work. Here is my code. for student in soup.find_all('student'): #SETS VALUES WITHIN ALERTS ARRAY try: alert_medical = student.find("alerts").find("medical").find("description").get_text() except Exception as err8: print(err8,'Error in student.alert array.') Error I get in console is : object has no attribute 'find' -
Connection reset by peer after fetching file in django
i'm using django as a backend server and flutter as a mobile app. when i request a 3d model from my django app the message Exception occurred during processing of request from ('127.0.0.1', 49163) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socketserver.py", line 747, in __init__ self.handle() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer but when i open the same file from another online server it works! what should i do? -
How can i save data to text file from django form inputs?
I wanna save form input datas to text file and storage in local. But i am also new at django. Here is my sample codes... How can i save to form datas to text file? Thanks for help. My models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse #from datetime import datetime, date class Post(models.Model): #post_date = models.DateField(auto_now_add = True) soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="") soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="") soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="") soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="") soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="") soru6 = models.CharField(verbose_name='Birinci Evlilik', max_length=10000, default="") My forms.py file from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' #field = ('title', 'author') yapılabilir widgets = { # 'title': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), # 'author': forms.Select(attrs={'class': 'form-control'}), # 'body': forms.Textarea(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), 'soru1': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı yazınız'}), 'soru2': forms.TextInput(attrs={'class': 'form-control'}), 'soru3': forms.TextInput(attrs={'class': 'form-control'}), 'soru4': forms.TextInput(attrs={'class': 'form-control'}), 'soru5': forms.TextInput(attrs={'class': 'form-control'}), 'soru6': forms.TextInput(attrs={'class': 'form-control'}), my views.py file from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from .forms import PostForm from django.urls import reverse_lazy from django.db.models import Q from django.http … -
Django - how to correctly install library without pip in venv to work after deployment
According to this guide I successfully connected to Sybase database in my django project in virtual environment. After deployment in Apache the web writes this error message Environment: Request Method: GET Request URL: http://localhost:8080/ Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'sybase_app') 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', 'django.middleware.security.SecurityMiddleware') Traceback: File "/home/pd/sibp/env/lib/python3.6/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/contextlib.py" in inner 51. with self._recreate_cm(): File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/transaction.py" in __enter__ 150. if not connection.get_autocommit(): File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in get_autocommit 286. self.ensure_connection() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 130. self.connect() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/utils.py" in __exit__ 97. six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/pd/sibp/env/lib/python3.6/site-packages/django/utils/six.py" in reraise 658. raise value.with_traceback(tb) File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in ensure_connection 130. self.connect() File "/home/pd/sibp/env/lib/python3.6/site-packages/django/db/backends/base/base.py" in connect 118. conn_params = self.get_connection_params() File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlany_django/base.py" in get_connection_params 517. root = Database.Root('PYTHON') File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in __init__ 466. 'libdbcapi_r.dylib') File "/home/pd/sibp/env/lib/python3.6/site-packages/sqlanydb.py" in load_library 458. raise InterfaceError("Could not load dbcapi. Tried: " + ','.join(map(str, names))) Exception Type: InterfaceError at / Exception Value: Could not load dbcapi. Tried: None,dbcapi.dll,libdbcapi_r.so,libdbcapi_r.dylib I edited /etc/apache2/envvars and appended a line export LD_LIBRARY_PATH=/opt/sqlanywhere17/lib64:/opt/sqlanywhere17/lib32:$LD_LIBRARY_PATH The error message changed to: Environment: Request Method: GET Request URL: http://localhost:8080/ Django Version: 1.8 Python Version: 3.6.9 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', …