Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting failed to setup new system in my device
btw i am using windows :: (system used Django to build) when i try to run this command in my terminal ( pip install -r requirement.txt) it shows this error even i tried to install and update reportlab but still cant note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for reportlab Running setup.py clean for reportlab Failed to build reportlab ERROR: Could not build wheels for reportlab, which is required to install pyproject.toml-based projects -
how to prefetch comments in django
class Comment(models.Model): parent_comment=models.ForeignKey( to='self', related_name='_comments', on_delete=models.DO_NOTHING, null=True, blank=True, how to prefetch _comments: child_comment The deeper the depth, the deeper the N+1 query problem -
How can I resolve errors encountered during migration from SQLite to MySQL in Django?
(venv) PS E:\Easyalgo project\django-tailwind-blog> python manage.py migrate System check identified some issues: WARNINGS: ?: (ckeditor.W001) django-ckeditor bundles CKEditor 4.22.1 which isn't supported anmyore and which does have unfixed security issues, see for example https://ckeditor.com/cke4/release/CKEditor-4.24.0-LTS . You should consider strongly switching to a different editor (maybe CKEditor 5 respectively django-ckeditor-5 after checking whether the CKEditor 5 license terms work for you) or switch to the non-free CKEditor 4 LTS package. See https://ckeditor.com/ckeditor-4-support/ for more on this. (Note! This notice has been added by the django-ckeditor developers and we are not affiliated with CKSource and were not involved in the licensing change, so please refrain from complaining to us. Thanks.) ?: (urls.W002) Your URL pattern '/post' has a route beginning with a '/'. Remove this slash as it is unnecessary. If this pattern is targeted in an include(), ensure the include() pattern has a trailing '/'. Operations to perform: Apply all migrations: Adv_css, DBMS, admin, auth, blogs, contenttypes, cp_sheet, cs_subject, home, htmlapp, mini_sheet, networking, patterns, prepration_sheet, programming, sessions, stl Running migrations: Applying home.0003_blog_remark...Traceback (most recent call last): File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\Easyalgo project\django-tailwind-blog\venv\Lib\site-packages\MySQLdb\cursors.py", … -
how to upload and execute a file in django then show the result?
I want to build a web application using Django These are the flow I'm planning to execute: Page1 - User upload file to be executed using the upload button and then press execute button. Page2 - execute the Python code and show the result. i have tried the upload part but i still need help in the execution and the show of the result . -
Django Allauth Bad Request Error, Error Retrieving Access Token: Invalid Grant
I am using Django Allauth from PyPi in a Django project to authenticate users so they can upload YouTube videos. The way I do this is with a button on the login page that should collect tokens from Google to upload the videos. I am able to send the user to Google for authentication, but I get an error in the Allauth view when the user is returned to the website. {'provider': 'google', 'code': 'unknown', 'exception': OAuth2Error('Error retrieving access token: b\'{\\n "error": "invalid_grant",\\n "error_description": "Bad Request"\\n}\'')} Any idea how to fix this? I have used django-allauth before without any trouble. For reference, the full source code I am using to produce this error is on my github at https://github.com/daisycamber/femmebabe-2024. Thank you for your help. -
How to query child models from parent model data?
I currently have a set of models like so: class BaseModel(models.Model): approved = models.BooleanField() class ModelA(BaseModel): # model fields class ModelB(BaseModel): # models fields class ModelC(BaseModel): # model fields What I'd like to do is get a list of all instances of ModelA, ModelB, and ModelC with approved=True. I can query BaseModel with a queryset: BaseModel.objects.filter(approved=True) but this returns all instances of BaseModel, not ModelA, ModelB, or ModelC. I'd like my queryset to contain instances of each model -- preferably without exhaustively querying every single possible child model of BaseModel. Is there a way to do this? -
[[Errno 2]] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in my Django project
I've been moving development of my website over to using Docker. I recently adjusted the location of media files when I was presented with this error: [Errno 2] No such file or directory: '/tmp/tmp1d93dhp7.upload.mp4' in Django. So far I've checked for typos in my file location code in my settings, views and models. The website works by simply storing user uploaded media files in a media folder. Uploaded files are stored in media/human. Here is the relevant code: views.py: ... fs = FileSystemStorage() filename = fs.save(uploaded_file.name, uploaded_file) uploaded_file_path = fs.path(filename) file_type = mimetypes.guess_type(uploaded_file_path) request.session['uploaded_file_path'] = uploaded_file_path user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) files = request.FILES.getlist('file') for file in files: user_doc, created = RequirementsChat.objects.get_or_create(id=user_id) uploaded_file = UploadedFile(input_file=file, requirements_chat=user_doc, chat_id = user_id) uploaded_file.save() user_doc.save() ... The error seems to be caused by the uploaded_file.save() line. models.py: class RequirementsChat(models.Model): id = models.CharField(primary_key=True, max_length=40) alias = models.CharField(max_length=20, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) language = models.CharField(max_length=10, blank=True, null=True) due_date = models.CharField(max_length=10, blank=True, null=True) subtitle_type = models.CharField(max_length=10, blank=True, null=True) transcript_file_type = models.CharField(max_length=10, blank=True, null=True) additional_requirements = models.TextField(max_length=500, blank=True, null=True) date = models.DateTimeField(auto_now_add=True, blank=True, null=True) url = models.CharField(max_length=250, blank=True, null=True) task_completed = models.BooleanField(default=False) class UploadedFile(models.Model): input_file = models.FileField(upload_to='human_upload/')#new chat_id = models.CharField(max_length=40, null= True) requirements_chat = models.ForeignKey(RequirementsChat, on_delete=models.CASCADE, … -
Sending parts of react components from django server to be rendered in a react client server
I have a unique problem statement. I have a client side react server running on port 3000 and a django server of port 8000. Both the servers communicate through rest framework. But I have a situation where I cannot keep the UI code of react in the react frontend so I should send the react(html) code from the django backend(security reasons) so that I could only load that secure UI react component when I receive the html(react compiled) code from the django server(backend). I think we can use some way to compile the react code from an additional node.js server into html code and keep it in django server. When user with right permissions try to access that component only then the server send the react UI code to the frontend to temporarily display that component in the frontend. Can I know how this can be achieved if it cam be achieved. Feel free to ask any additional questions you have regarding the problem statement in the comments. -
How to create model instances from html form and save to AuraDb?
Most of the online tutorials and videos describe how to create and save model instances to the local database using Django. I found this medium article https://medium.com/swlh/create-rest-api-with-django-and-neo4j-database-using-django-nemodel-1290da717df9 explaining how to upload it to Neo4j. I tried to run the same project and this is what I got when I went to http://127.0.0.1:8000/person (see snapshot below). The "Person" object is a StructuredNode, defined as follows in models/person.py: from neomodel import StructuredNode, StringProperty, IntegerProperty,UniqueIdProperty, RelationshipTo from myapi.models.city import City class Person(StructuredNode): uid = UniqueIdProperty() name = StringProperty(unique_index=False) age = IntegerProperty(index=True, default=0) email = StringProperty(unique_index=True) # Relations : city = RelationshipTo(City, 'LIVES_IN') friends = RelationshipTo('Person','FRIEND') def __unicode__(self): return self.uid I want to get the details from a user through a form and save it as an instance of the Person object in my AuraDB: person.save() So in `views/forms.py' I created a form as such: from django import forms from splitjson.widgets import SplitJSONWidget from myapi.models import Person class testForm(forms.Form): attrs = {'class': 'special', 'size': '40'} data = forms.CharField(widget=SplitJSONWidget(attrs=attrs, debug=True)) class Meta: model = Person and I added it as a path to the urls.py: from django.urls import re_path as url from myapi.views import * from django.urls import path urlpatterns = [ path('', home, name='home'), … -
JS script is not included in Django project
I'm learning django and have a problem. JS script is not included in Django project. The path is correct, the page itself with the graph block works, but the output of a round or bar chart does not occur. index.html {% extends 'partials/base.html' %} {% block title %}Home Page{% endblock %} {% block content %} <div class="row "> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart1" width="400" height="300"></canvas> <script src="{% static 'main.js' %}"></script> </div> </div> </div> <div class="col-md-6 my-4"> <div class="bg-white"> <div class="card-body"> <canvas id="myChart" width="400" height="300"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for order in order %} '{{order.name}}',{% endfor %}], datasets: [{ label: 'Orders', data: [{% for order in order %} {{ order.order_quantity }}, {% endfor %}], backgroundColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] … -
Django doesn't override base admin template
I'm trying to add small customizations to my Django admin panel such as a favicon. I followed the official guide and have created a base_site.htmlfile in app/templates/admin/. base_site.html {% extends "admin/base_site.html" %} {% load static %} {% block branding %} <img src="{% static 'portal/img/favicon.png' %}" alt="Favicon"> {{ block.super }} {% endblock %} It seems like the template isn't being overridden at all as I don't see an error for not being able to find the favicon / incorrect src (works fine on other pages). urls.py from django.contrib import admin from django.urls import path, include from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.sitemaps.views import sitemap from bmlabs.sitemaps import StaticViewSitemap from .views import robots sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ path('admin/', admin.site.urls, name="admin"), ] urlpatterns += staticfiles_urlpatterns() -
Can i run 2 django projects on 2 domains but on 1 ip?
I'm trying to run two django projects using nginx using these two configurations: upstream django { server unix:///home/hypebeeruser/HypeBeer/HypeBeerProject/HypeBeerProject.sock; } # configuration of the server server { server_name hypebeer.com.ua; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/media; } location /static { alias /home/hypebeeruser/HypeBeer/HypeBeerProject/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/hypebeeruser/HypeBeer/HypeBeerProject/uwsgi_params; } } # the upstream component nginx needs to connect to upstream django_tobabox { server unix:///home/tobabox/TobaBox/TobaBox/TobaBox.sock; } # configuration of the server server { listen 80; server_name tobabox.com www.tobabox.com; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/tobabox/TobaBox/TobaBox/media; } location /static { alias /home/tobabox/TobaBox/TobaBox/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django_tobabox; include /home/tobabox/TobaBox/TobaBox/uwsgi_params; } } I run uwsgi --socket HypeBeerProject.sock --module HypeBeerProject.wsgi --chmod-socket=666 and it runs my first site, but the second doesn't work with the same comand (yes, i changed the names of .sock and project.wsgi). It runs normally without any errors, but i still can't connect via domain name. Do I need to buy an additional IP or can I … -
Filter in Django Admin via a ManyToMany field with Through
My models.py: class Subject(models.Model): name = models.CharField(max_length=200) class Person(models.Model): subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) class PersonRole(models.Model): project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) Now, in my admin back-end I'd like to add a nice filtering with list_filter. This filter should make it possible to filter by the schools that a person is attached to a project. In other words, if John (belonging to school 'no. 1') is attached to project no. 3, I'd like the projects table on the backend to show only project no. 3. I suppose I should customise a simplelistfilter. First of all, though, I'm a bit stuck as to how to get the list of schools attached to the persons attached to a project. My attempt so far is: class PersonRole(models.Model): [...] def get_school(self): return self.person.school class Project(models.Model): @admin.display(description='PI School') def get_PI_school(self): return [p for p in self.person.get_school()] admin.py: class ProjectAdmin(admin.ModelAdmin): list_display = ("get_PI_school",) #This is just to see if the field is populated With this, I get 'ManyRelatedManager' object has no attribute 'get_school'. -
create django models using HTML form
i am working with django and trying to build a web app builder with pure django and grapesjs and django-tenant. i am wondering how to let the customer create his own database models separate from other customers and link these fields with django model in grapesjs. Models.py """" """" -
How to create pdf with multiple pages based on html using python pdfkit
I am trying to create a pdf with python using pdfkit library in my Django project, and I want to separate each content in a different page, how can I do it import pdfkit from django.template.loader import render_to_string my_contents = [ {'title':'Example 1', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 2', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 3', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 4', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']}, {'title':'Example 5', 'contents': ['Lorem ipsum dorer', 'Lorem ipsum']} ] final_html = '' for content in my_contents: data = { 'title': content['title'], 'contents': content['contents'], } final_html += render_to_string( 'pdfs/routines_handout.html', data) my_pdf = pdfkit.from_string(final_html, 'out.pdf') -
login with superuser not working in django admin panel
I was writing code, everything worked fine, all services were running via docker-compose, then the database crashed, I had to clean up the database files and recreate them using the same docker-compose. This time, I tried to create an admin user using python manage.py createsuperuser, I created it, but I can't authenticate with it in django/admin. Settings: from pathlib import Path import environ import os env = environ.Env(DEBUG=(bool, False)) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' environ.Env.read_env(os.path.join(BASE_DIR, '.env')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') ALLOWED_HOSTS = [] INTERNAL_IPS = [ "127.0.0.1", ] AUTH_USER_MODEL = 'codenest.User' TAILWIND_APP_NAME = 'theme' # AUTHENTICATION_BACKENDS = [ # 'django.contrib.auth.backends.RemoteUserBackend', # 'django.contrib.auth.backends.ModelBackend', # ] SITE_ID = 1 INSTALLED_APPS = [ 'codenest.apps.CodenestConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'tailwind', 'theme', 'django_browser_reload', ] 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.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_browser_reload.middleware.BrowserReloadMiddleware', ] ROOT_URLCONF = 'learning_system.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { … -
Django Pytests in docker container not using temp sqlite3 database
I'm running pytest on a django app that lives in a docker container. Pytest is being run in the docker container after it's built. Normally the django app references a mysql container running on the same host. I've been trying to use a sqlite3 db instead for testing, but I've been having trouble getting it to use this instead of the mysql container. I've gotten it to work one way: test_settings.py: from .settings import * # Override the DATABASES setting to use SQLite for tests DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } pyproject.toml: [tool.pytest.ini_options] testpaths = ["tests"] addopts = [ "--ds=django_app.test_settings", ] [tool.pytest.ini_options.env] PYTHONPATH = "web" I don't want to do it this way because of the wildcard import (also my ruff linter doesn't like). I've tried to overwrite using conftest.py, but it seems to get overwritten again by the DJANGO_SETTINGS_MODULE env variable, which is set in the container's env file. How can I get my pytest to use sqlite3 without using this wildcard import on test_settings.py? Or without using test_settings.py at all? Thanks -
What are the best practices regarding SSR, Django and temprarly changed data?
I'm currently building a Django app using htmx. It's something like a journal with multiple entries per day. When a user changes one entry or adds another I don't want to store the data just yet in case the user cancels the input. This is no problem for a single change but when there are multiple changes it gets overly complicated because the current state is only correctly represented on the website and not in the DB object anymore. What would be the best practice to handle this problem? I'm using function based views, not classes. I'm thinking about adding a temporary object table where a copy of my journal week/days is added and changed and gets deleted after the user saves the real object. Is there a better way to do it? -
How to use SQL Alchemy models the same way than django models
I have been using fast api for a few days and passing the db session around is starting to bother me a bit. In my previous project I was using a django backend, where to make queries I only needed to import the model. Something like: from models import SomeModel class SomeRepository: def method(self): SomeModel.objects.filter(...) But in fast api, I need to take care of the db session object and pass it as argument, something like: from sqlalchemy.orm import Session from models import SomeModel class SomeRepository: def method(self, db: Session): db.query(SomeModel).all() Is there any way to make fast api and sql alchemy work like the way models work in Django? -
Authorization error with Django on Windows with IIS
Dear Django and Windows IIS experts, I am a medical physicist, trying to help a colleague set up a new installation of OpenREM version 1.0.0b2, an open source patient radiation dose management system (openrem.org). We have been following the documentation here: https://docs.openrem.org/en/1.0.0b2/install_windows.html. The system is running on Windows Server 2016 Datacenter. The OpenREM installation works perfectly when run using Django's built-in "python.exe manage.py runserver" command. However, it needs to be configured to run via Microsoft's IIS, and we cannot get this to work. There is an "Authorization" problem reported when I run "Test Settings" from the "Basic Settings" dialogue box in IIS: We have tried giving the OpenREM application pool read access to the site, but this did not work. Can any of you offer some help or advice with this? I have a fully-working Windows server installation of OpenREM 1.0.0b2 at my workplace, so have some experience of installing and configuring the system, but IIS on my colleague's server has me stumped. Many thanks in advance for any help you can offer. Kind regards, David -
Django socialaccount login with email instead of username
I am trying to implement google login in my Django app. In my standart class-based login view I am using the extended AbstractBaseUser model and it works fine: class AppUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' objects = CustomUserManager() def get_by_natural_key(self, email): return self.get(email=email) def set_password(self, raw_password): self.password = make_password(raw_password) In my settings.py I've added these: INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ... ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email' ], 'AUTH_PARAMS': { 'access_type': 'online', } } } ... AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_PASSWORD_MIN_LENGTH = 8 SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' AUTH_USER_MODEL = "profiles.AppUser" This is the error message i received: FieldDoesNotExist at /accounts/google/login/callback/ AppUser has no field named 'username' ...Python\Python39\lib\site-packages\django\db\models\options.py, line 681, in get_field return self.fields_map[field_name] … Local vars During handling of the above exception ('username'), another exception occurred: ...Python\Python39\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars ...Python\Python39\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars ...Python\Python39\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 87, in view return self.dispatch(request, *args, **kwargs) … Local vars ...Python\Python39\lib\site-packages\allauth\socialaccount\providers\oauth2\views.py, line 171, … -
Display a filtered result from ManyToMany through model in Admin
This is my models.py: class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return '{}, {}'.format(self.surname, self.forename) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [etc...] ] title = models.CharField(choices=TITLE_CHOICES, max_length=9) project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) def __str__(self): return '{}: {} as {}.'.format(self.project, self.person, self.person_role) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) def __str__(self): return self.title def get_PI(self, obj): return [p.person for p in self.person.all()] #I'll then need to filter where person_role is 'Principal investigator', which should be the easy bit. In my Admin back-end I'd like to display the person (principal investigator) in the main table: class ProjectAdmin(ImportExportModelAdmin): list_filter = [PersonFilter, FunderFilter] list_display = ("title", "get_PI") ordering = ('title',) You can see that I created my get_PI() in my models.py and references in my list_display. I'm getting Project.get_PI() missing 1 required positional argument: 'obj'. What am I doing wrong? -
migrate from django migrations to fastapi alembic
I had a Django service which had an app called "User". This app has 2 tables in, which are being migrated to the database using Django migration system. In order to change the architecture from monolith to micro-service, I broke down User app and add the models and APIs in another Fastapi project. But I didn't separate the database and during this time, I was changing User tables in database using my previous Django project migration system. But now I want to break down tables in the database and move them to the new database. What is the best practices of doing this? And how can I change migrations from Django to alembic? -
getting "Failed to create meeting error 401 Client Error: Unauthorized for url: https://api.zoom.us/v2/users/me/meetings"
I have added the client id and secrete key and if i am autharizing the app from postman its working but as soon as i tried to ping the api with my app it giving 401 error. how can i authorize my app into zoom app and can create meeting with dynamic token authrization_url = 'https://zoom.us/oauth/authorize' authrization_params = { 'client_id': zoom_client_key, 'response_type': 'code', 'redirect_uri': 'https://gensproject.supporthives.com/zoom', } auth_response = requests.post(authrization_url, data=authrization_params) if auth_response: # Obtain a new access token access_token_url = 'https://zoom.us/oauth/token' access_token_params = { 'grant_type': 'client_credentials', 'client_id': zoom_client_key, 'client_secret': zoom_client_secret, } try: response = requests.post(access_token_url, data=access_token_params) response.raise_for_status() access_token = response.json().get('access_token', '') except requests.RequestException as e: return Response({'message': 'Failed to obtain access token', 'error': str(e)}, status=500) # Create a Zoom meeting # user_id = "ops@supporthives.com" # create_meeting_url = f"https://api.zoom.us/v2/users/{user_id}/meetings" "https://zoom.us/oauth/authorize?client_id=MeGkVnUrQGG15c7ESPP1ZA&response_type=code&redirect_uri=https%3A%2F%2Fgensproject.supporthives.com%2Fzoom" create_meeting_url = 'https://api.zoom.us/v2/users/me/meetings' create_meeting_headers = { 'Authorization': f'Bearer {access_token}', # 'Authorization': f'Bearer eyJzdiI6IjAwMDAwMSIsImFsZyI6IkhTNTEyIiwidiI6IjIuMCIsImtpZCI6IjQ0NTYzNTg5LTA0YzAtNDY1ZC05NjBhLTljM2Y4YmI1ZjRmMyJ9.eyJ2ZXIiOjksImF1aWQiOiJiOTg4ZGQ4ZGNiYmQ0NTcyMjM0OWU4ZWE1ZGQ5NTVkMCIsImNvZGUiOiJ6V0tvUWhBREtuQWRHdVVuRkt5Uk15WXF2TjBYaXpDa0EiLCJpc3MiOiJ6bTpjaWQ6TWVHa1ZuVXJRR0cxNWM3RVNQUDFaQSIsImdubyI6MCwidHlwZSI6MCwidGlkIjowLCJhdWQiOiJodHRwczovL29hdXRoLnpvb20udXMiLCJ1aWQiOiI3RkRIdW16TFNMZW5xUVk0cDRFNDRnIiwibmJmIjoxNzExNDUyMTk0LCJleHAiOjE3MTE0NTU3OTQsImlhdCI6MTcxMTQ1MjE5NCwiYWlkIjoiMVpmNnBDYkRROHF2emU1RFB0VnQ0USJ9.2oTMkSwL0OrnOAswTJoscy8zOSJhVmplTHsE6gh3H5-z_7sznAanBF2XyL3wO9FLGpggsFSqWxB04MXQof7YDw', 'Content-Type': 'application/json', } event_datetime = datetime.combine(event.event_date, datetime.min.time()) start_time_utc = mktime(event_datetime.utctimetuple()) create_meeting_params = { 'topic': event.event_title, 'type': 2, # Scheduled meeting 'start_time': f'{start_time_utc}000', 'duration': 60, 'timezone': 'UTC', 'description': event.event_description, 'settings': { 'host_video': True, 'participant_video': True, 'waiting_room': False, 'join_before_host': True, 'mute_upon_entry': False, 'auto_recording': 'none', }, } try: create_meeting_response = requests.post(create_meeting_url, headers=create_meeting_headers, json=create_meeting_params) create_meeting_response.raise_for_status() meeting_link = create_meeting_response.json().get('join_url', '') event.event_link = meeting_link … -
My image show not found error but the link in terminal is able to locate the file
My image can't be load on page, the feedback shows Not Found: /auctions/static/auctions/images/Artboard_1_copy.png "GET /auctions/static/auctions/images/Artboard_1_copy.png HTTP/1.1" 404 3417 but when I ctrl and click on the link in feedback, I was able to open my image in my workspace. This is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'auctions', '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 = 'commerce.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 = 'commerce.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_USER_MODEL = 'auctions.User' # Password validation # https://docs.djangoproject.com/en/3.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 # …