Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i am facing problem while connecting to azure sql using django, please help me
D:\CDP\Anomaly_Detection_Service\config\server_config.ini System check identified no issues (0 silenced). December 20, 2021 - 07:31:27 Django version 2.1.15, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. title_name :>> asg file_name :>> 536484573901199.csv file_content :>> b't,a,b,c\n1,Wed Oct 13 15:43:22 GMT 2021,abc,india\n2,Wed Oct 13 15:43:22 GMT 2021,xyz,\n3,Wed Oct 13 15:43:22 GMT 2021,pqr,india\ n4,Wed Oct 13 15:43:22 GMT 2021,efg,japan\n' [20/Dec/2021 07:31:46] "POST / HTTP/1.1" 200 8440 Internal Server Error: /save_filedetails Traceback (most recent call last): File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\engine\base.py", line 3240, in _wrap_pool_connect return fn() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 310, in connect return _ConnectionFairy._checkout(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 868, in _checkout fairy = _ConnectionRecord.checkout(pool) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 476, in checkout rec = pool._do_get() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\impl.py", line 146, in _do_get self._dec_overflow() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__ compat.raise_( File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_ raise exception File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\impl.py", line 143, in _do_get return self._create_connection() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 256, in _create_connection return _ConnectionRecord(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 371, in __init__ self.__connect() File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 666, in __connect pool.logger.debug("Error on connect(): %s", e) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__ compat.raise_( File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_ raise exception File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\pool\base.py", line 661, in __connect self.dbapi_connection = connection = pool._invoke_creator(self) File "D:\venv\Anomaly_Detection_Service\lib\site-packages\sqlalchemy\engine\create.py", line 590, in connect return dialect.connect(*cargs, **cparams) … -
How to add Background image in django admin login page
I would like to add django background image in my django admin login page here is my code it is not showing any error but still image is not loading. base_site.html {% extends "admin/base.html" %} {% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"><a href="{% url 'admin:index' %}">{{ site_header|default:_('Django administration') }}</a></h1> {% endblock %} {% block nav-global %}{% endblock %} {% load static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" type="text/css" href="{% static 'admin_extra.css' %}" /> {%endblock%} admin_extras.css body { /* The image used */ background-image: url('static\admin\containers.jpg') !important; /* Full height */ height: 100%; /* Center and scale the image nicely */ background-position: center; background-repeat: no-repeat; background-size: cover; } settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, "ProjectName", "static"), ) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') my code is running and no error popping up in console but still background image is unable to load -
how to escape ^ in django
Below are my codes. url.py app_name = 'home' urlpatterns = [ ... path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.Certification.as_view(), name='activate'), ] acc_active_emal.html {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, {{ domain }}{% url 'home:activate' uidb64=uid token=token %} {% endautoescape %} views.py def post(self, request, pk = None): ... message = render_to_string('registration/acc_active_email.html', { 'user': user, 'domain': 'mydomain', # current_domain 'uid': urlsafe_base64_encode((user.pk).to_bytes(5, 'little')), 'token': account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') When user sign up my site, I send active_email to confirm registration. But email send url like below. mydomain/%5Eactivate/(%3FPFwAAAAA%5B0-9A-Za-z_%5C-%5D+)/(%3FPaxyoyt-906068a2d7255bc3da520c10c5793d22%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/$ Then my site returns the current path, ^activate/(?PFwAAAAA[0-9A-Za-z_-]+)/(?Paxyoyt-906068a2d7255bc3da520c10c5793d22[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$, didn’t match any of these. How I escape %5E using {% url %} ?? -
Django query to get List of Sums of the Count of different Choices
I am trying to get a list of the sum of the count of different choices. The choices are strings, so I want to count the same strings and get their sum, and then do the same for other choices. I made a query but it does not give me the total count of each choice instead list them all with the count 1. model.py class sublist(models.Model): Music = 'Music' Video = 'Video' Gaming = 'Gaming' News = 'News' Lifestyle = 'Lifestyle' Access = 'Access' SUBTYPE_CHOICES =( (Music , "Music"), (Video , "Video"), (Gaming , "Gaming"), (News , "News"), (Lifestyle , "Lifestyle"), (Access , "Online Access"), ) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) name = models.CharField(max_length=150) cost = models.FloatField(default = 0) subtype = models.CharField(max_length= 50, choices = SUBTYPE_CHOICES, default = Access) This is my query. (i tried coming up with other combinations by looking at the documentation but no luck) expenselist = sublist.objects.filter(author = curruser.id) subtypecount = list((expenselist .annotate(subcount=Count('subtype')) .values('subtype', 'subcount') )) result of query above: [{'subtype': 'Access', 'subcount': 1}, {'subtype': 'Access', 'subcount': 1},{'subtype': 'Video', 'subcount': 1}] Desired result: [{'subtype': 'Access', 'subcount': 2},{'subtype': 'Video', 'subcount': 1}] -
in the command "pip install -r requirements.txt" what does '-r' meant? same as in "python3 -m pip install something" what does '-m' meant?
I searched before asking this question but i did get exact answer. can anyone let me know where to read about these operators and others like same as this? Thanks in advance. -
How to protect your API from abuse - DRF & React
I'm really struggling to wrap my head around the concept of protecting ones API end point. How do you do you protect it from abuse if it's exposed with React? I understand if a user were to login then be issued them with a token etc. I get that. But let's say have a front end that does not require someone to be logged in? They simply filling out a form with their details and it gets passed via you API then gets stored in the DB. Whats stopping someone just abusing your API? They could just write a script and attack you end point with spammy data? I just can't understand how this is protected? -
Django To use two FilterView classes in one template
I am creating a search form using FilterView in the main window. Double-click the input form in the search form in the main window to display the modal. I want to display another FilterView class in modal. The class of these two FilterViews is different in the model, filter, and form that they refer to. How can this be achieved? Views.py class Filter1(FilterView): model = Model1 filterset_class = Filter1 template_name = 'filter.html' class Filter2(FilterView): model = Model2 filterset_class = Filter2 template_name = 'filter.html' HTML(templates) <form action="" method="get"> <div class="row"> {{filter.form|crispy}} <-I want to use class filter 1 </div> <div id="myModal" class="modal fade" tabindex="-1" role="dialog"> ・・・ {{filter.form|crispy}} <- I want to use class filter 2 </div> -
Django - Return a list of months that a query of Post objects spans to front-end in local time
So I have kind of a weird and interesting problem. Lets say I want to be able to group posts on an application like Facebook by months in local time to whoever sent the request. Let's say I have a Post table in Django with the standard created, body and author fields. Where created is the date and time it is created. Let's say I want to find all posts by a user so that query would look like Post.objects.filter(author=<some name>). I want to be able to send back to the requester for these posts the dates they span. The reason this is slightly tricky is because Django stores in UTC and has no notion of user's time zone unless given. My initial idea would be make a url that's something like /post/<str:author>/<str:timezone> then somehow convert created date for all queried Post to that time zone and figure out the months. The timezone is needed to cover the edge case that someone posts on the last day of the month. Depending on the time zone that could be the current month in UTC or the next. How would I find all the months in the requestors timezone that Post span … -
User matching query does not exist. I want to add data if user is first time coming?
Actually I m working on Blood Donation system. I m checking that if user is already exist then I checking that He or She completed 90 days Or not if He or She completed then His or Her request will be accepted. if didn't complete then I will show message U have to Complete 90 days. I add data through data admin side and checked on the base of the CNIC that he or she completed 90 days completed or not and its Working But Now the main problem is that If add New Data from Front End he said User matching query does not exist. Now I have to Add else part But I don't know How? please tell me about that I m stuck from past 4 days. #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from django.shortcuts import redirect from .models import User from datetime import datetime,timedelta class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) existuser = User.objects.get(cnic = cnic) if existuser: previous_date = existuser.last_donation current_date = datetime.now().astimezone() print(previous_date,"-----_---",current_date) final = current_date - previous_date print("The final is -> ",final) if final < timedelta(days= 90): raise … -
None data value in nested serializer instance
During the update method I'm getting none as an output of child models. My serializers are as follow - class AddressSerializer(serializers.ModelSerializer): stateName = serializers.SerializerMethodField() class Meta: model = publicAddress fields = "__all__" def get_stateName(self, instance): return instance.state.state_name class customerSerializer(serializers.ModelSerializer): custgroupName = serializers.SerializerMethodField() publicAdd = AddressSerializer(many=True) class Meta: model = customerMaster fields = ['id', 'mobileNumber', 'custGroup', 'custgroupName ','publicAdd'] def get_custgroupName(self, instance): return instance.custGroup.name and the update method od customerSerializer - def update(self, instance, validated_data): pubAdd_data = validated_data.pop('publicAdd') data = instance.publicAdd print(data) return instance Here I'm getting the data in the print statement as None. And I'm sure there are multiple addressess linked to the customer as in get request of customer publicAdd is a list of values. Trying to figure out what have I missed ? -
How To Get Data User Login And Post It In Form Django
Im Confused, To Get Data User Login and post it in forms. My question is how to do that ? authentication/models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name dashboard/models.py class UserProfil(models.Model): jenis_kelamin_choice = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) nik = models.CharField(max_length=11, null=True, unique=True) nidn = models.CharField(max_length=11, null=True, unique=True) dashboard/forms.py class UserProfilForm(ModelForm): class Meta: model = UserProfil fields = '__all__' widgets = { 'user' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'namaLengkap', 'placeholder' : 'Nama Lengkap'}), 'nidn' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nidn', 'placeholder' : 'Nomor Induk Dosen Nasional'}), 'nik' : forms.TextInput({'class' : 'form-control form-control-user', 'id' : 'nik', 'placeholder' : 'Nomor Induk Karyawan'}), } dashboard/views.py class UserProfilTemplateView(FormView): template_name = 'dashboard/profil.html' form_class = UserProfilForm def get(self, request, *args, **kwargs): user = self.request.user return self.render_to_response(self.get_context_data()) def form_valid(self, form): messages.success(self.request, 'Data Profil Berhasil Disimpan.') print(form.cleaned_data) return super().form_valid(form) I Want The Name User Is Appear in the Form "Nama Lengkap", How should i do ? -
Can we add any python package to Django?
Below code working fine for Wikipedia site but not with particular WordPress website, I want to get backlinks for this site, or is there any python package for backlink checker or scraper. thanks in advance import requests def get_url_data(link): f = requests.get(link) return f.text, f.status_code if __name__ == "__main__": url = "https://yoblogger.com/" data = get_url_data(url) print("URL data", data[0]) print("URL status code", data[1]) -
Django Channels onmessage doesn't run
I don't know why onmessage doesn't run in Javascript when I send something of type 'websocket.message'. The websocket_receive method supposedly sends something to websocket.message because 'successfully updated data' prints every time I open a connection. The problem is that I see no console output in the onmessage event in the JS. consumers.py class ActivityStatus(SyncConsumer): def websocket_connect(self, event): self.room_name = 'activity' self.send({ 'type': 'websocket.accept' }) async_to_sync(self.channel_layer.group_add)(self.room_name, self.channel_name) def websocket_receive(self, event): dict_received = json.loads(event['text']) user = CustomUser.objects.get(username=dict_received['user']) user.is_online = True user.save() async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'username': dict_received['user'] } ) print('succesfully updated data') html javascript const activityUrl = 'ws://' + window.location.host + '/ws/active/'; const activityWS = new WebSocket(activityUrl); activityWS.onopen = function(event) { console.log('connection is onpened'); activityWS.send(JSON.stringify({ 'user': '{{ request.user.username }}' })); } activityWS.onmessage = function(event) { console.log(event) console.log("Message is received"); } -
How to use Swagger with Python based Django REST APIs?
I am trying to make a CRUD API with using Django. How I implemented swagger docs with Django. -
Django jwt channels cannot verify
I have two Django Projects sharing the same database. One is django-restframework One is django-channels django-restframework login will get JWT I cannot verify successfully in django-channels I wrote the test function restframework verify ok class Test(APIView): def get(self, request): try: token = UntypedToken( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0') print(token, 'token') except (InvalidToken, TokenError): print('InvalidToken, TokenError') return Response(status=status.HTTP_200_OK) channels verify error @database_sync_to_async def test_get_user(): try: token = UntypedToken( 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.???.Z22plhyGEZW9IBZLzICu2mWTkuMrblYQhvUGoUtpKd0') print(token, 'token') except (InvalidToken, TokenError) as e: print('InvalidToken, TokenError', e) Can't verify JWT like this? -
ImportError: Couldn't import Django. with "poetry"
I configure django project with poetry. I created pyproject.toml and installed django. [tool.poetry] name = "graphene" version = "0.1.0" description = "" authors = ["yilmaz <yilmaz@gmail.com>"] license = "MIT" [tool.poetry.dependencies] python = "^3.9" #Django installed Django = "^4.0" psycopg2-binary = "^2.9.2" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" If I try adding django again: # venv is activated (base) ┌──(venv)─(t㉿kali)-[~/Documents/projects/graphql/graphene] └─$ poetry add django 1 ⨯ The following packages are already present in the pyproject.toml and will be skipped: • django If you want to update it to the latest compatible version, you can use `poetry update package`. If you prefer to upgrade it to the latest available version, you can use `poetry add package@latest`. Nothing to add. I created apps folder and want to add an app p manage.py startapp users apps/users this is giving me this error: ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
CSRF verification failed. Request aborted.No solution works for me on the internet
In my forms with the same token I add the @csrf_exemp, but since in login I am using the Django default I do not have a login view, I have put the token in each template and deactivated the MIDDLEWARE in settings and nothing to solve the problem too I have the host fine, I can register but not logging in nor in the django admin it gives me the same error. enter image description here {% extends "layout.html" %} {% block content %} {% load static %} {% load crispy_forms_tags %} <main style="min-height: 100vh"> <section> <div class="container p-4" style="min-height: 100vh"> <div class="row"> <div class="col-12 col-md-6 offset-md-3"> <div class="card bg-black"> <div class="card-body"> <h2 class="h3">Login</h2> <form method="post"> {% csrf_token %} {{ form | crispy }} <a href="{% url 'main' %}">Home</a> | <a href="{% url 'sign_up' %}">Sign Up</a> <input type="submit" class="btn btn-success" value="login" /> </form> </div> </div> </div> </div> </div> </section> </main> {%endblock%} -
exec: "--env": executable file not found in $PATH: unknown
I try to build a docker image of my Django App. The build is successful but when I run it, I've got this error : docker run -it -p 8888:8888 gads-api-monitor --env PORT 8888 docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "--env": executable file not found in $PATH: unknown. ERRO[0000] error waiting for container: context canceled Here's my pipenv : [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "4.0" gunicorn = "*" psycopg2-binary = "*" [dev-packages] [requires] python_version = "3.9" And my Dockerfile : FROM python:3.9-slim ENV APP_HOME /app WORKDIR ${APP_HOME} COPY . ./ RUN pip install pip pipenv --upgrade RUN pipenv install --skip-lock --system --dev CMD /usr/local/bin/gunicorn google_ads_api_monitor.wsgi:application --bind "0.0.0.0:$PORT" --env "DJANGO_SETTINGS_MODULE=google_ads_api_monitor.settings.production" I'm not sure to understand what "executable" is not found here. Gunicorn ? Or my Django settings file ? Many thanks ! -
How to prefill input box with future date in Django template?
I am trying to prefill an input field with a future date in a django template. <input name="expiration_date" class="form-control" id="expiration_date" type="text" data-toggle="input-mask" data-mask-format="0000-00-00" value="{{ object.table.expiration_date|default:'' }}" How could I set it so object.table.expiration_date|default:'' is prefilled with datetime.now() plus 30 days? -
Importing Model from different App - Getting Relative Import or No module Errors
I've read numerous Stackoverflows on this subject and unfortunately still don't understand what's going on and can't get this to work. I'm trying to import a model contained in a different app of the same project. I've tried just about everything including: from ProjectName.Appname.models import Class from ..AppName.models import Class import ProjectName.Appname.models (then reference via models.ClassName) from Appname.models import Class Nothing seems to work. I either get a no module error, or relative import error. Note, PyCharm doesn't show any errors and displays the location of the file/class when hovering over the import, so naming is correct. The error only occurs when running check. -
SSL/TLS Error when Testing Django API via HTTPS on Localhost
In an effort to test an API via an HTTPS connection locally, I followed the approach described here by Evan Grim where I use stunnel4 as a middleman between my requests and my API server. Here's a minimalist urls.py that will generate a token provided a valid username and password. from django.urls import include, path from django.contrib import admin from rest_framework_simplejwt import views as jwt_views urlpatterns = [ path("admin", admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),] I have also modified the stunnel4 config file as below. pid= cert = stunnel/stunnel.pem sslVersion = all foreground = yes output = stunnel.log options = NO_SSLv2 [https] accept=8443 connect=8001 TIMEOUTclose=1 However, when I try any route via postman or curl (at port 8443), I receive the following errors. I get a tls_setup_handshake:internal error from stunnel4. 2021.12.19 18:51:22 LOG5[16]: Service [https] accepted connection from 127.0.0.1:36502 2021.12.19 18:51:22 LOG3[16]: SSL_accept: ../ssl/statem/statem_lib.c:109: error:141FC044:SSL routines:tls_setup_handshake:internal error 2021.12.19 18:51:22 LOG5[16]: Connection reset: 0 byte(s) sent to TLS, 0 byte(s) sent to socket Postman gives me the following error in its console when I submit requests through it. Error: write EPROTO 48081748826312:error:10000438:SSL routines:OPENSSL_internal:TLSV1_ALERT_INTERNAL_ERROR:../../third_party/boringssl/src/ssl/tls_record.cc:594:SSL alert number 80 And when I try curl, I see the following. curl: (35) OpenSSL SSL_connect: Connection … -
SearchVectorField - joined reference not allowed for taggit field
My model definition is as follows (a simplified model of the one being used in actual product. There are a coupe of other fields: from django.db import models from taggit.managers import TaggableManager from django.contrib.postgres.search import SearchVectorField from django.contrib.postgres.indexes import GinIndex class Product(models.Model): tags = TaggableManager() search_vector = SearchVectorField(null=True) class Meta: indexes = [ GinIndex(fields=['search_vector']) ] I run make migrations and migrate commands. These work correctly. I then run the following set of commands to build the index: search_vector = SearchVector('tags__name') Product.objects.all().update(search_vector=search_vector) I end up getting the following error: django.core.exceptions.FieldError: Joined field references are not permitted in this query This is clearly caused by the tags__name field, but I am not sure how to solve it. Can someone please explain what I would need to do in order to run the above commands correctly? Thanks! -
How to unpack a Python queued job results?
I finally got to setting up RQ to help me with long running function calls in django, but I'm running into a problem with unpacking the values from a queue's result. I checked out the docs as per https://python-rq.org/docs/results/ but to no avail. Here's what my code currently looks like under views.py: def render_data(request): reddit_url = request.POST.get('reddit_url') sort = request.POST.get('sort') res = q.enqueue(run_data, reddit_url, sort) val1, val2 = res.result data = { 'val1': val1, 'val2': val2, } return JsonResponse(data) The expected response would be the returned values, but instead, in console I receive an error 500 along with createError.js:16 Uncaught (in promise) Error: Request failed with status code 500. In Heroku console, the error is File "/app/pc_algo/views.py", line 49, in render_data 'val1': val1, NameError: name 'users_data' is not defined Am I unpacking the jobs results wrong? I've tried looking up the error but I couldn't find a better tutorial on RQ results than the one above. -
Display file uploaded to Aws S3
https://s3.console.aws.amazon.com/s3/object/<Bucket_name>?region=us-east-2&prefix=media/<filename> is the url I want to save to my custom Abstractuser from file upload. How would you upload a file to override the user avatar field from the views.py? from django.shortcuts import render from .forms import UserProfileForm def index(request): return render(request,'home.html') The retrieving part works. <img class="profile-pic" src="{{user.avatar.url}}" > Will currently display the avatar associated with the user. https://s3.console.aws.amazon.com/s3/object/<Bucket_name>?region=us-east-2&prefix=media/default.png Settings.py MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, MEDIAFILES_LOCATION ) DEFAULT_FILE_STORAGE = 'portfolio.storage_backends.MediaStorage' -
Django cannot find new modules, using pyenv and virtualenv
I’m sure this is pretty straightforward to someone experienced. I’m learning Django through the Wedge of Django ebook. I’m using Python 3.8.7 installed via pyenv like so: pyenv install 3.8.7 Then I’ve set up a virtualenv like so: pyenv virtualenv 3.8.7 everycheese I activate the virtualenv in my repo like so: pyenv local everycheese The environment is shown as active in the prompt, as it starts with (everycheese). The main project is cloned from Django Cookiecutter https://github.com/cookiecutter/cookiecutter-django I’ve then used pip to install requirements from the requirements.txt files. However - I’m running into trouble when I try to add new packages (by adding the package to requirements.txt as a new line and installing again with pip). pip list, or pip freeze both show the new module. But when I add the module to my INSTALLED_APPS and try to import it in my models.py file, Django cannot find it. When I type which python, and which pip, they point to different directories and I think this may be part of the problem but I am stuck.