Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 bad gateway with nginx and gunicorn
502 Bad Gateway nginx/1.19.5 reinstall portainer and recreate docker images to solve this isssue, but didnt work. how can i solve this issue? i think something's wrong before collectstatic because if this issue was about collectstatic, webpage have been deployed with static files not applied. gunicorn container logs 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. 0 static files copied to '/home/loldb/staticfiles', 147 unmodified. Operations to perform: Apply all migrations: accountapp, admin, articleapp, auth, commentapp, contenttypes, profileapp, projectapp, sessions, subscribeapp Running migrations: No migrations to apply. nginx logs /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ /docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh 10-listen-on-ipv6-by-default.sh: Getting the checksum of /etc/nginx/conf.d/default.conf 10-listen-on-ipv6-by-default.sh: Enabled listen on … -
how to test if deleted post has been removed from blog
as I'm new in Django I've tried to write a simple program for blog posts to add, update and delete a post. Now I want to test if my deleted post has been removed from my blog list by assertNotContains code and I got an assertion error. I added part of my code related to my question please feel free for more information. thanks in advance. views.py def post_delete(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': post.delete() return redirect('blog_list') return render(request,"blog/post_delete.html",{"post":post}) urls.py urlpatterns=[ path("",views.blog_list,name="blog_list"), path("<int:pk>/",views.post_details,name="post_detail"), path("create/",views.create_new_post,name="post_create"), path('<int:pk>/update/', views.post_update ,name='post_update'), path('<int:pk>/delete/', views.post_delete , name='post_delete'), ] models.py class Post(models.Model): STATUS_CHOICES=( ('pub','published'), ('drf','draft'), ) title=models.CharField(max_length=100) text=models.TextField() status=models.CharField(max_length=3,choices=STATUS_CHOICES) created_datetime=models.DateTimeField(auto_now_add=True) modified_datetime=models.DateTimeField(auto_now=True) author=models.ForeignKey(User, on_delete=models.CASCADE) test.py class TestBlogPost(TestCase): @classmethod def setUpTestData(cls): cls.user=User.objects.create(username="user1") cls.post1=Post.objects.create( title="post1", text="this is post1", status=Post.STATUS_CHOICES[1][0], author=cls.user ) def test_delete_post_view_url(self): response = self.client.post(reverse("post_delete",args=[self.post1.id])) self.assertEqual(response.status_code,302) ** self.assertNotContains(response, self.post1.title) ** **error I got: AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) ** -
Django - How to prevent Custom Field Validator from executing unless the field has changed?
I have a custom validator that checks that the size of the uploaded gallery image is not too big. This validator runs every time the model is saved no matter if the field has changed or not. This usually wouldn't be a big issue. The problem is that I have an admin panel inline, and any time I save the parent model "Profile" the validation inside of all the children "GalleryImages" gets executed. The validation of 50 images takes a long time since it needs to load all images and check for the resolution. How can I configure this validator to only run if the field value has been updated? # models.py @deconstructible class ImageValidator(object): """ Checks that image specs are valid """ def call(self, value): # Some code to check for max size, width and height if too_big: ValidationError('Image is too big') class Profile(Model): user = models.ForeignKey(User) class GalleryImage(Model): profile = models.ForeignKey(Profile) image = models.ImageField(validators=[ImageValidator]) # admin.py class GalleryImageInline(admin.TabularInline): model = GalleryImage @admin.register(Profile) class ProfileAdmin(ModelAdmin): inlines = [GalleryImage] -
Need Help Troubleshooting Django Registration Error
I'm encountering an issue with the registration functionality in my Django project. When I attempt to register a new user, I receive a generic error message, "There was an error, please try again," instead of a successful registration confirmation. Here is my project view.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request, ("You Have Been Logged In!")) return redirect('home') else: messages.success(request, ("There was an error, please try again")) return redirect('login') else: return render(request, 'login.html', {}) def logout_user(request): logout(request) messages.success(request, ("You have been logged out")) return redirect('home') pages navbar.html {% if user.is_authenticated %} <li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Logout</a></li> {% else %} <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li> {% endif %} pages urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('login/', views.login_user, name='login'), path('logout/', views.logout_user, name='logout'), ] -
Understanding django.db.utils.OperationalError: connection is bad: nodename nor servname provided, or not known error
I am attempting to create a Django website with a Postgress database. When I run python manage.py runserver command to start up the website I get the following error message. Traceback Error Message Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/backends/base/base.py", line 275, in ensure_connection self.connect() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/psycopg/connection.py", line 750, in connect raise last_ex.with_traceback(None) psycopg.OperationalError: connection is bad: nodename nor servname provided, or not known The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/recorder.py", line 63, … -
Add icon to django-admin's navbar
I want add icon for every app and models, How should i do? and how change the default app name for django-admin. I using tailwindcss and daisyUI and fontawesome for custom -
Dynamically Create and Use Django Database Connections for Each School Without Server Restart
I am developing a Django application where schools can register, and each school has its own database. However, I am facing an issue: after creating a new database for a school, the Django server needs to be restarted for the new database to be recognized. I want to dynamically create database connections for each school without having to restart the Django server. I've tried various approaches, including creating dynamic connections using django.db.connections, but it doesn't seem to work as expected. Is there a solution or recommended approach to allow Django to dynamically create and use database connections for each new school without requiring a server restart? Thanks in advance for any help or suggestions! ConnectionDoesNotExist at /inscription/ecole/ The connection 'school_db_belle_rose' doesn't exist. Request Method: POST Request URL: http://127.0.0.1:8000/inscription/ecole/ Django Version: 5.0 Exception Type: ConnectionDoesNotExist Exception Value: The connection 'school_db_belle_rose' doesn't exist. Exception Location: C:\Users\Ppang\Desktop\project_procode\ConnectEdu\venv\Lib\site-packages\django\utils\connection.py, line 61, in getitem Raised during: comptes_ecole.views.InscriptionEcole Python Executable: C:\Users\Ppang\Desktop\project_procode\ConnectEdu\venv\Scripts\python.exe Python Version: 3.11.0 Python Path: ['C:\Users\Ppang\Desktop\project_procode\ConnectEdu\back-end', 'C:\Python311\python311.zip', 'C:\Python311\DLLs', 'C:\Python311\Lib', 'C:\Python311', 'C:\Users\Ppang\Desktop\project_procode\ConnectEdu\venv', 'C:\Users\Ppang\Desktop\project_procode\ConnectEdu\venv\Lib\site-packages'] Server time: Mon, 08 Jan 2024 02:22:52 +0000 -
AttributeError when using TfidfVectorizer in a SKLearn pipeline
I have the following code to combine the results of an NLP model and a quantitative model with a StackingClassifier: # Feature Selection pipelines NLP_COLS = ['processed_text'] KNN_COLS = ['retweet_count', 'favorite_count', 'num_hashtags', 'num_urls'] tfidf_vectorizer = TfidfVectorizer() combined_tweet_df['processed_text'] = combined_tweet_df['processed_text'].astype(str) pipe_nlp = Pipeline([ ('select', ColumnTransformer([('sel', 'passthrough', NLP_COLS)])), ('tfidf', tfidf_vectorizer), ('clf', nlp_model) ]) pipe_knn = Pipeline([ ('select', ColumnTransformer([('sel', 'passthrough', KNN_COLS)])), ('clf', knn_model) ]) # stacking ensemble stacking_model = StackingClassifier( estimators=[ ('nlp', pipe_nlp), ('knn', pipe_knn) ], final_estimator=DecisionTreeClassifier(), cv=5 ) # train test split x_train, x_test = train_test_split( combined_tweet_df[['processed_text', 'retweet_count', 'favorite_count', 'num_hashtags', 'num_urls']], test_size=0.25, random_state=4 ) y_train, y_test = train_test_split(combined_tweet_df['type'], test_size=0.25, random_state=4) stacking_model.fit(x_train, y_train) However, at the stacking_model.fit I run into the following error: AttributeError: 'numpy.ndarray' object has no attribute 'lower' How can I fix this? -
Database config for Django and SQL Server - escaping the host
I have setup my Django app to use Microsoft SQL Server database. This is my database config. DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': "reporting", 'HOST': '192.168.192.225\SQL2022;', 'PORT': 1433, 'USER': "sa", 'PASSWORD': "Root_1421", 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } The SQL Server database is installed on my desktop machine and DESKTOP-RC52TD0\SQL2022 is the host\instance name. When print my config, I get the following. {'default': {'ENGINE': 'mssql', 'NAME': 'reporting', 'HOST': 'DESKTOP-RC52TD0\\SQL2022', 'USER': 'sa', 'PASSWORD': 'Root_1421', 'OPTIONS': {'driver': 'ODBC Driver 17 for SQL Server'}}} Notice that in HOST, the value has two slashes added to it, which is causing my app to not be able to connect to the database. I believe this is because of Python escaping feature for strings. How do can I escape so that I end up with a single slash and not double? As I am getting the following error: django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') I've tried the following and still same result: r'DESKTOP-RC52TD0\SQL2022' 'DESKTOP-RC52TD0\\SQL2022' r'DESKTOP-RC52TD0\SQL2022' Any ideas how I can escape in the context of a dictionary. In a string adding double slash \\ works but not when used in a … -
FirstValue and NthValue Django window function not working as expected
I have the following query grouped_data = ( Notification.objects .filter(type=2, user=18, is_removed=False) .values('question') .annotate( total_likes=Count('user'), most_recent_at=Max('created_at'), is_read=Min('is_read'), first_actor=Window(expression=FirstValue('actor_id'), order_by=F('id').desc(), partition_by=['question_id']), second_actor=Window(expression=NthValue('actor_id', 2), order_by=F('id').desc(),partition_by=['question_id']), ).order_by('-total_likes') ) Here's my Notification model: class Notification(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='actors') actor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users') question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=True, null=True) comment = models.ForeignKey(Comment, on_delete=models.CASCADE, blank=True, null=True) type = models.ForeignKey(NotifType, on_delete=models.CASCADE) is_read = models.BooleanField(default=False) is_removed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) For some reason, second_actor is always None and the first_actor is always the very first actor id and not the latest actors. For example, if I have: id actor_id 20 10 19 21 18 3 I'd expect first_actor to be 10 and second_actor to be 21. What I get is first_actor as 3 and second_actor as None. Why is this happening? My underlying database is MySQL...when I do a raw query in MySQL I get the correct result. -
CSS doesn't load when deploying Django on Railway, because MIME type ('text/html') is not a supported stylesheet MIME type
I've completed the CS50W project 1 wiki project. Though not part of the assignment, I would like to host it online so that I can show it to my friend. The deployment to Railway is a success but when I view the page, the CSS doesn't load. You can view my website here: https://web-production-40b27.up.railway.app/ The error message I got is this: I think it has something to do with the static files path. Can someone help me? DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT =os.path.join(BASE_DIR, 'staticfiles') Here's a breakdown of my directory tree: wiki └── wiki ├── db.sqlite3 ├── encyclopedia │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ ├── __init__.py │ │ └── __pycache__ │ │ └── __init__.cpython-312.pyc │ ├── models.py │ ├── static │ │ └── encyclopedia │ │ └── styles.css │ ├── templates │ │ └── encyclopedia │ │ ├── create.html │ │ ├── edit.html │ │ ├── entry_page.html │ │ ├── error.html │ │ ├── index.html │ │ ├── layout.html │ │ └── search.html │ ├── tests.py │ ├── urls.py │ ├── util.py │ ├── views.py │ ├── __init__.py │ └── __pycache__ │ ├── admin.cpython-312.pyc │ ├── … -
django module not found, cyclic.sh
I tried to deploy my django app on cyclic.sh, i have the requirements.txt file in the root, and according to the logs, it is in fact downloading them on the server. but when i try to access the page, i get an error saying module not found 'django'. Initial logs: 2024-01-07T23:37:49.675Z: Setting environment variables: CYCLIC_URL="http****************" CYCLIC_DB="lazy****************" CYCLIC_BUCKET_NAME="cycl****************" DJANGO_SETTINGS_MODULE="serv****************" REACT_APP_API_URL="********************" CYCLIC_APP_ID="lazy****************" 2024-01-07T23:37:49.051Z: [CYCLIC] cloning... 2024-01-07T23:37:50.334Z: From https://github.com/AnshUjlayan/CourseOverflow * branch 7fd1626cd9c8a1595531ba8851d0b94a56977fee -> FETCH_HEAD 2024-01-07T23:37:50.394Z: HEAD is now at 7fd1626 idek 2024-01-07T23:37:50.399Z: [CYCLIC] Building... 2024-01-07T23:37:50.601Z: Build Configuration: Root Path: /server Output Path: /server Main file: server/wsgi.py Static Site: false Runtime: python3.11 Branch: deployment Ref: 7fd1626cd9c8a1595531ba8851d0b94a56977fee 2024-01-07T23:37:50.604Z: [CYCLIC] verifying... 2024-01-07T23:37:51.346Z: [CYCLIC] using: python:3.11.2 pip:22.3.1 runtime:python3.11 [CYCLIC] building from: /server 2024-01-07T23:37:51.347Z: [CYCLIC] installing dependencies from /server/requirements.txt into /server 2024-01-07T23:38:02.767Z: [CYCLIC] bundling /server... 2024-01-07T23:38:07.459Z: [CYCLIC] packaging 166.65 MB... 2024-01-07T23:38:07.459Z: [CYCLIC] done packaging 2024-01-07T23:38:07.459Z: [CYCLIC] Deploying... 2024-01-07T23:38:21.846Z: deployed eu-west-1 - 14.337s 2024-01-07T23:38:21.847Z: SUCCESS took 34.5 seconds api deployed at: https://lazy-gray-lizard-belt.cyclic.app the logs when i try to access the page: 05:13:04.828 Traceback (most recent call last): File "/var/task/server/wsgi.py", line 11, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [CYCLIC] ERROR: No response from server on port 3000 this is my file structure: - server - … -
i have the problem to import dash to html
def dashboard_view(request): clients = Client.objects.values('nom', 'tot_presta') data = Data.objects.values('client', 'tot_net') rdv = RDV.objects.values('client', 'item') df_clients = pd.DataFrame(list(clients)) df_data = pd.DataFrame(list(data)) df_rdv = pd.DataFrame(list(rdv)) ventes_par_client = df_data.groupby('client')['tot_net'].sum().reset_index() ca_par_technicien = df_rdv.groupby('client')['item'].sum().reset_index() fig_ventes_clients = px.bar(ventes_par_client, x='client', y='tot_net', title='Ventes par Client') fig_ca_techniciens = px.bar(ca_par_technicien, x='client', y='item', title="Chiffre d'affaires par Technicien") app = DjangoDash('dashboard_app') app.layout = html.Div([ html.H1(children='Analyse des Ventes'), dcc.Graph( id='ventes-clients', figure=fig_ventes_clients ), dcc.Graph( id='ca-techniciens', figure=fig_ca_techniciens ) ]) dash_content = app.index() context = {'dash_content': dash_content} return render(request, 'ManagerSalon360/dashboard.html', context) i received this error to my terminal Internal Server Error: /ManagerSalon360/dashboard/ Traceback (most recent call last): File "D:\MonLogiciel\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\MonLogiciel\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\MonLogiciel\ManagerSalon360\views.py", line 263, in dashboard_view dash_content = app.index() AttributeError: 'DjangoDash' object has no attribute 'index' [07/Jan/2024 22:35:20] "GET /ManagerSalon360/dashboard/ HTTP/1.1" 500 78946 i using dash==2.9.3 dash-bootstrap-components==0.13.1 dash-core-components==2.0.0 dash-html-components==2.0.0 dash-renderer==1.3.0 dash-table==5.0.0 distlib==0.3.8 Django==3.2.23 django-asset-definitions==1.0.0 django-bootstrap4==23.4 django-cors-headers==4.3.1 django-dashboards==0.1.7 django-extensions==3.2.3 django-plotly-dash==2.2.2 django-redis==5.4.0 dpd-components==0.1.0 dpd-static-support==0.0.5 -
How to save each instance from a patch request in Djanog
In my Django appliations, I have four models, Exercise, Workout, Target, and TargetExerciseSet. Here are the models below along with my current Workout View and patch request function. The patch request is only done when a workout is completed. I have created a new model, Log (also shown below), to store each instance of a workout. My current problem here is that Object { error: "Object of type ImageFieldFile is not JSON serializable" } workout.component.ts:359:16. I have tried to workout with ChatGPT, and they are suggesting to create new tables for completed workouts, but this wont work because the database is only so big. So my question, each time a workout is completed, what would be the best way to save this data? I have tried just trying to save the exercise name and image in a json, but by time I try to view the data on my frontend application, the image url is expired. I know I can just save the exercise id, then do a request to get the exercises by ID, but I don't want to keep calling to the backend. (I know I can do one request with all the exercises). Any help will be … -
Why is Django not redirecting to url compare files?
I am uploading two files, then comparing them with xxhash algorithm and return same if they are same or different otherwise, however when submitting the form containing the files it is not redirecting it to the function in views that does the magic, and it is giving me error 404: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post?file1=f.txt&file2=t.txt Using the URLconf defined in hashhosh.urls, Django tried these URL patterns, in this order: admin/ [name='home'] login/ [name='login'] compare-files/ [name='compare-files'] The current path, post, didn’t match any of these why is that happening? urls.py: from django.contrib import admin from django.urls import path from django.contrib.auth.views import LoginView from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home_view, name='home'), path('login/', LoginView.as_view(template_name='login.html'), name='login'), path('compare-files/', views.compare_files_view, name='compare-files'), # Update the URL pattern ] views.py: from django.contrib.auth.views import LoginView from django.shortcuts import render import xxhash from django.http import HttpResponse def home_view(request): return render(request, 'home.html') def login_view(request): return render(request, 'login.html') def compare_files_view(request): # Update the view name if request.method == 'POST' and 'file1' in request.FILES and 'file2' in request.FILES: file1 = request.FILES['file1'] file2 = request.FILES['file2'] result = "Same" if compare_files(file1, file2) else "Different" return render(request, 'home.html', {'result': result}) else: return render(request, 'home.html') def compare_files(file1, file2): … -
Something went wrong. Could someone check my code please? [closed]
my code goes wrong, please could someone check it? Thank you in advance. the view: def account_view(request, *args, **kwargs): context = {} user_id = kwargs.get("user_id") try: account = Account.objects.get(pk=user_id) posts = Post.objects.filter(account=account).order_by("id").reverse() context = {'posts': posts} except: return HttpResponse("Something went wrong.") The urls: path('<user_id>/', account_view, name="view"), The template: Something went wrong. -
how to run scrapy in a Django view and alert Django when the spider is finished?
I am trying to start a scrape spider from a Django view and have a method of knowing when the spider is finished. I can run the spider successfully by disabling signals in the crawler process. Like in the code below. Because the scrapy signals need to run in the main thread to function. But the only way I am currently aware of knowing when the spider has finished is using the spider_closed signal. Is there another way alert Django when the spider is finished or a method to make sure the spider and the signals run in the main thread? class PosmoScraperView(APIView): # Authentication classes authentication_classes = [TokenAuthentication] # Requires user authenticate to access permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): # Get user input from json serializer = StartURLSerializer(data=request.data) if serializer.is_valid(): # Get url from json post request start_url = serializer.validated_data['url'] # Get spider settings process = CrawlerProcess(get_project_settings()) # Run the Scrapy spider process.crawl(BaseSpiderSpider, start_url=start_url) process.start(stop_after_crawl=True, install_signal_handlers=False) return Response({'status': 'request received'}, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django pass datetime to TempusDominus
When I edit en entity I want to pass the datetime to the form, but the format is not respected. In my view I have: def get_initial(self): initial = { 'season': Season.objects.get(pk=self.request.session['selected_season_id']), 'start': self.object.start.strftime('%Y-%m-%d') if self.object.allday else self.object.start.strftime('%Y-%m-%d %H:%M') } if self.object.end is not None: initial = { 'end': self.object.end.strftime('%Y-%m-%d') if self.object.allday else self.object.end.strftime('%Y-%m-%d %H:%M') } return initial The form has following options: var picker = new tempusDominus.TempusDominus(document.getElementById(date_element_id), { //put your config here localization: { startOfTheWeek: 1, format: 'yyyy-MM-dd HH:mm', hourCycle: 'h24' }, restrictions: { minDate: new Date(), maxDate: undefined, disabledDates: [], enabledDates: [], daysOfWeekDisabled: [], disabledTimeIntervals: [], disabledHours: [], enabledHours: [], } }); picker.dates.formatInput = date => moment(date).format('yyyy-MM-DD HH:mm'); On an empty input field the datetime is shown correct. On an existing field, for an edit, the format is '12/31/2024, 16:00' But the datetime-string is passed correctly to the form and in the source I also see the correct format like '2024-12-31 16:00' . Why is the format changed? -
Django channels 4.0.0 not working, can't connect to the web socket server
Following the official docs, built a small django channel server but when tried to test it using WebSocket King it always throws Could not connect to "ws://127.0.0.1:8000/chat/". You may be able to find more information using Inspector/Dev Tools on this page. Settings.py INSTALLED_APPS = [ 'daphne', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', #Custom apps 'user_auth', 'core', ] ASGI_APPLICATION = 'buddies.asgi.application' asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application from django.urls import path from core.consumers import EchoConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'buddies.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ # path("chat/admin/", AdminChatConsumer.as_asgi()), path("chat/", EchoConsumer.as_asgi()), ]) ) ), }) consumers.py # it is inside the core app from channels.consumer import SyncConsumer class EchoConsumer(SyncConsumer): def websocket_connect(self, event): self.send({ "type": "websocket.accept", }) def websocket_receive(self, event): self.send({ "type": "websocket.send", "text": event["text"], }) When I run the django server it gives no errors (even when I try to ping the server) System check identified no issues (0 silenced). January 07, 2024 - 20:58:04 Django version 5.0.1, using settings 'buddies.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Tried lowering down the channels version to 3.0.5 and using "channels" in the INSTALLED_APPS, … -
How to set up dark/light mode in Django?
I'm working on Django project and I purchase the HTML theme. Within the theme there is option for light and dark theme, by default you have light theme, but if I wand dark theme I need to add class to body: <body class="theme--dark">. I'm trying to think a way to add switch at menu and with if statement to change the theme, but this is bit tricky since I don't have view for base.html I'm not sure how to do this and I'm not sure what to google to find appropriate solution. Any help is more than welcome, thanks in advance! -
Integrate custom tax and discounts in Stripe checkout session
Can you please help me with integration of tax and discounts in my Stripe sission This is my current code class CreateCheckoutSessionOrderView(View): def get(self, request, *args, **kwargs): order_id = self.kwargs["order_id"] DOMAIN: str = 'http://127.0.0.1:8000' order = Order.objects.get(id=order_id) # tax_rates = [] # for tax in order.tax.all(): # tax_rate = stripe.TaxRate.create( # display_name=tax.name, # description=tax.name, # percentage=tax.rate, # jurisdiction="RU", # inclusive=False, # ) # tax_rates.append(tax_rate.id) # # discounts = [] # for discount in order.discount.all(): # discount_amount = stripe.Coupon.create( # amount_off=discount.amount, # duration='once', # currency='usd', # name=discount.name, # ) # discounts.append(discount_amount.id) session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': order.get_total_cost() * 100, 'product_data': { 'name': order.__str__(), }, }, 'quantity': 1, }, ], payment_intent_data={ 'metadata': { 'order_id': order.id, }, }, mode='payment', success_url=DOMAIN + '/success/', cancel_url=DOMAIN + '/cancel/', # tax_rates=tax_rates, discounts=[{"discounts": '{{COUPON_ID}}'}], ) return JsonResponse({'id': session.id}) Getting this traceback for now stripe._error.InvalidRequestError: Request req_h7p3k0OElRSyeg: Received unknown parameter: discounts[0][discounts] [07/Jan/2024 10:40:53] "GET /order_checkout/1 HTTP/1.1" 500 115336 I really appreciate any suggestions and code review. I'm just learning how to deal with stripe payments for now -
Django User Management: Gets a 404 page | can't logout using "localhost:8000/accounts/logout
I used an online instractions for building my first application on Django. I created a project and an app and it's all works fine by now. The problem is, whenever I want to log in, it redirect to "accounts/login" and I log in using my username and password and i cannot log out while i'm clicking on the button i added to log out its redirecting to a build-in accounts/logout and it doesnt exist. I added this in my app urls: path("accounts/", include("django.contrib.auth.urls")), Where did I go wrong? I tried path("accounts/", include("django.contrib.auth.urls")), -
Please you recommend English literature on e-commerce systems or Django for my pet e-commerce platform
everyone! I am a student from China working on my graduation project. I plan to build a pet e-commerce platform using Django and Vue. Before starting this project, I need to read some English literature related to e-commerce systems or Django. Any recommendations would be greatly appreciated. Thank you! 我尝试使用过谷歌学术,但我不知道什么英文论文才值得看 -
Is there a way to change attributes of a form based on one attribute?
Good evening! I'm a django newbie and I'm currently experiencing a problem. I'm using a ClassBasedView, where field x is a char field with specific choices. I want to know if it's possible to hide field y and z before choosing x and to add field y or z based on choice. class BookCreateView(LoginRequiredMixin, CreateView): model = Book fields = ['x', 'y', 'z'] ` -
CI/CD pipeline for a django application in google cloud
I am creating a pipeline to deploy a Django application to google cloud run. Google has created a codelab with steps on how to manually deploy such an application. They use a Procfile which contains the migration script. And then they would deploy a cloud run job that would trigger this migration. I am using cloud build which uses multiple steps to finish the deployment. Starting with a docker step, then what follows. but the problem is that I cant get the migrate to run. I cant understand how a Procfile works and how their deployment works so I can hack it into running as a pipeline