Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save post via celery
I have a particular use case where i write text for a blog post in admin dashboard. Then i want to generate the embeddings of post. I am doing this in admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'created_at') readonly_fields = ('embeddings_calculated','emebddings_updated_at') def save_model(self, request, obj, form, change): if not obj.meta_title: obj.meta_title = obj.title obj.meta_description = obj.content[:160] super().save_model(request, obj, form, change) print("django post id",obj.id) post = get_object_or_404(Post, id=obj.id) print("django post title",post) if not change: # if new post not an edit post task_id = perform_task.delay(obj.id) result = AsyncResult(str(task_id), app=app) print("AsyncResultx", result) print("AsyncResultx_state", result.state) here is my celery task @shared_task() def perform_task(post_id): print("celery post id",post_id) post = get_object_or_404(Post, id=post_id) print("celery post title",post) I am getting this error django.http.response.Http404: No Post matches the given query. Though the print statement such as django post id and django post title show me correct result. But the issue lies in celery. I cant see celery post title in console. I aslo tried task_id = transaction.on_commit(lambda: perform_task.delay(obj.id)) But it did not work as well. Without celery every thing work well, but i want to use celery. -
Django retrieves wrong datetime objects (timezone overridden) from postgres database
I am using: psycopg==3.1.18 Django==4.2.10 PostgreSQL 16.1 I use a DateTimeField on a Django model which created a timestamp with timezone in postgres If I create a new object of that model with passing a timezone-aware datetime, save it to the DB, it gets created correctly. With that I mean, when i connect to the DB with a viewer like pgadmin or datagrip, the datetime is correct. But when i get the data back in django, they have the wrong offset. It seems like it overrides the Offset to 0 (UTC). The time is still the same, which is the problem. Exmaple: I pass to the model: 2024-02-18 01:46:29+01:00 In the database (viewed with DataGrip) the following is stored: 2024-02-18 01:46:29.000000 +01:00 When i get the object in django, it is: 2024-02-18 01:46:29+00:00 So the time is not the same anymore, because instead of reading the time just in the UTC Timezone, it take the time in the UTC+1 timezone but changes the timezone to UTC I have set the following in settings.py USE_TZ = True TIME_ZONE = 'UTC' I have tried playing around with the TIME_ZONE setting in the DATABASE Variable (settings.py) Setting it to 'TIME_ZONE': 'Europe/Zurich', resulted in … -
Django Password not receiving {{ uid }}
Anyone familiar with the inbuilt django built in password reset? in my url.py i'm calling path('password-reset-confirm///', PasswordResetConfirmView.as_view(), name="password_reset_confirm"), html is: You've requested to reset your password. Please go to the following URL to enter your new password: {{ protocol }}://{{ domain }}/password-reset-confirm/{{ uid }}/{{ token }}/ the email is showing as You've requested to reset your password. Please go to the following URL to enter your new password: http://127.0.0.1:8000/password-reset-confirm/%7B%7B uid }}/c3af5t-1c91e83e20617d5751750c6eb30e5b60/ I don't get why uid is not being recognised I tried debugging with print statements -
How to configure redis cluster for celery.py?
I'm trying to run my celery worker but I keep running into errors. I'm using aws elasticache redis cluster and running it on an ec2 instance. # celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # Import Django settings from celery.schedules import crontab from redis.cluster import RedisCluster os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shipninja.settings') redis_cluster_nodes = [ {'host': 'rediscluster-0001-001.rediscluster.m0rn9y.use1.cache.amazonaws.com', 'port': 6379}, {'host': 'rediscluster-0002-001.rediscluster.m0rn9y.use1.cache.amazonaws.com', 'port': 6379}, {'host': 'rediscluster-0003-001.rediscluster.m0rn9y.use1.cache.amazonaws.com', 'port': 6379}, ] broker_url = 'redis://' + ','.join([f'{node["host"]}:{node["port"]}' for node in redis_cluster_nodes]) result_backend = broker_url app = Celery('shipninja') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(['app']) # This will discover tasks in all registered Django apps app.conf.beat_schedule = { 'aggregate-and-charge-users-weekly': { 'task': 'path.to.aggregate_and_charge_users_weekly', # Use the correct path to your task 'schedule': crontab(hour=0, minute=0, day_of_week='monday'), }, 'update_inventory_items': { 'task': 'app.tasks.update_inventory_items', 'schedule': 60, }, 'update-shipments-every-minute': { 'task': 'app.tasks.update_shipments_cache', 'schedule': 300, }, 'update_package_statuses_every_minute': { 'task': 'app.tasks.update_package_statuses', 'schedule': 28800, }, 'refresh-access-tokens': { 'task': 'app.tasks.refresh_tokens_task', 'schedule': 3600, }, } I tried using redis-py-cluster with redis 3.5.3: ^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/rediscluster/connection.py", line 160, in __init__ self.nodes.initialize() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/rediscluster/nodemanager.py", line 300, in initialize raise RedisClusterException("Redis Cluster cannot be connected. Please provide at least one reachable node.") rediscluster.exceptions.RedisClusterException: Redis Cluster cannot be connected. Please provide at least one reachable node. Using redis-py with … -
Error when connecting Angular app with REST-Django service
I have an web application deployed on GKE. Front-end service is Angular 17 app running on Official NginX Docker container Load Balancer with Ingress. Backend is REST-Django service running on Gunicorn running on Official Python container. The problem is when I want to reach the service (GET method) from Angular I get error Reason: CORS request did not succeed in Firefox browser - Chromium says net::ERR_NAME_NOT_RESOLVED. The Django service has installed CORS: INSTALLED_APPS = [ ... 'corsheaders', ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS = True In local docker-compose environment everything works like it should. From Angular's pod/container I am able to curl the Django service and it responds in desired way. -
Django: Transform an object into an object of a derived model class
In Django I've got a model class M1 and class M2 which is derived of M1. In the database this is generated as two tables T1 and T2 where T2 points to T1 like this: T1.id = T2.T1_ptr_id So far so good. Now it might be that in the database the entry for for T2 is missing sometimes - and I would like to create this entry on the fly by changing M1 to M2 in Django. I have tried this, but it (obviously) fails: m2 = M2(pk=m1.id) Furthermore I don't want to create a new instance of M2 - i want to transform M1 into M2. Is there a way to do this? -
Celery Problem - Docker unable to run Celery background task, Celery does not seem to start properly - Docker, Django, React, Redis, Celery
I have created a test repository that has Django, React, Redis, Celery: https://github.com/axilaris/docker-django-react-celery-redis. My goal is to get celery working but its not. This is based from this Docker - React and Django example tutorial code: https://github.com/dotja/authentication_app_react_django_rest And trying to use Docker - Celery & Redis from this tutorial code: https://github.com/veryacademy/docker-mastery-with-django/tree/main/Part-4%20Django%20Postgres%20Redis%20and%20Celery <-- Part 4 tutorial for Celery & Redis I am having trouble to get Celery started correctly as I see the background task is not executed. It did not print this. I think this is the problem. celery | -------------- celery@b755a7cdba8d v5.3.6 (emerald-rush) celery | --- ***** ----- celery | -- ******* ---- Linux-6.6.12-linuxkit-aarch64-with 2024-03-02 20:48:06 celery | - *** --- * --- celery | - ** ---------- [config] celery | - ** ---------- .> app: core:0xffff9bbd7550 celery | - ** ---------- .> transport: redis://redis:6379// celery | - ** ---------- .> results: redis://redis:6379/ celery | - *** --- * --- .> concurrency: 10 (prefork) celery | -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) celery | --- ***** ----- celery | -------------- [queues] celery | .> celery exchange=celery(direct) key=celery Here are more details on the console logs for docker-compose build/up and also … -
Django polls tutorial part 3, template is able to load Question model text but not related Choice model
I'm currently on the third part of the official Django polls tutorial. Have a problem where when I load the template detail.html, question_text from the Question model is being rendered fine but choice_text(s) are not. The browser shows the correct amount of list bullets as but the text is not there. Here is the template I am trying to load: <h1>{{ question.question_text }}</h1> <ul> {% for question in question.choice_set.all %} <li> {{choice.choice_text}} </li> {% endfor %} </ul> The associated view function is: def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, "polls/detail.html", {'question': question}) The models are defined as: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField("date published") def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text polls/1 the Question model with two Choices related to it is rendered as text from Questions model rendered correctly but elements from Choice model are not I expected the related Choice objects obtained from {% for question in question.choice_set.all %} to display onto the HTML page as list elements. Instead only the bullets show up without the text. Would really appreciate any help! -
Wagtail: How to filter children of index page, when index page is accessed through foreign key
I apologize for any mistakes, English is not my native language. I am making site with news and events of multiple organizations (each organization has their own account allowing them to create news and events by themself). Using the news as an example: NewsIndexPage is parent for all NewsArticlePages. Each NewsArticlePage is linked with organization. At url /news/ NewsIndexPage shows all news and allow to filter news by organization with RoutablePageMixin (/news/organization/<str: organization_slug>/). Also each organization has their own landing page (OrganizationPage) with organization's info and news section. News section shows up to 3 latest news of organization (like in bakerydemo repository, when latest 3 blog entries is listed in HomePage: https://github.com/wagtail/bakerydemo/blob/1d9247f0f516dd842da995b1d67fadcd7d644f7d/bakerydemo/base/models.py#L305 https://github.com/wagtail/bakerydemo/blob/1d9247f0f516dd842da995b1d67fadcd7d644f7d/bakerydemo/templates/base/home_page.html#L30). Each OrganizationPage references NewsIndexPage through ForeignKey. But I don't know, how to filter children of NewsIndexPage when it accessed through ForeignKey. When I access OrganizationPage instance I want to pass organization's slug to linked NewsIndexPage so I can filter children NewsArticlesPages. The only thing I came up with is to create template_tag that will pass slug as an argument to some kind of get_news_articles(self, organization_slug) function. But I haven't been able to do that yet. news.models: class NewsArticlePage(Page): """ A news article page. """ image = models.ForeignKey( … -
not able to redirect to next html template although code is correct
{% for cinema_hall in cinema_halls %} <div> <h2>{{ cinema_hall.name }}</h2> <div class="show-container" id="show-container-{{ cinema_hall.id }}"> <!-- Loop through shows for each cinema hall --> {% for show in shows %} {% if show.cinemahall == cinema_hall %} <div class="show-box" data-cinema_hall_id="{{ cinema_hall.id }}" data-show_id="{{ show.id }}"> Show: {{ show.timings }} <br> ₹ {{ show.price }} </div> {% endif %} {% endfor %} </div> </div> {% endfor %} this is html code // Click event handler for show-box elements $(document).on('click', '.show-box', function() { // Get the cinema hall ID and show ID from the clicked element's data attributes const cinemaHallId = $(this).data('cinema_hall_id'); const showId = $(this).data('show_id'); // Redirect to seats.html with the cinema hall ID and show ID as query parameters window.location.href = `/seats/?cinema_hall_id=${cinemaHallId}&show_id=${showId}`; }); this is js code def seats(request): cinema_hall_id = request.GET.get('cinema_hall_id') show_id = request.GET.get('show_id') # Use cinema_hall_id and show_id to fetch relevant data # For example: # seats_data = Seat.objects.filter(cinema_hall__id=cinema_hall_id, show__id=show_id) context = { 'cinema_hall_id': cinema_hall_id, 'show_id': show_id, # Include other context data as needed } return render(request, 'screen/seats.html', context) this is views.py code now what i want is that when that div is clicked it takes me to new url with website screen/seats.html but i am keep getting this … -
Django unable to connect to elasticsearch cluster within the same task in ECS
I deployed an application into a ECS task using the following container definitions [ { "name": "api", "image": "${app_image}", "essential": true, "memoryReservation": 256, "environment": [ {"name": "DJANGO_SECRET_KEY", "value": "${django_secret_key}"}, {"name": "DB_HOST", "value": "${db_host}"}, {"name": "DB_NAME", "value": "${db_name}"}, {"name": "DB_USER", "value": "${db_user}"}, {"name": "DB_PASS", "value": "${db_pass}"}, {"name": "DEBUG", "value": "false"}, {"name": "STORAGE_HOST", "value": "${bucket_host}"}, {"name": "ALLOWED_HOSTS", "value": "${allowed_hosts}"}, {"name": "DJANGO_SETTINGS_MODULE_STAGING", "value": "${django_settings_module}"}, {"name": "S3_STORAGE_BUCKET_NAME", "value": "${s3_storage_bucket_name}"}, {"name": "S3_STORAGE_BUCKET_REGION", "value": "${s3_storage_bucket_region}"} ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "${log_group_name}", "awslogs-region": "${log_group_region}", "awslogs-stream-prefix": "api" } }, "portMappings": [ { "containerPort": 9000, "hostPort": 9000 } ], "mountPoints": [ { "readOnly": false, "containerPath": "/vol/web", "sourceVolume": "static" } ] }, { "name": "proxy", "image": "${proxy_image}", "essential": true, "portMappings": [ { "containerPort": 8000, "hostPort": 8000 } ], "memoryReservation": 256, "environment": [ {"name": "APP_HOST", "value": "127.0.0.1"}, {"name": "APP_PORT", "value": "9000"}, {"name": "LISTEN_PORT", "value": "8000"} ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "${log_group_name}", "awslogs-region": "${log_group_region}", "awslogs-stream-prefix": "proxy" } }, "mountPoints": [ { "readOnly": true, "containerPath": "/vol/static", "sourceVolume": "static" } ] }, { "name": "elasticsearch", "image": "${elasticsearch_image}", "essential": true, "memoryReservation": 256, "portMappings": [ { "containerPort": 9200, "hostPort": 9200 } ], "logConfiguration": { "logDriver": "awslogs", "options": { "awslogs-group": "${log_group_name}", "awslogs-region": "${log_group_region}", "awslogs-stream-prefix": "elasticsearch" } } } ] in django … -
DRF: Serialize field with different serializers and many=True
I have the following models in my django rest framework app: class Question(models.Model): class Type(models.TextChoices): TEXT = 'text', 'text question' RADIO = 'radio', 'choosing one option quesiton' CHOICE = 'check', 'choosing multiple options question' type = models.CharField(max_length=5, choices=Type.choices) title = models.CharField() description = models.TextField(blank=True, default='') def __str__(self) -> str: return f'{self.type}: {self.title}' class TextQuestion(Question): answer = models.CharField() class RadioQuestion(Question): variants = fields.ArrayField(models.CharField()) answer = models.CharField() class ChoiceQuestion(Question): variants = fields.ArrayField(models.CharField()) answers = fields.ArrayField(models.CharField()) class Test(models.Model): name = models.CharField() creator = models.ForeignKey(User, on_delete=models.CASCADE) questions = models.ManyToManyField(Question)``` I want to write serializer for test serialization, but I dont know how to serialize questions field. Because I have different serializer for every question type: What should I do? Maybe it`s better to reorganize my models somehow? I already writed serializers for all question types: class TextQuestionSerializer(serializers.ModelSerializer): class Meta: model = TextQuestion fields = '__all__' class RadioQuestionSerializer(serializers.ModelSerializer): class Meta: model = RadioQuestion fields = '__all__' class ChoiceQuestionSerializer(serializers.ModelSerializer): class Meta: model = ChoiceQuestion fields = '__all__' I thought about using serializer.SerializerMethodField() but it this doesnt work with many=True -
How to implement of social login with dj-rest-auth and getting redirected back to frontend which uses vanilla js with sessionid and token cookies set
I'm currently implementing social login with dj-rest-auth with a custom provider. I have went through plenty of sites but most tutorials/resources don't show how to implement the frontend, so I'm unsure how to implement it. The frontend can only use vanilla js and is a SPA. My current idea/testing is with a href=127.0.0.1/api/auth/callback which will run the function callback. If a code is not return it'll redirect to the authorize url to obtain one and proceed to be redirected back to the same function to start login. After logging in then redirect to homepage with all relevant cookies. REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } Provider login api (http://127.0.0.1:8000/api/auth/provider/) auth/views.py redirect_uri = 'http://127.0.0.1:8000/api/auth/callback/' def callback(request): if 'code' in request.GET is None: socialapp = SocialApp.objects.get(name='provider') authorize_url = (f'{settings.OAUTH_SERVER_BASEURL}/oauth/authorize' '?client_id=' + socialapp.client_id + '&redirect_uri=' + quote(redirect_uri, safe='') + '&response_type=code') return redirect(authorize_url) if 'code' in request.GET: socialapp = SocialApp.objects.get(name='NAME') code = request.GET['code'] context = {} context['grant_type'] = 'authorization_code' context['client_id'] = socialapp.client_id context['client_secret'] = socialapp.secret context['code'] = code context['redirect_uri'] = 'http://127.0.0.1:8000/api/auth/callback/' try: token_response = requests.post('https://provider-api-link/oauth/token', json=context) data = token_response.json() # access-token is inside if 'error_description' in data: print("error_description_post_code:", data) social_login_response = requests.post('http://127.0.0.1:8000/api/auth/provider/', json=data) response = HttpResponseRedirect('/') response.set_cookie("Authorization", 'Token … -
Can someone help me on django error on pycharm?
I cant runserver on django in pycharm. error: modulenotfound (django_project) I asked Chatgpt and tried some of it solution but it didn’t work. So can someone help me how to fix it? Im new in django and I don’t know nothing -
Django logout view shows a blank page and does not log out a user
I faced an issue with my logout view. I created a custom CBV that inherits from the default Django LogoutView. The interesting fact is that it works perfectly fine with the FBV. When I associate the /logout/ URL with the CBV there appears only a blank page and does not log out the signed user. I have also created a template that is visualized without any problems with the FBV. Here you can see my views: from django.shortcuts import redirect, render from django.contrib.auth import views as auth_views, get_user_model, logout from django.urls import reverse_lazy from django.views import generic as views from accounts.forms import MyUserCreationForm UserModel = get_user_model() # Create your views here. class MyUserRegisterView(views.CreateView): template_name = "user-register.html" form_class = MyUserCreationForm success_url = reverse_lazy("home page") class MyUserLoginView(auth_views.LoginView): template_name = "user-login.html" class MyUserLogoutView(auth_views.LogoutView): template_name = "user-logout.html" def logout_view(request): if request.method == "POST": logout(request) return redirect("home page") return render(request, "user-logout.html") Here are my urls: from django.urls import path from accounts import views urlpatterns = ( path("register/", views.MyUserRegisterView.as_view(), name="register"), path("login/", views.MyUserLoginView.as_view(), name="login"), path("logout/", views.MyUserLogoutView.as_view(), name="logout"), ) I have also defined LOGOUT_REDIRECT_URL = reverse_lazy("home page") in settings.py here is also my template which is working fine with the FBV and does its job: {% if request.user.is_authenticated … -
How to run a Python Django app designed with HTML
I'm trying to run a Python app made with Django and designed with HTML on a server in dotroll (so there are 2 files that I need to upload, Python and HTML). I know that there is a option in cpanel to run Python apps and I did everything that needed and the Python app runs but when I searched up the website the app was not running there was just a text that said "It works!", "Python 3.10.13" and I don't know why it does this. Is there any fix for this or another way to run these files? Here is a picture of the Python app settings in cpanel: (https://i.stack.imgur.com/SUlfA.png) -
Simple Django app deployed on Azure App Service keeps showing application error
enter image description here It keeps showing error after the app has been succesfully deployed on the Azure App Service, has anyone experienced something similar to this? I have tried ssh into it to confirm my files are intact and they are all right, was expecting the default index page I built for the application -
First grid item from a pandas dataframe isn't displayed properly when using Flask/Django
I'm kind of new to this and I'm trying to display a pandas dataframe in a grid using Django, but the first item of the dataframe is not displayed as a grid item. Dataframe: | Index | Title | | -------- | -------- | | 0 | item1 | |1 | item2 | |2|item3| html template: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> } .grid-container{ display: grid; grid-template-columns: repeat(auto-fill,minmax(200px,1fr)); gap: 16px; } .grid-item{ border: 1px solid #000000; padding: 10px; text-align: center; } <body> <div> <h1>Sample DataFrame</h1> <div class = 'grid-container' {% for product in html_data_df %} <div class = 'grid-item'> <h1>{{product.Title}}</h1> </div> {% endfor %} </div> </div> </body> </html> views.py: def display_products(request): data_df['Image_HTML'] = data_df['Image_link'].apply(lambda x: f'<img src="{x}" width="100">') html_data_df = data_df.to_dict(orient='records') return render(request, 'price_comp/display_products.html', {'html_data_df': html_data_df}) I've also tried using flask, but I am getting the same problem. Item1 is not displayed properly, i've tried shifting the index so that it starts on 1 instead of 0, but that doesn't work either. -
A Start Up. Starting a Start UP [closed]
Not a question I have been thinking this for quite a time.. why don't some of us team up and create our own company?? We can share our own ideas and make websites come to life.. Like.. I can handle Back end and Web design part but i am bad at front end especially DOM part.. Like i have some ideas and i am pretty sure some of you guys have too so lets team up 6-7 of Us 2 and than start it ASAP. If interested DM me in either insta @sandeshpathak0012 or directly in this stack overflow. Blanksacsacsacscs sacac -
Django can't change username in custom User model
I have the following User model in Django's models.py: class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True, primary_key=True) full_name = models.CharField(max_length=65, null=True, blank=True) email = models.EmailField( max_length=255, unique=True, validators=[EmailValidator()] ) When trying to update a username via shell python manage.py shell: userobj = User.objects.get(username="username1") userobj.username = user.lower() userobj.save() It seems that it is trying to create a new user, for which the UNIQUE constraint of the e-mail is violated: django.db.utils.IntegrityError: UNIQUE constraint failed: data_app_user.email Any solutions? Thank you! -
How to solve NSInternalInconsistencyException in django
guys i am trying to run this project from github here . i cloned the repo and installed django (it doesn't have requirements file) and tried to run the project it runs till login, register page but then it goes bad. It throws this error (base) rishikapadia@MacBook-Air budget_project % python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified some issues: WARNINGS: budget_app.ExpenseInfo: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the BudgetAppConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. System check identified 1 issue (0 silenced). You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run 'python manage.py migrate' to apply them. March 02, 2024 - 13:35:25 Django version 5.0.2, using settings 'budget_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [02/Mar/2024 13:35:27] "GET / HTTP/1.1" 200 1547 [02/Mar/2024 13:35:30] "GET /sign_up HTTP/1.1" 200 2137 [02/Mar/2024 13:35:56] "POST /sign_up HTTP/1.1" 302 0 /Volumes/Work/Finance/Django/Django-Budget-App/budget_project/budget_app/views.py:19: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail. fig,ax=plt.subplots() *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: … -
Using the widget, I used the CheckboxSelectMultiple field, as a result, the queryset returns None
I put a form in the template and implemented the addition of an article. As a result, the user fills in the information, especially the categories that are used in multiple relationships and clicks submit. The information can be saved. Here, it is important that the user clicks on one of the categories. Everything, but as a result, the article with correct information but the categories returns None, this is my problem. models.py class CategoryArticle(models.Model): title = models.CharField(max_length=200, verbose_name='عنوان') url_title = models.CharField(max_length=200, verbose_name='عنوان در url') is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال') def __str__(self): return self.url_title class Meta: verbose_name = 'دسته بندی مقاله' verbose_name_plural = 'دسته بندی های مقاله' class Article(models.Model): title = models.CharField(max_length=200, verbose_name='عنوان مقاله') slug = models.SlugField(null=True, blank=True, verbose_name='اسلاگ') article_category = models.ManyToManyField(CategoryArticle, verbose_name='دسته بندی مقاله') short_description = models.TextField(verbose_name='توضیح مختصر') author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='نویسنده') created_at = models.DateTimeField(auto_now_add=True, verbose_name='تاریخ ایجاد مقاله') views = models.PositiveIntegerField(default=0, verbose_name='تعداد بازدید', editable=False) preview_image = models.ImageField(upload_to='images/previews_articles/', verbose_name='پیش نمایش مقاله') content = CKEditor5Field('Text', config_name='extends') audio_file = models.FileField(upload_to='audio_files/', null=True, blank=True, verbose_name='فایل صوتی', validators=[validate_audio_file]) video_file = models.FileField(upload_to='videos/', null=True, blank=True, verbose_name='فایل ویدیویی', validators=[validate_videos_file]) is_active = models.BooleanField(default=True, verbose_name='فعال / غیرفعال') is_important_new = models.BooleanField(default=False, verbose_name='اخبار مهم') is_special = models.BooleanField(default=False, verbose_name='ویژه') forms.py class CreateArticleForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField( label="دسته بندی مقاله", queryset=CategoryArticle.objects.filter(is_active=True), widget=forms.CheckboxSelectMultiple(), required=False, … -
How To add paypal subscription in my django rest_framework websites
I'm devlopping a website by django rest_framework and react and I want to use the subscription so that the user manager should pay for example 20 dollars per month ,my project contains two types of users the Resident and Manager ,every Resident user should belong to a village or Dwar as I created , the village is created by a Manager so those residents users has the Manager as responsible for them and if the manager didn't pay no user can log in this my models .py from django.db import models from django.contrib.auth.models import AbstractUser from rest_framework.authtoken.models import Token from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from dwar.models import Dwar # from time import timezone from datetime import timezone import time # Create your models here. class CustomUser(AbstractUser): territorial=models.CharField(max_length=80) phone_number=models.CharField(max_length=15) is_real=models.BooleanField(default=False) is_resident=models.BooleanField(default=False) is_manager=models.BooleanField(default=False) def __str__(self) : return self.username def fullname(self): return f'{self.first_name} {self.last_name}' class Manager(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE,related_name='manager') village_name=models.CharField(max_length=60) manimg=models.ImageField(blank=True,null=True) is_has_dwar=models.BooleanField(default=False) def __str__(self): return self.user.username class Resident(models.Model): user=models.OneToOneField(CustomUser,on_delete=models.CASCADE) number_of_water_meter=models.CharField(max_length=60,default='o') selected_village_name=models.ForeignKey(Dwar,on_delete=models.SET_NULL,null=True) the_village=models.CharField(max_length=90) name=models.CharField(max_length=90) resimg=models.ImageField(blank=True,null=True) def __str__(self): return self.user.username class Fatoura(models.Model): created_by=models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='the_manager') sendit_to=models.ForeignKey(Resident,on_delete=models.CASCADE,related_name='fatoras') name=models.CharField(max_length=90) village=models.CharField(max_length=90) number_of_water_meter=models.CharField(max_length=60,default='o') created_at=models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.number_of_water_meter class MessageToResident(models.Model): created_by=models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='who_create') send_to=models.ForeignKey(Resident,on_delete=models.CASCADE,related_name='messago') message=models.TextField(max_length=600) is_global=models.BooleanField(default=False) name_of_manager=models.CharField(max_length=70,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True,blank=True,null=True) def __str__(self): return self.created_by.username I already worked with paypal payment … -
Django Add field values as per month and year wise and consolidate
I am trying to consolidate the field values in Django 3.2 and add them and group them month & year wise, but I am unable to get it work, below is my code. models.py class Event(models.Model): name = models.CharField(max_length=255, null=True) MONTH = ( ('january', 'january'), ('february', 'february'), ('march', 'march'), ('april', 'april'), ('may', 'may'), ('june', 'june'), ('july', 'july'), ('august', 'august'), ('september', 'september'), ('october', 'october'), ('november', 'november'), ('december', 'december'), ) YEAR = ( ('2023', '2023'), ('2024', '2024'), ('2025', '2025'), ('2026', '2026'), ('2027', '2027'), ('2028', '2028'), ('2029', '2029'), ('2030', '2030'), ) month = models.CharField(max_length=255, null=True, choices=MONTH) year = models.CharField(max_length=255, null=True, choices=YEAR) event_price = models.IntegerField(null=True) def __str__(self): return self.name views.py from django.db.models import Sum def viewEvent(request): event = Event.objects.all() total_event_price = Event.objects.values(sum('event_price)) context = {'event': event, 'total_event_price: total'} return render(request, 'view_event.html', context) view_event.html <div class="card card-body"> <table class="table table-sm"> <tr> <th>Year</th> <th>January</th> <th>February</th> <th>March</th> <th>April</th> <th>May</th> <th>June</th> <th>July</th> <th>August</th> <th>September</th> <th>October</th> <th>November</th> <th>December</th> <th>Total</th> </tr> {% for items in event %} <tr> <td>{{ items.year }}</td> <td>{{ items.month }}</td> <td>{{ items.total }}</td> </tr> I want the entries added as per month wise and another total which adds all month wise as per the year, which is total field. how do I achieve ? -
I'm struggling to learn Django Framework
How do I learn Django? I understand python basics such as functions, classes etc. I'm trying to learn Django for more than six months. Actually I understand the concept a little but it seems I've not learnt anything at all as I cannot memorize every nuts and bolts of Django framework. I'm feeling so frustrated nowadays. It's may not be relevant but want to mention that I'm 39 years old. Why I'm so struggling? Is it because of my age as my brain has become slow? Or I'm skipping something? Here I want to mention that I understand the basics of html and CSS. I've not learnt JavaScript yet. Thanks. I've tried a number of books and YouTube videos. I'm spending one or two hours to learn the framework everyday. But I'm seeing no progress.