Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uncaught ReferenceError jquery and Django (model.Form)
I am having an Exception thrown after calling a jquery function inside the Widgets area of the forms as below : class TipsterEmployeeAdminForm(forms.ModelForm): class Media: js = ('admin/js/tipster-employee.js',) class Meta: model = TipsterEmployee fields = ( 'first_name', 'last_name', 'slug', 'email', 'international_prefix', 'phone_number', 'tipster_partner', ) widgets = { 'tipster_partner': SelectExtra( attrs={'onchange': 'updateEmployeeUrl("{base_url}")'.format( base_url=get_base_url())}), } The exception thrown is : Uncaught ReferenceError: updateEmployeeUrl is not defined This happens around here : widgets = { 'tipster_partner': SelectExtra( attrs={'onchange': 'updateEmployeeUrl("{base_url}")'.format( base_url=get_base_url())}), } Also in the base.html template , the jquery link is there : -
I can't filter fields in model (Django)
I have models (removed all unnecessary): class Contract(models.Model): contract_number = models.IntegerField(primary_key=True) student = models.ForeignKey('Student', on_delete=models.CASCADE) lessons = models.ManyToManyField('Lesson') class Student(models.Model): name = models.CharField(max_length=150) age = models.IntegerField() class Lesson(models.Model): lesson_time = models.TimeField(verbose_name='Время урока') lesson_date = models.DateField(verbose_name="Дата урока") is_done = models.BooleanField(verbose_name="Проведен") In my html I use special link: <a href="{%url 'stud_detail' id=student.id%}"> which leads to url in urls.py: path('student/<int:id>', views.one_student, name='stud_detail') And there is my view (again removed all other models): def one_student(request, id): student = Student.objects.get(id=id) contracts = Contract.objects.filter(student=id) lessons = Lesson.objects.filter(id__in=contract) print(lessons) content = dict(student=student, contracts=contracts, lessons=lessons) return render(request, 'studbase/student_detail.html', content) Now I have 10 lessons in the contract, but based on filtration results I have only one. print(lessons) returns only 1 lesson instead of 10 lessons. What did I do wrong? -
Doesn`t work method create for serializers.ModelSerializer
I study Django Rest Framework. First I created CustomUser Model based on AbstractUser. After I created serializer RegistrationSerializer based on ModelSerializer. In RegistrationSerializer I wrote my own create() for password2 validation using official specification. Extra field for password2 works well. But my RegistrationSerializer "doesn't use" my create(). Looks like it doesnt know about method and I cant understand why. On my POST request without password2 I recieve password2 is required. On my POST request with password2 I recieve CustomUser() got an unexpected keyword argument 'password2'. accounts/models.py class CustomUser(AbstractUser): image = models.ImageField(verbose_name="Аватар", upload_to="covers/", null=True) And accounts / api / serialers.py from rest_framework import serializers from accounts.models import CustomUser class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = CustomUser fields = ['email', 'username', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True}, } def create(self): account = CustomUser( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) account.set_password(password) account.save() return account -
Django, importing models class into new file. Import error attempted relative import with no known parent
I am working on learning Django by making a simple analysis dashboard. I did the startproject command and the startapp command like the tutorial ran through. I added a new file called connectionOracle.py in the app folder. My folder structure is (top folder is was created via venv) AnalysisSite |AnalysisSite |coreAnalysis ||models.py ||connectionOracle.py I have a class called WorkOrder in the models.py file. I am trying to import it into the connectionOracle.py file by doing the following from .models import WorkOrder I then go to the Command Line (on windows) and navigate tot he coreAnalysis folder and run the following python connectionOracle.py I get an error that says. ImportError: attempted relative import with no known parent package I did some reading online, and I tried doing an absolute path with AnalysisSite.AnalysisSite.coreAnalysis.models that didnt work. I also tried moving the connection file to different directories and that didnt work either. I also tried going into the command line and typing set DJANGO_SETTINGS_MODULE = AnalysisSite.settings I also put a _init_.py in each folder. (Django automatically put it into the project directory and app directory). I am not sure what I am doing wrong -
Find the shortest path in a web application
I want to create a web application. I want to create a site that can recommend tourist places to tourists. I would like to recommend the shortest route between several tourist places to the tourist. I use Python, Django and OSM. please guide me. -
How to Reset a Password through mobile number in Django?? Please suggest some tips
This is my models.py. I want to reset the password of the user by mobile number. Can't find answer yet. Can someone help to suggest any methods? Thanks in advance. from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User,null=True, on_delete=models.CASCADE) mobile = models.CharField(max_length=15, blank=True, null=True) def __str__(self): return self.user.username -
Django forms gives 'str' object has no attribute '_meta'
I am making a custom User model that looks like this accounts/models.py class MyUser(AbstractUser): role_tuple = ( ('admin', 'admin'), ('user', 'user'), ('activist', 'activist'), ) role = models.CharField(null = True, default='user', max_length = 200, choices = role_tuple) user_proof_image = models.ImageField(null=True, upload_to='user_proof_images') Added it to settings.py AUTH_USER_MODEL = 'accounts.MyUser' I now want to create a form using the custom user model so I used from django.contrib.auth.forms import UserCreationForm from CPW.settings import AUTH_USER_MODEL class CreateUserForm(UserCreationForm): class Meta: model = AUTH_USER_MODEL fields = ['username', 'email', 'password1', 'password2', 'role'] But it tells me from .forms import CreateUserForm File "C:\Users\xyz\OneDrive\Desktop\Django\CPW\user_auth\forms.py", line 4, in <module> class CreateUserForm(UserCreationForm): File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 258, in __new__ apply_limit_choices_to=False, File "C:\Users\xyz\AppData\Local\Programs\Python\Python37\lib\site-packages\django\forms\models.py", line 142, in fields_for_model opts = model._meta AttributeError: 'str' object has no attribute '_meta' I have never tried forms of custom users. Help? -
pass django template file content to javascript
I want to pass a template file content to my javascript file for later use to create DOM elements there. What I have tried is to pass it to js as a variable with an include tag like this: <script>const list_item = {% include 'myapp/list_item.html' %}</script> But this end up getting: Uncaught SyntaxError: Unexpected token '<' Is there a way I can pass template file content to js file? Thanks in advance -
Django-How to update or edit formset factory form in my invoice
I am working in Django having invoice form saved successfully but can't update the invoice form. I have a main invoice form and another LineItemSet formset form with calculation. I tried to edit it but the formset form cannot update the existing one and saved it as a new entry. Here is my model form: class Customer(models.Model): name = models.CharField(max_length=100) GST_no = models.CharField(max_length=50, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) customer_email = models.EmailField(null=True, blank=False) billing_address = models.TextField(null=True, blank=False) date_created = models.DateField(auto_now_add=True, auto_now=False, blank=True, null=True) def __str__(self): return self.name class Supplier(models.Model): name = models.CharField(max_length=100) GST_no = models.CharField(max_length=50, blank=True, null=True) phone = models.IntegerField(blank=True, null=True) supplier_email = models.EmailField(null=True, blank=False) bill_address = models.TextField(null=True, blank=False) date_created = models.DateField(auto_now_add=True, auto_now=False, blank=True, null=True) def __str__(self): return self.name class PriceTag(models.Model): name = models.IntegerField(blank=True, null=True) def __str__(self): return str(self.name) class Products(models.Model): item = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=100, blank=True, null=True) pricetag = models.ManyToManyField(PriceTag) quantity = models.IntegerField() price = models.IntegerField(default='0') reorder_level = models.IntegerField(default='0', blank=True, null=True) last_updated = models.DateField(auto_now_add=False, auto_now=True) date = models.DateField(auto_now_add=False, auto_now=False, null=True, blank=True) comment = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return str(self.item) class Invoice(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) invoice_no = models.IntegerField(blank=False, null=True) due_date = models.DateField(auto_now_add=False, auto_now=False, null=True, blank=True) last_updated = models.DateField(auto_now_add=False, auto_now=True) status = models.BooleanField(default=False) total_amount = models.DecimalField(decimal_places=2, … -
Django sessionid not created for Locust client
I'm running Django 2.2.24 and Locust 2.1.0 for load testing. When I run some Locust test logging in as a the Django admin user, there are no issues - all my GETs work as expected. Now I am actually logging in as a specific user. From a web interface, Django passes a CSRFtoken and a sessionid token with no problem. From the Locust client however, the sessionid does not show up at all. Not only that, but when I look in the django_session table (where the web tokens do exist), there are no tokens for the Locust client. I think this is more related to Django session management than to locust - hence the post in this forum. My locust file looks like this: def on_start(self): ''' The start script for each user - this order is important ''' # Below 3 lines work fine - we get the csrftoken and put it in the header successfully response = self.client.get("/accounts/login") self.csrftoken = response.cookies['csrftoken'] self.headers = {'X-CSRFToken': self.csrftoken} # Now login with username and password as POST r1 = self.login() return r1 def login(self): # admin login and retrieving it's access token udata = {'username': self.username, 'password': self.password} cookies=self.client.cookies.get_dict()) #csrftoken cookie … -
How to show the information in the same page where I am submitting form in django
I am trying to submit a form and get the result in the same page where I have created the form . But , can't get the values in the same page . But , whenever I am trying to take the value in a different page it's working. My views.py file : def home(request): words = request.GET['text'] count = len(words.split()) context = {'count':count} return render(request,'index.html',context) My index.html file: <div class="container"> <h3 style="display:inline-block; text-transform: capitalize; padding-top: 10px; border-bottom: 2px solid #e5e5e5;">Word counting app</h3> <h5 style="padding-top: 40px;text-transform: capitalize;">enter your word below to count</h5> <div class="row"> <div class="col-lg-6"> <form method="" action=""> <textarea name="text" cols="30" rows="7"></textarea> <button type="submit" style="padding: 6px 28px; border: none; background:orange; margin-top: 10px;">Submit</button> </form> <p>{{count}</p> </div> </div> </div> -
Exception thread in Accessing sqlite3 in django
I am playing in Django, in views - print('datatable', Datatable.objects.all()) - shows this error/exception Exception in thread Thread-5: Traceback (most recent call last): File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Karthiyayini Dhillip\Documents\dj\project1\cv\views.py", line 87, in update print('datatable', Datatable.objects.all()) File "C:\Users\Karthiyayini Dhillip\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 255, in __repr__ return '<%s %r>' % (self.__class__.__name__, data) models.py from django.db import models # Create your models here. class Users(models.Model): email = models.EmailField(max_length = 254) password = models.CharField(max_length=100) def __str__(self): return(self.email) class Datatable(models.Model): classes = models.CharField(max_length = 254) date_d = models.DateField() def __str__(self): return(self.date_d, self.classes) How to solve this, thanks -
Django - Query for posts along with it's number of replies?
So I'm trying to populate a news feed with posts of a certain category. Then I want to be able to display the number of replies on the post. The reason I'm confused on how to do this, is because I filtered through goals by category then I filtered all the posts associated with all those goals and now I have a list of a dictionary containing the post body and goal description and create date, but I'd like to also add in the number of replies and I'm not sure how to do this in an efficient way. Also I realize my way of doing things in the view.py is less than ideal so any suggestions would be great! Model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) class ReplyPost(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="reply") post_id = models.ForeignKey(Post, on_delete=models.CASCADE) body = models.CharField(max_length=250) View.py @api_view(['GET']) def get_most_recent_posts_by_category(request, category, count): goals_list = list(Goal.objects.filter(category = category).values_list('uuid', flat=True)) data = list(Post.objects.filter(goal_id__in=goals_list).order_by('created').values('body', 'goal_id__description', 'created')) data['goal_description'] = data['goal_id__description'] data['post_body'] = data['body'] del data['goal_description'] del data['body'] return JsonResponse(data, status=status.HTTP_200_OK) -
Access to Django admin site deployed on non-root URL with mod_wsgi
I have a DRF 3.12.4 (with Django 3.2.3) app deployed on apache httpd 2.2.15 with mod_wsgi 4.6.5 running on Python 3.7. I want my app to be served on non-root URL, e.g. prefixed by /alert. With the following settings in wsgi.conf: ... Alias /alert/static/ /var/www/djangoapps/achtung_alert/static/ WSGIDaemonProcess achtung_alert user=infa group=infa threads=25 display-name=%{GROUP} home=/var/www/djangoapps/achtung_alert python-home=/var/www/djangoapps/achtung_alert/venv python-path=/var/www/djangoapps/achtung_alert:/var/www/achtung_alert WSGIScriptAlias /alert /var/www/achtung_alert/wsgi.py process-group=achtung_alert application-group=%{GLOBAL} WSGIProcessGroup achtung_alert <Location /alert > WSGIProcessGroup achtung_alert WSGIPassAuthorization On </Location> ... and project's urls.py: from django.contrib import admin from django.urls import path, include from rest_framework.authtoken import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('achtung_alert.urls')), path('api-auth/', include('rest_framework.urls')), path('api-token-auth/', views.obtain_auth_token), ] and no FORCE_SCRIPT_NAME in settings.py I am able to access all endpoints in my achtung_alert app, api-auth/, api-token-auth/ - all prefixed by /alert. But if I try to access /alert/admin/ I'm getting the following error from Django's debug page: Page not found (404) Request Method: GET Request URL: https://mysite/alert/admin/ Using the URLconf defined in achtung_alert_project.urls, Django tried these URL patterns, in this order: admin/ openapi [name='openapi-schema'] swagger-ui/ [name='swagger-ui'] ^events/$ [name='event-list'] ... The current path, alert/admin/, didn’t match any of these. If I make a typo in URL, then "/alert" prefix will be removed from the current path as expected: Page not found … -
Raise 404 instead of 500 when using an invalid uuid
I have a uuid field in my Document model If I get() my model with a bad uuid, I got a error 500. This line throw an error: x = Document.objects.get(uuid=object_uuid) Instead of a 500 I want a 404 error I wrote this, but I don't want to put my function everywhere it's so redundant (I'm lazy) def is_valid_uuid_or_404(object_uuid): try: return uuid.UUID(object_uuid) except ValueError: raise Http404("Invalid uuid") x = Document.objects.get(uuid=is_valid_uuid_or_404(object_uuid)) #Boring Someone has a good idea to make it better ? -
Django Filter BooleanFilter with 3 options - True, False and Both
I am trying to create a filter for where an attribute is null with Django-Filter for an Appointment model. The relevant docs are: https://django-filter.readthedocs.io/en/stable/guide/tips.html?highlight=isnull#solution-1-using-a-booleanfilter-with-isnull class Appointment(models.Model): ... professional = models.ForeignKey(telemed_models.HealthcareProfessionalProfile, null=True, blank=True, on_delete=models.SET_NULL, related_name='appointments', verbose_name=_('professional')) ... The filter I need is called 'Unassigned' which will filter for those appointments where no professional is set. I am using a checkbox for this: class AppointmentListFilter(django_filters.FilterSet): ... unassigned = django_filters.BooleanFilter(field_name='professional', lookup_expr='isnull', label=_("Unassigned"), widget=forms.widgets.CheckboxInput()) ... On page load (i.e. before clicking 'filter items') all items are shown (obviously) and the checkbox is unchecked. The weird behaviour is as a result of the following: After clicking 'filter items' the checkbox is technically 'working' when it is used - i.e. unchecked is showing appointments where professional is not null. Checked is showing appointments where professional is null. So, there's a clash with the fresh/page load state. Basically that on pageload unchecked means "all items", but after filtering, unchecked means "only those with a value". While the filter is technically doing what it is supposed to do, this is bad UX because it's quite confusing for the user. Does anybody know a good way of handling this? I mean, a boolean feels like the right way to … -
Does flask and django work together, should I learn them simultaneously?
I recently learned Django & I wonder if I have to learn Flask in order to have a good back end stack? I know Node.js and used it for APIs before but I don't know if it should be mixed with Django in a single project or not. Thanks in advance. Update: I am thinking APIs & Socket wise because I don't feel like Django supports them (Please correct me). -
Django models.CharField max_length not working
I am trying set up a model in Django, the DB I am using is SQLite class MyTable(models.Model): MyField = models.CharField(max_length=5) But when I try to enter a value more with length more than 5 it does not throw any error. >>> from AppOne.models import MyTable >>> MyTable(MyField="12345678").save() >>> MyTable.objects.all()[0].MyField '12345678' I read SQLite there is no length Limit for VARCHAR. So I will be able to connect to the DB out side Django. I will be able enter value with any length. But while doing it from Django should not it be validated. Am I doing anything wrong? What is the correct way? From Admin site it does not let me enter any value greater than 5 though. -
Django postgresql query return an array value in html table
I am trying to fetch array data from Django postgresql database and want to display in a html table. Also I input those data through html table with manual input which are given below: <td><input type="text" name="product_id" value="{{data.product_id}}" readonly></td> <td><input type="text" name="price" value="{{data.price}}" readonly></td> <td><input type="text" name="quantity" value="{{data.quantity}}" readonly></td> In views: product_id = request.POST.getlist('product_id') price = request.POST.getlist('price') quantity = request.POST.getlist('quantity') amount = request.POST.getlist('amount') purchase_table = PurchaseInvoice.objects.create(product_name=product_id, price=price, quantity=quantity) purchase_table.save() data successfully added in my database. data stored like ['value1','value2']. But when I am trying to display those data on my html table its show on same format like ['value1','value2']. I want to display those data separately like in first row value1 and 2nd row value2. my models, views and html code given bellow: models: class PurchaseInvoice(models.Model): product_name = models.CharField(max_length=500) price = models.CharField(max_length=300) quantity = models.CharField(max_length=200) def __str__(self): return self.product_name View: def purchaseDetails(request,pk): invo_data = PurchaseInvoice.objects.all().filter(invoice=pk) return render(request,'purchase/invoice_details.html', {'invoice':invo_data}) HTML: {% for data in invoice %} <tr><td> {{ data.product_name }}</td> <td>{{ data.price }}</td> <td>{{ data.quantity }}</td></tr> {% endfor %} -
How can I download all the files related to a specific request in an zip file at once?
I have a table in which all the files related to specific request are stored(a specific request can have more than one or few related files). I have used a download_zip_file function to download the file at once. But unfortunately I receive an error which says "[WinError 3] The system cannot find the path specified: '/media/documents/my_needs_Zxvf8IN.docx'" The file that is in the url error, exists.I don't know what caused the error and how to fix it. Does anyone has a clue?? my download zip function is here: @login_required def download_zip_file(request, docreq_id): doc_req = Documents.objects.get(id=docreq_id) if doc_req.sent_from_assignee: doc_ups = AMdocDocuments.objects.filter(docrequest__pk=docreq_id) filenames = list(map(lambda f: f.doc_file.url, doc_ups)) zip_subdir = "%s %s" % (doc_req.request_title, doc_req.user_email) zip_filename = "%s.zip" % zip_subdir s = BytesIO() zf = zipfile.ZipFile(s, "w") for i, fpath in enumerate(filenames): fname = fpath.split("/")[-1] # Rename uploaded files to doc file ext = fname.split(".")[-1] if ext: fname = '%s' % smart_str(doc_ups[i].amdoc.doc_name + "." + ext) zip_path = "%s %s" % (zip_subdir, fname) zf.write(fpath, zip_path) zf.close() resp = HttpResponse(s.getvalue(), content_type="application/x-zip-compressed") resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp return Http404 here is my urls: from django.urls import path from . import views app_name = 'account' urlpatterns = [ path('login/', views.user_login, name='login'), path('signup/', views.user_signup, … -
DRF update the nested foreign key of an object
I am trying to wrap my head around this for too long already :( I need the following output for my frontend (specially the ID & name field in combination): { "serial": "e3461fb0", "shipment": { "id": 1, "name": "via rotterdam" } } model: class Shipment(models.Model): name = models.CharField("name", max_length = 128) date = models.DateField() class Product(models.Model): serial = models.CharField("serial", max_length = 31, unique = True) shipment = models.ForeignKey(Shipment, on_delete = models.CASCADE, blank = True, null = True) serializer: class ShipmentSerializer(serializers.ModelSerializer): class Meta: model = Shipment fields = ["pk", "name",] class ProductSerializer(serializers.ModelSerializer): shipment = ShipmentSerializer() def update(self, instance, validated_data): print("TEST:", instance, validated_data) return super().update(instance, validated_data) class Meta: model = Product fields = ["serial", "shipment",] lookup_field = "serial" read_only_fields = ["serial",] ViewSet: class ProductViewSet(ModelViewSet): serializer_class = ProductSerializer lookup_field = "serial" http_method_names = ["get", "patch", "put"] def get_queryset(self): return Product.objects.all() my problem here is the following: Lets say a product ist linked to a shipment and what I want now is to update that product by linking it to another shipment by using the id. But even in the HTML view of DRF I only get to see the name attribute of shipment. How can I only show/use the id here? I know … -
Change django-autocomplete-light html property
1st How do i change a default html property on django-autocomplete-light? 2nd How does django renders the html elements from a form widget? Hi there! I'm using django-autocomplete-light v3. 1st I will show you how to understand my problem 2nd I'going to ask you for any help Would you like to try django-autocomplete-light in less than a minute and help me? You may follow the steps from here: https://django-autocomplete-light.readthedocs.io/en/master/install.html Or just: pip install django-autocomplete-light Then, to let Django find the static files we need by adding to INSTALLED_APPS, before django.contrib.admin and grappelli if present: 'dal', 'dal_select2', # 'grappelli', 'django.contrib.admin', Install the demo project Install the demo project in a temporary virtualenv for testing purpose: cd /tmp virtualenv -p python3 dal_env source dal_env/bin/activate pip install django pip install -e git+https://github.com/yourlabs/django-autocomplete-light.git#egg=django-autocomplete-light cd dal_env/src/django-autocomplete-light/test_project/ pip install -r requirements.txt ./manage.py migrate ./manage.py createsuperuser ./manage.py runserver # go to http://localhost:8000/admin/ and login Now you are able to help!!! 1.1 Log in to your admin panel 1.2 scroll until you see "SELECT2_ONE_TO_ONE" and click 1.3 Add a new Tmodel clicking in the 'plus' button from the right 1.4 Go to the Inspection mode on you Browser (ctrl+shift+i)and click on any select field there i don't have … -
when i run the server , instead of the localhost:8000, i'm redirected to localhost:8000/app/
Page not found (404) “/home/sowou/Bureau/my_space/etude/IFNTI/stage/Django-CRM/app” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/app/ Raised by: django.views.static.serve Using the URLconf defined in crm.urls, Django tried these URL patterns, in this order: ^swagger(?P<format>\.json|\.yaml)$ [name='schema-json'] ^swagger/$ [name='schema-swagger-ui'] ^redoc/$ [name='schema-redoc'] api/ logout/ [name='logout'] ^(?P<path>.*)$ The current path, app/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
Stripe import could not be resolved. Django
As in title i can not import stripe to my django app. I get this message. I use virtual environment for this project if it changes anything. Import "stripe" could not be resolved from source(reportMissingModuleSource) -
Django on Heroku not uploading to S3
I'm working on a project using Django(3) in which I want to upload static files to S3 bucket using boto3 Here's setttings.py: if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' else: STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') django_on_heroku.settings(locals()) options = DATABASES['default'].get('OPTIONS', {}) options.pop('sslmode', None) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' My site is loading correctly and while deployment collectstatic copied all files to S3 bucket but now if I upload a file from django admin, its not uploading to S3 bucket, there's wasn't any mediafiles folder in the bucket, so I manually created that directly but files are not uploading there.