Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Python script from rest API in django
I have a script file (.py) which I need to run in my POST API requests. The scripts have few input parameters as well. I am able to follow the link: https://django-extensions.readthedocs.io/en/latest/runscript.html and now I am successfully able to run a script from the shell. python manage.py runscript scriptName --script-args arg1 arg2 But now, I want to run the same script with arguments in my API where arguments will be posted from the POST requests. I found that I can use subprocess for it. But it's not working. Below is the code I am trying to run: cmd = subprocess.Popen(['scriptName', arg1, arg2], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = cmd.communicate() Please help me out and let me know what I am doing wrong here. -
How to match two databases in python django
I am trying to create a model in which manufacturers can post a load which needs to be shipped and a transporter can post that his truck is going from point A to point B. If the Origin, Destination and load(to be transported and truck capacity) matches then both of them are notified like a tinder match. I have tried researching on automatic matching but the closest I come to is the Hungarian Algorithm that solves the assignment problem, but I am not so sure if it's the right direction or not. In the model I have already created input forms for both sections i.e. manufacturers and transporters and the data is saved in a Database. I am thinking of applying a trigger function which rechecks for a best match everytime a new entry comes in Database Here is the Data from both input forms: Manufacturer M_ID From To M_Type T_Type T_Length T_Weight #Trucks Loading_Time 1025 A B Boxes Open 12-Tyre 22 3 27-March-2019 6:00PM 1029 C D Cylinders Trailer HIGH 23 2 28-March-2019 6:00PM 1989 G H Scrap Open 14-Tyre 25 5 26-March-2019 9:00PM Transporter T_ID From To T_Type T_Length T_Weight #Trucks Price 6569 A B Open 12-Tyre 22 … -
What causes 'function' object has no attribute '_committed' error in django views?
I am trying to store a persistent sklearn joblib model through my app's model. Suddenly, my save() call in my views raised an error. something like this: 'function' object has no attribute '_committed' This is writen for django2.1 Here is my view: def predictionModelCreateView(request, **kwargs): proj_pk = kwargs.get('pk') if request.method == 'POST': form = PredictionCreateModelForm(proj_pk, request.POST) print('POST') if form.is_valid(): predModel = form.save(commit=False) # proj = Project.objects.filter('id'=kwargs('pk').first() predModel.model_file = train_model #sample joblib file to be stored into database predModel.save() # form.save() messages.success(request, f'Model has been created!') return redirect('project-home') else: form = PredictionCreateModelForm(project_id=proj_pk) context = { 'form': form } return render(request, 'predictions/create_prediction_model.html', context) Additionally, here is my Forms.py: ALGORITHM_TYPE = ( ('bin-log regression', 'Binary Logistic Regression'), ('another regression', 'Another Model') ) class PredictionCreateModelForm(forms.ModelForm): # proj = '' name = forms.CharField(max_length=100) algorithm_type = forms.ChoiceField( choices=ALGORITHM_TYPE, widget=forms.RadioSelect, label="Select Algorithm:" ) predictors = forms.MultipleChoiceField( widget = forms.CheckboxSelectMultiple, label="Select Feature Predictor:" ) target_column = forms.CharField( widget = forms.RadioSelect, label="Select Target Feature:" ) def __init__(self, project_id=1, *args, **kwargs): super(PredictionCreateModelForm, self).__init__(*args, **kwargs) project = Project.objects.get(id=project_id) df = pd.read_csv(project.base_file) cols = df.columns a_cols = np.column_stack(([cols, cols])) self.fields['predictors'].choices = a_cols self.fields['target_column'].choices = a_cols class Meta: model = PredictionModel fields = ['name', 'algorithm_type', 'target_column', 'model_file'] exclude = ['model_file'] And here is … -
Creating custom Search filter in Django API view
I have my custom API view and I want to use Search filter in this view, but generic filter dodn't work so i want to create custom one but It doesn't work and I dont know where is problem. view class TaskIndexAPIView(APIView): filter_backends = (CustomSearchFilter,) search_fields = ('name', 'description', 'user__username') def get_queryset(self): return Task.objects.all() def get(self, request): tasks = self.get_queryset() for i in tasks: if i.date <= date.today(): i.delayed = 'This task is delayed' i.save() else: i.delayed = '' i.save() serializer = IndexSerializer(tasks, many=True) return Response(serializer.data) My custom search filter search_filter class CustomSearchFilter(filters.SearchFilter): def get_search_fields(self, view, request): if request.get_queryset.get('name', 'user'): return ['name', 'user'] return super(CustomSearchFilter, self).get_search_fields(view, request) -
Django - Unable to open database file when logging into admin with nginx running
After typing my credentials into my Django admin. I get an error and it's an unable to open database error. I had to turn debugging on in order to get the error. I've tried searching other threads and many people indicated it's a rights issue to the folder or database itself. And I believe my nginx uses www-data I've tried to chown www-data /home/ubuntu/ chown www-data /home/ubuntu/db.sqlite3 however it still does not work after giving rights to the folder. Also I tried setting a true path in my settings.py to the database file which does not help it either. I know when an analyst setup my nginx is not used python-apps, installed in the system, but used virtualenv folder with virtual environment: /home/env/ I'm not sure if this is what is possibly the cause or how I fix it? -
Django: for loop and if condition in one line
I want to bring if dynamic_tickets: and for ticket in dynamic_tickets: in one line. I always receive a syntax error. Do you have an idea, how to achieve that? def adjust_prices(): events = Event.objects.filter(status=EventStatus.LIVE) active_events = [event for event in events if not event.is_over] for active_event in active_events: dynamic_tickets = [ ticket for ticket in active_event.tickets.all() if ticket.dynamic_pricing_activated() ] if dynamic_tickets: for ticket in dynamic_tickets: print(ticket) print("DO OTHER STUFF") -
Error of Required Field In Django APIView
I am trying to Update A Employee. I am able to update also. But the problem is coming a while updating when i am not sending data in body. It is giving error of Required Field. This error is one of kind - where i was not sending excempt in json body serializer2 {'excempt': [ErrorDetail(string='This field is required.', code='required')]} Even i tried to put required=False and it is working but i am not understanding if we are passing instance of that EmployeeProfileSerializer(userprofile, data=request.data). Example userprofile but why it is still it is giving error. And how should i tackle it. I don't think this is the solution required=False?. APIView class EmployeeUpdateApiV2(APIView): def post(self, request, *args, **kwrgs): try: accesstoken=AccessToken.objects.get( token=self.request.META.get('HTTP_AUTHORIZATION').replace('Bearer ', '') ) except ObjectDoesNotExist: return Response ( { "status" : False, "error" : "Wrong Access Token", "error_message":"You have provided wrong access token.", } ) user_id = request.data['user_id'] user = get_object_or_404(User, id=user_id) print(user) userprofile = get_object_or_404(UserProfile, user=user_id) print(userprofile) serializer1 = EmployeeRegisterSerializer(user, data=request.data) serializer2 = EmployeeProfileSerializer(userprofile, data=request.data) if serializer1.is_valid() and serializer2.is_valid(): serializer1.save() serializer2.save() print('Inside Valid') return Response ( { "status" : True, "message":"Employee Updated Successfully.", "api_name" : "EmployeeUpdateApiV2", "result": serializer1.data, "result1": serializer2.data, } ) print('Out Valid') print('serializer1 ', serializer1.errors) print('serializer2', serializer2.errors) return … -
Idea about downloading file in django
I have a piece of code which uploads file from users def upload_article(request): if request.method == 'POST': form = ArticleForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('journals') else: form = ArticleForm() return render(request, 'jurnal/article_upload.html', {'form':form}) but Users should download uploaded files as well. How can I do this? any ideas plz? -
How to get decrement forloop.counter in django template?
I'm new to django and python, and not able to find how to get decrement forloop.counter. (no matching result in google & stack overflow.) Please help me. -in_a_django_template.html START {% for value in list %} {% forloop.counter- %} {% endfor %} END What I expected: START 5 4 3 2 1 END -
django - search function with relational query
I am attempting to create a search functionality that returns products that are associated with a vendor. In each listing that is returned I would like to have the vendor name and create a link to the vendor's page using the vendor primary key. The relationship between both tables is created in a vendor_id as a foreign key pointing to the vendor table. Ideally in the output I could do something like: {% for product in products %} {{product.name}} <br /> {{product.description}} <br /> <a href="{% url 'vendor' vendor.id %}>{{vendor.name}}</a> {% endfor %} I can get all vendors, but that seems inefficient, and I am not sure how to make the relationship between the vendor who "owns" the product in that cycle of the loop. I've seen a post on select_related but that did not work for me, and appears to be used with objects.get instead of objects.filter Here is my search functionality defined in view.py def search(request): queryset_list = Products.objects.order_by('id') if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) context = { 'products': queryset_list } return render(request, 'products/search.html', context) -
how to built Live chat web-app in Django?
I want to develop a live chat web-app using django as our college sir told and for that purpose I am studying django and python for past 1 month and i am not sure where to begin the project. I needed a suggestion what i need to study before starting a project and how exactly the things work with live chat web-app -
Is it possible to install Haskell and non-Haskell packages within a Python/Django app deployed in Heroku?
My Django application uses packages associated with Haskell, such as HLint, and some non-Haskell packages such as graphviz. I use the shlex command in my app to call a bash script that then goes on to call the package. This runs fine locally. However, I have also deployed the app to Heroku using Travis - over there, the views designed to activate the bash scripts do not run. I'm running a before_deploy script to install the required packages and the Travis build says they are successfully installed; I don't think the packages are available to the Heroku app. My question is: is it possible for the required packages to be available in the Heroku app? And if so, how can I configure Heroku to run them via bash or some other means? Any help would be really appreciated! It may be useful to know that the app is running in a Linux environment, and that I'm using a single Python build pack. Code My .travis.yml file is as follows: sudo: true language: python python: - '3.6' env: - DJANGO=2.1.5 install: - pip install -q Django==$DJANGO - pip install -q -r requirements.txt script: - python manage.py test before_deploy: - "./before_deploy.sh" deploy: … -
Deploying Django with Apache and Waitress on Windows doesn't serve static files
I'm have deployed my Django app using Apache and Waitress as a Python WSGI server. My Apache server is configured to serve my static files and I have set up a ProxyPass for my WSGI server: httpd.conf: Alias /static/ /path/to/static/ <VirtualHost *:*> ProxyPreserveHost On ProxyPass / http://localhost:9001/ ProxyPassReverse / http://localhost:9001/ ServerName localhost </VirtualHost> I use Waitress to handle the rest of the app like so: python: waitress-serve --listen=0.0.0.0:9001 my_app.wsgi:application The idea is that Apache handles all my static files and Waitress handles the rest. This setup works on Linux/OSX, but I cannot seem to get it to work on Windows, where waitress WSGI seems to prevent Apache from serving static files, e.g. if I don't run the WSGI server then Apache serves the static files, but if both are running I cannot see my static files (404). Any idea why this fails on Windows? I'd like to find a solution that works on all three platforms without having to use mod_wsgi, pure Python WSGI solution preferred. Any help with this workflow would be much appreciated, thanks! -
TypeError: int() argument must be a string, a bytes-like object or a number, not 'QueryDict'
I am trying to print filtered sub_location drop down according to location attribute form extended admin user in Django. I have a view which displays a form and saves the same form. There is no problem showing the view but when saving I get this following error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'QueryDict' Here is my code:- MODEL: class Location(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class SubLocation(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class AdminProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) def __str__(self): # __unicode__ for Python 2 return self.user.username class Batch(models.Model): location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) sub_location = models.ForeignKey(SubLocation, on_delete=models.SET_NULL, null=True) batch_name = models.CharField(max_length=30, unique=True) def __str__(self): return self.batch_name FORM: class BatchForm(forms.ModelForm): class Meta: model = Batch fields = ('sub_location', 'batch_name') def __init__(self, user, *args, **kwargs): super(BatchForm, self).__init__(*args, **kwargs) self.fields['sub_location'].queryset = SubLocation.objects.filter(location = Subquery(AdminProfile.objects.filter(user = user).values('location'))) VIEW: def add_batch(request): if request.user.is_authenticated: msg = "" if request.method == "GET": batch_form = BatchForm(user=request.user) else: batch_form = BatchForm(request.POST, request.FILES) if batch_form.is_valid(): try: obj = batch_form.save(commit=False) #logined admin location will be here admin_object = AdminProfile.objects.filter(user = request.user) obj.location = admin_object[0].location obj.save() batch_form = BatchForm() … -
Django model prevent Duplicate based on two variables
I need to make sure the entry does not have the same project and case id. How is the best way to prevent a duplicate entry? Here the project can not have the same case twice. class Cases(models.Model ): project = models.ForeignKey ( Project, on_delete = models.CASCADE ) case = models.ForeignKey ( Case, on_delete = models.CASCADE ) active = models.BooleanField ( default = 1 ) Thank you. -
How to generate a variable number of forms according to an input and save the data from the forms into one model at the same time?
I am new to django. I am trying to make an Airline Reservation System where the user can select the source, destination and the number of passengers for the flight search. This will take the user to the page where all the flights are listed according to the query. Now, once the user selects a flight, I want to take the user to a page where he can enter passenger details (name, age, gender). Now, I want that whatever number the user had entered in 'number of passengers' field in the first page, that many forms will be shown for the user in this page and after filling the data and pressing submit button, I want to save the data from all the forms to a single model in the database(namely the passenger model). I am not able to do it. Any help will be appreciated. -
Django: How to download file from S3
What I want to do is to download file from Amazon S3. I've been looking up the ways to do it but it didn't work well. I saw this question and use the one of the anwer's code. What I did is like this. html <a href="{% url 'topic:download_file' filename=file.filename %}{{ file.filename }}</a>" views.py from django.utils.encoding import smart_str def download_file(request, filename): file_path = "https://%s/media/topic/%s" % (settings.AWS_S3_CUSTOM_DOMAIN, filename) resp = HttpResponse(content_type='application/force-download') resp['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename) resp['X-Sendfile'] = smart_str(file_path) return resp when I click the filename, it actually starts downloading file but the file is empty or it says we don't support this file type for image. To be honest, I still don't get what the code above is doing at all. How can I download the file correctly? I'm currently checking if it works on local. -
LDAP authentication not working with Django python
I have been assigned with a task to implement LDAP authentication for one of the application with Django framework but after exploring hundreds of solution, finally I implemented but it's not working as expected. attached is the implemented code and my use case is when the user tries to self authenticate to the web application, he/she should be sent to respective pages based on the authentication result. Login success-> Home page Login failure->back to login page Settings.py import os import ldap from django_auth_ldap.config import LDAPSearch # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) AUTH_LDAP_SERVER_URI = "192.168.210.24" AUTHENTICATION_BACKENDS = ('django_auth_ldap.backend.LDAPBackend',) AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=corp,dc=yodlee,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)") # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '4xkkb*m!&@^xzhkpe6#gxe@xeee0ug3q0h$@-)#lv8+0dqpid*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["LDAP hostIp"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'NewHandBook.apps.NewhandbookConfig', ] 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', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ] ROOT_URLCONF = 'HandBook.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
What GIT / workflow do I use to avoid overwriting my server side Django users, with my local users who are dummy/test users?
I am developing a Django application in Atom locally, and then on pythonanywhere, when I'm ready, I'm doing a GIT PUSH command after syncing those changes to GITHUB. The problem is, at some point, those changes which were pushed through from my local development env have overwritten all my live users with just the local dummy users I've been using for testing and development. Basically, I'm testing the login and registration system locally, logging in and registering with lots of dumb emails. Once I was happy it was working, I synced the Django code I'd changed to GITHUB (with the desktop app) and then did a GIT PUSH command on a PythonAnywhere (my server) console. The sqlite DB is included in those updates/sync - is that correct? Or should it just be totally ignored? I just realised, that one (perhaps all?) pushes have overwritten my sqlite DB, and there were perhaps 30 or so actual users who had signed up on the website whose data is no longer registered on the site. I managed to find a trace of them in the Django Admin logs, and I've found the version history of the Sqlite DB on GITHUB, but my question … -
Django ModelForm with ModelChoiceField and Query Filter
I need to create a list of cases in dropdown list from data passed into the form for the individual firm. I pass the id into the form, but how do I use it in the CaseChoiceField query? First in the view: form = NewProjectCaseForm ( id = f.id ) The model form: class NewProjectCaseForm ( forms.Form ): # get all the cases for the firm # how do I get the ID from below ??? case = CaseChoiceField ( queryset = Case.objects.filter (firm_id = id ) ) def __init__ ( self, *args, **kwargs ): # id from the view self.id = kwargs.pop ( 'id' ) super ( NewProjectCaseForm, self ).__init__ ( *args, **kwargs ) self.helper = FormHelper () self.helper.layout = Layout ( Div ( Div ( 'case', css_class = 'large-10 cell' ), css_class = 'grid-x' ), ButtonHolder ( Submit ( 'submit', 'Add Case', css_class = 'button small-6' ) ) ) to create the dropdown I use this: class CaseChoiceField ( ModelChoiceField ): def label_from_instance ( self, obj ): return '{} - {}'.format ( obj.name, obj.firm ) I am using Crispy forms (for Foundation) I hope this makes sense. Thank you very much. -
im trying to make a call to my discord bot.py and django is throwing no module for all my import how would i fix this?
using pycharm: I'm trying to call a function in my django to a small discord bot.The bot code runs fine outside of Django but inside it it throws error saying my modules are not loaded the error: File "main\urls.py", line 17, in <module> from . import views File "main\views.py", line 7, in <module> from.raiderweb import ranker File "main\raiderweb.py", line 2, in <module> import discord ModuleNotFoundError: No module named 'discord view.py from django.shortcuts import render from django.contrib import messages from.raiderweb import ranker def leaderboard(request): ranking = ranker() if ranking: return render(request=request, template_name="main/leaderboard.html", context={"ranking": ranking}) else: messages.error(request, 'Couldn\'t connect to the database') return render(request=request, template_name="main/leaderboard.html") and my discord bot raiderweb.py if it helps import asyncio import discord import mysql.connector async def ranker(): connection = False try: cnx = mysql.connector.connect()#connection stuff connection = True except mysql.connector.Error as error: return False if connection: cur = cnx.cursor() cur.execute('SELECT * FROM users ORDER BY rank DESC') txt = [] for row in cur: string = str(row) string = string.replace('\"', '') string = string.replace('"', '') string = string.replace("\'", '') string = string.replace("'", '') string = string.replace("(", '') string = string.replace(")", '') string = string.replace("'", '') txt.append(string.split(',')) if len(txt) == 0: return False return txt else: return False … -
"Error while running '$ python manage.py collectstatic --noinput'" after changing database on django
I'm a bit of a beginner with Django so forgive me if I'm missing some necessary information. I recently revised my database on settings.py and I keep getting an error when I run git push heroku master The error block looks like: Counting objects: 22, done. Delta compression using up to 8 threads. Compressing objects: 100% (22/22), done. Writing objects: 100% (22/22), 4.84 KiB | 825.00 KiB/s, done. Total 22 (delta 12), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Python has released a security update! Please consider upgrading to python-3.6.8 remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing requirements with pip remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> remote: import psycopg2 as Database remote: ModuleNotFoundError: No module named 'psycopg2' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 15, in <module> remote: execute_from_command_line(sys.argv ) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File … -
Unable to raise Validation Error from ModelForm on the browser (DJANGO)
I am trying to raise an error and show it on the browser if the user enter submit an input of an email already inside the database. For some reasons, instead of raising the error, nothing is saved in the database but the user is redirected to the page i set to redirect to. I want to be able to stop the user and raise the error if email exists in the database. Model: class Foo(models.Model): full_name = models.CharField(max_length=50) email = models.EmailField(max_length=50, blank=False) phone_number = models.CharField(max_length=10, blank=False) Forms. from django import forms from .models import Foo class FooModelForm(ModelForm): class Meta: model = Foo fields = ['full_name', 'email', 'phone_number'] help_texts = {'full_name': ('Required'), 'email': ('Required'), 'phone_number': ('Required')} def clean_email(self): ''' Check if exists in database. ''' email = self.cleaned_data.get('email') try: match = Foo.objects.get(email=email) except Foo.DoesNotExist: return email # raise forms.ValidationError('This email is already in use.') from django.shortcuts import render, redirect from snippets.models import Foo from snippets.forms import FooModelForm def index(request): if request.method == 'POST': form = FooModelForm(request.POST) if form.is_valid(): form.save() return redirect('snippets:form-sent') else: form = FooModelForm() context = {'form':form} return render(request, 'snippets/index.html', context) HTML <form method="post" id="form"> {% csrf_token %} {{ form|crispy }} <div class="text-center"> <button type="submit" class="btn btn-primary">Download now</button> </div> … -
How to display dynamic content from database on bootstrap modal by using button id on django
I am loading bootstrap cards with brief university details using a for loop with context passed from my django view. Now, I want to display a modal with more details depending on which card's button I press. I would like this dynamic data to be displayed without reloading/refreshing the page. this is my views.py from django.shortcuts import get_object_or_404 from django.http import JsonResponse from university.models import University def dispUni(request): # hoping to retrieve university.id from the clicked button uniPK = request.GET.get('universityId') uniDetails = { 'university': get_object_or_404(University, id=uniPK) } return JsonResponse(uniDetails) this is my urls.py from django.urls import path from . import views urlpatterns = [ path('', views.dispUni, name='uniDetails') ] This is my html page where I want to display this information <div class="container-fluid d-flex justify-content-center"> <!-- display Universities --> <div class="row mt-5"> {% if universities %} {% for university in universities %} <div class="card mx-4 uniCard" style="width: 20rem;"> <img src="{{university.photo_main.url}}" class="card-img-top" alt="{{university.title}}"> <div class="card-body"> <h5 class="card-title Dark-shades-text">{{university.title}}</h5> <p class="card-text"> <i class="fas fa-map-marked-alt"></i>&nbsp;{{university.city}}, {{university.state}} <br> <i class="fas fa-phone"></i>&nbsp;{{university.phone_number}} </p> <!-- Button trigger modal --> <button type="button" value="{{university.id}}" id="btn-UniModal{{university.id}}" class="btn main-color" data-toggle="modal" data-target="#UniDetails"> View Details </button> </div> </div> {% endfor %} {% endif %} </div> </div> <!-- Modal for University Details --> <div … -
"Can't connect to local MySQL server through socket '/tmp/mysql.sock'
Trying to connect to django with mysql, but facing some issues. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blessen', 'USER': 'root', 'PASSWORD': 'open', } } Then created a database blessen. Started mysql server $systemctl restart mysql . $python manage.py dbshell executed successfully, but $python manage.py runserver Error: django.db.utils.OperationalError: (2006, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") $django-admin runserver django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.