Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing data from Django to React
Im trying learn django and react and im doing so by trying to create a web app using spotify api to display top tracks and top artists for users. I have successfully connected to the api and created a view to extract the data I need and have created a template navigating through different time frames etc but i was wondering how i would now use React to build the frontend and how to pass the data to react. this is my current view to retrieve the users top tracks data: def top_track(request): code = request.session.get('spotify_code') time_frame = request.GET.get('time_frame', 'short_term') # Retrieve timeframe parameter from URL, Default to 'short_term' limit_frame = request.GET.get('limit_frame', 20) if code: request.session['spotify_code'] = code spotify_auth = SpotifyOAuth( client_id=settings.SPOTIPY_CLIENT_ID, client_secret=settings.SPOTIPY_CLIENT_SECRET, redirect_uri=settings.SPOTIPY_REDIRECT_URI, ) token_info = spotify_auth.get_access_token(code) access_token = token_info['access_token'] sp = spotipy.Spotify(auth=access_token) # Fetch data using the token and the selected time frame top_tracks = sp.current_user_top_tracks(limit=limit_frame, time_range=time_frame) # Track info dictionary track_info = [] for track in top_tracks['items']: track_id = track['id'] album = sp.track(track_id)['album'] album_cover = album['images'][0]['url'] artist_name = track['artists'][0]['name'] track_info.append({ 'track': track, 'album_cover': album_cover, 'artist_name' : artist_name, }) timeframe = " " if time_frame == "short_term": timeframe = "1 Month" elif time_frame == "medium_term": timeframe = "6 … -
How can we pass the data pages into to layouts partials file in Django
Layouts.html <div class="ispl-header js-ismHeader"> {% include './partials/_breadcrumbs.html' %} </div> Child Pages `{% extends 'layouts.html'%} {% endblock %} {% block breadcrumb %} <li>Test1</li> <li>Test12</li> <li>Test3</li> {% endblock %} ` partials/_breadcrumbs.html <ol class="breadcrumb ispl-admBreadcumb_listing"> {% block breadcrumb %}{% endblock %} </ol> breadcrumb not printing child page data Trying to print data into partial file -
Add second row of model data below Django select menu choice
I have all of my choices rendering in the dropdown menu but I was wondering if it was possible to add a second row of descriptive subtext below each choice that shows in the menu. class FootballLineup(forms.ModelForm): class Meta: model = FootballContestEntry fields = ['qb'] qb = forms.ModelChoiceField(label='', queryset=NFLPlayer.objects.filter(active=True, position='QB'), empty_label="Select Quarterback", required=True) qb.widget.attrs.update({'class': 'text-center lineup-select marker'}) -
PermissionError: [WinError 5] Access is denied whenever I run anything in python manage.py
Im relatively new to django and I got this error two days ago and tried everything to fix it. I tried to run as administrator and it did not work, and i tried re installing python and it didn't work as well. Also, I reintsalled the virtual environment and it didn't work as well. I read a couple of articles including https://sebhastian.com/environmenterror-winerror-5-access-is-denied/ https://gameofthrones-croatia.com/permissionerror-winerror-5-access-is-denied/ And i still couldn't figure it out. Traceback (most recent call last): File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\HP\AppData\Local\Programs\Python\Python36\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\HP\OneDrive\Documents\Project\django\djangoProject\MakEnv\lib\site-packages\django\contrib\auth\models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File … -
I'm getting an error while installing 'mysqlclient' for a Django project on Ubuntu. Can anyone please help me fix this error?
Installing mysqlclient... Resolving mysqlclient... Adding mysqlclient to Pipfile's [packages] ... ✔ Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Resolving dependencies... ✘ Locking Failed! ⠴ Locking... ERROR:pip.subprocessor:[present-rich] Getting requirements to build wheel exited with 1 [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 704, in _main [ResolutionFailure]: resolve_packages( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 662, in resolve_packages [ResolutionFailure]: results, resolver = resolve( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/resolver.py", line 642, in resolve [ResolutionFailure]: return resolve_deps( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 1167, in resolve_deps [ResolutionFailure]: results, hashes, markers_lookup, resolver, skipped = actually_resolve_deps( [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 948, in actually_resolve_deps [ResolutionFailure]: resolver.resolve() [ResolutionFailure]: File "/home/deepak-budha/.local/lib/python3.10/site-packages/pipenv/utils/resolver.py", line 690, in resolve [ResolutionFailure]: raise ResolutionFailure(message=str(e)) [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. You can use $ pipenv run pip install <requirement_name> to bypass this mechanism, then run $ pipenv graph to inspect the versions actually installed in the virtualenv. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: Getting requirements to build wheel exited with 1 I've used this command "sudo apt-get install python3-dev default-libmysqlclient-dev build-essential" and tried to install mysqlclient. But I get the same error. -
Django Crontab Job Not Executing Within Docker Container
I am facing an issue with running Django crontab jobs within a Docker container. The crontab jobs work perfectly in my local development environment, but when I dockerize my Django app and attempt to run it within a container, the crontab jobs do not seem to execute as expected. Here's a breakdown of the setup and the problem I'm encountering: Local Development (Working): In my local development setup, I have added the following configuration to my Django settings: THIRD_PARTY_APPS = [ "django_crontab", ] CRONJOBS = [ ("* * * * *", "apps.{path}.jobs.deactivate_expired_enrollments"), ] This configuration sets up a crontab job that deactivates expired course enrollments. The crontab job works perfectly in this environment. Docker Setup: To dockerize my Django app, I've created a Dockerfile and a start.sh script as part of my Docker Compose configuration: Dockerfile: # Install apt packages RUN apt-get update && apt-get install --no-install-recommends -y \ # Installing cron cron \ RUN touch /var/log/cron.log RUN (crontab -l ; echo "* * * * * echo 'Hello world' >> /var/log/cron.log") | crontab # Run the command on container startup CMD cron && tail -f /var/log/cron.log start.sh: #!/bin/bash set -o errexit set -o pipefail set -o nounset python manage.py … -
I have an issue with i18n and custom error handling in Django
I am implementing custom error handling in Django, and I have an issue with the '404 Not Found' error. Essentially, when I access http://localhost:8000, I am redirected to the 404 error page. However, if I type http://localhost:8000/en/, I am redirected to the homepage. What I want to achieve is to be redirected to the homepage even by simply typing http://localhost:8000. In the main urls.py I've defined the urlpatterns in the following way: urlpatters = i18n_patterns( ... ) and handler404 = "baseApp.views.error_404" Do you have any suggestion? I tried changing LANGUAGE_CODE from "en-us" to "en" but it didn't work -
Sorting Many to Many relationship in django doesn't work
I've been trying to implement a sorting solution for so long and nothing has worked so far. I have a Email list and email model. There is a many to many relationship between them. Here's my model and serializer. Model.py from django.db import models from django_extensions.db.models import TimeStampedModel from users.models import User class Email(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) def __str__(self): return self.email class EmailList(TimeStampedModel): user = models.OneToOneField(User, on_delete=models.CASCADE) emails = models.ManyToManyField(Email, related_name='email_lists') def __str__(self): return self.user.username Serializers.py class EmailSerializer(serializers.ModelSerializer): class Meta: model = Email fields = ('email', 'first_name', 'last_name',) class EmailListRetrieveSerializer(serializers.ModelSerializer): emails = EmailSerializer(many=True) class Meta: model = EmailList fields = ('emails', 'id') I tried to use OrderingFilter but it didn't work. I tried annotation. Same result. I used ChatGPT to come up with a solution he also couldn't give me the solution. Same solution would work on one to many relationship but not on many to many. Please help me figure out a view for this. Thanks a lot. -
post method not allowed in HitCountDetailView
Adding a Comment Form to Django Blog Post: Encountering "Method Not Allowed (POST)" Error this is my view class BlogDetailView(HitCountDetailView): http_method_names = ['get', 'post'] model = BlogModel context_object_name = 'blog_detail' template_name = 'main/single.html' count_hit = True # for show all post in the sidebar def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) blog = self.get_object() # Get the current blog post # Get the comments related to the current blog post comments = CommentModel.objects.filter(blog=blog,active = True) context['comments'] = comments context['blogposts'] = BlogModel.objects.filter(status = 'p')[:3] # Get blog posts for the sidebar # Pass the comment form to the context context['comment_form'] = CommentForm() return context def post(self, request, *args, **kwargs): blog_post = self.get_object() comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = comment_form.save(commit=False) comment.blog = blog_post comment.save() return redirect('app:mag_detail', slug=blog_post.slug) context = self.get_context_data(**kwargs) context['comment_form'] = comment_form return self.render_to_response(context) and this is template <h1>comment </h1> <form method="post" action="{% url 'app:mag_detail' slug=mag_detail.slug %}"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit">Submit Comment</button> </form> how can i solve that? thanks I'm currently working on integrating a comment form into my Django blog post using a class-based view. My goal is to allow users to submit comments on each blog post. While the form is displayed correctly on the … -
Django admin login csrf error only on https
My django application is working fine both on locally and on server with http. But when I am enabling https for my domain it stops working and giving me csrf error. Once again. The problem is not happening on http. Only on https. My django application is dockarized. Also I am using nginxproxymanager as an alternative to nginx. Because it gives an easy gui to manage sites and handle ssl. I am using cloudflare to manage my dns. Here is my settings.py: CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = ["https://api.mailgrass.com", "http://api.mailgrass.com"] CORS_ALLOWED_ORIGINS = ["https://api.mailgrass.com", "http://api.mailgrass.com"] SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") Please help me solve this issue. I am pulling my hair for the last couple of days. -
SIgning users in Django through Google OAuth and using that data to access their Gmail
While signing users in through Google in Django is pretty conventional, I can't seem to figure out how to use that user data that I get upon login to get access to the user's Gmail. In case i need another authentication step, how do i make it so i remember their Gmail authentication for next time. Essentially, I need to log in users in my Django app through their Google account and then feed them their Gmail emails on their dashboard. Tried django allauth and played around but with no results. -
ModuleNotFoundError: No module named 'django.conf.urls.defaults' - django compat for background tasks
I'm trying to use background tasks in Django, but It requires django-compat, and the problem is that django-compat has some problems with my django version, so is there a way to fix the problem with compat or do I have to start looking for another way to use background tasks? error: \lib\site-packages\compat\__init__.py", line 48, in <module> from django.conf.urls.defaults import url, include, handler404, handler500 # pyflakes:ignore ModuleNotFoundError: No module named 'django.conf.urls.defaults' -
DRF Create list of objects even when some of them not valid
I'm currently working on a DRF project where I'm dealing with a scenario where I receive a list of objects through a POST request. The challenge I'm facing is that this list might contain some objects that are not valid according to certain criteria. However, I need to go ahead and create all the valid objects, and then perform a bulk creation of all these valid objects in one go. I've tried a few approaches, but I'm running into issues with properly validating and handling the objects, especially when using a many=True, if one of the items are not valid than no items created at all. Has anyone encountered a similar situation or can provide insights on how to approach this? Any guidance on how to correctly structure the validation, filtering, and bulk creation process would be greatly appreciated! Thank you in advance. Here is the code I've managed to write, but it doesn't look right to iterate over objects in the view: @action(methods=['post'], detail=False, url_path='custom_method') def custom_method(self, request): created = [] for item in request.data: serializer = self.get_serializer(data=item) try: serializer.is_valid(raise_exception=True) except ValidationError: # ... make log continue self.perform_create(serializer) created.append(serializer.data.get('id')) # custom action for created objects ... return Response(...) -
pythonanywhere admin site css is broken in django
when I deployed a django site on pythonanywhere, the admin site css got broken. It works fine on locally but on pythonanywhere it appears like this: enter image description here I read the documentation on static files, ran collectstatic successfully, ran findstatic (the program finds the base.css correctly), however, I still cannot see the proper styling of the admin site. -
404 Error When Verifying Email in Dj-Rest-Auth API for Mobile App
I'm developing an authentication API for a mobile app using dj-rest-auth in Django. After a user registers an account, a verification email is sent to the user with an activation key. However, when I try to verify the email by sending a POST request to the verification endpoint, I receive a 404 Not Found error. I'm unsure where the issue lies. # main project urls.py urlpatterns = [ # Other URL patterns... path('register/', include('dj_rest_auth.registration.urls')), # ... ] Settings ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True #ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '' #ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '' SITE_ID = 1 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myEmail' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 #EMAIL_HOST_USER = os.environ.get("EMAIL_USER") #EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_PASSWORD") REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ] } SIMPLE_JWT = { 'USER_ID_FIELD': 'email', 'ACCESS_TOKEN_LIFETIME': datetime.timedelta(minutes=15), 'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=10), 'ROTATE_REFRESH_TOKENS': True, } LOGIN_URL = 'https://localhost:8000/login/' REST_AUTH = { 'USER_DETAILS_SERIALIZER' : 'users.serializers.CustomUserDetailsSerializer', 'REGISTER_SERIALIZER': 'users.serializers.UserRegisterSerializer', 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'my-app-auth', 'JWT_AUTH_REFRESH_COOKIE': 'my-refresh-token', 'JWT_AUTH_HTTPONLY':False, } AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] Issue: When I try to verify the email by sending a POST request to the /register/account-confirm-email/ endpoint with the activation … -
how to make celery able to handle custom import
hello every one how do i make celery able to handle custom models, i have a model i want to perform some tasks on i tried importing it but i keeps throwing errors, below is the code. the error tend to be based on the registered apps, please how can i resolve the issue? i have my celery instance defined in my asgi.py all is set including redis setup CELERY.PY from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab from ecoperative.tasks import savings_increment from django.conf import settings from .load_env import load_env load_env() # set the default Django settings module for the 'celery' program. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "agric360.settings") app = Celery("agric360") app.config_from_object("django.conf:settings", namespace="CELERY") app.conf.beat_schedule={ 'increment':{ 'task':savings_increment(), 'schedule':crontab(minute=1) } } app.autodiscover_tasks() TASKS.PY from __future__ import absolute_import, unicode_literals from app.models import User from wallet.models import Wallet import datetime from celery import shared_task from celery.utils.log import get_task_logger # logger=get_task_logger(__name__) # # @shared_task # # def print_hello(): # # print('hello') @shared_task def savings_increment(): # print('hello') wallets=Wallet.objects.all() for wallet in wallets: date_range=datetime.datetime.now().second-wallet.savings_timestamp.second if wallet.savings != 0: if wallet.savings_timestamp is not None: if date_range >= 30: wallet.savings+=2 wallet.save() else: pass else: pass The error encountered is indicated below Traceback (most recent call last): … -
How to set an image as a background in div?
How can I insert an image into url(): <div class="panel active" style="background-image: url();"> <h3>Business Session</h3> </div> I tried template tag with this {% load static %} and also absolute path but it does not work. My image is in the static directory. -
ModuleNotFoundError: No module named '_sqlite3' when i wanted to create django app
I had a new mechine (PC), I want to use pipenv to work on my django app. It keeps on returning an error "ModuleNotFoundError: No module named '_sqlite3'" each time I try "python manage.py startapp " its really giving me issues and I dont know why. I tried updating python and the pipenv. I also tried installing sqlite3 using "apt-get". Ieven deleted the venv and downladed it again yet same error. I was able to install django and did "django-admin startproject ." and it ran smoothly. Except when I run "python manage.py startapp " it throws an error. -
Current Logged in user can't be found after filtering primary key in django application using REST framework
After filtering the user objects, I can see the current logged in user in json format when I go to this url 'http://127.0.0.1:8000/user_profile_info/', but when I do 'print(userData)' it prints this empty json '{'user': []}', but it should print the current logged in user in json format. Logged in user in json format: {'user': [{'id': 1, 'username': 'JerryTaylor13', 'email': 'JerryTaylor13@gmail.com', 'password': 'f49fidaf#', 'settings': {}}]} views.py @api_view(['GET', 'POST']) def user_profile_info(request): user = User.objects.filter(id=request.user.id) serializer = UserSerializer(user, many=True) return JsonResponse({"user": serializer.data}, safe=False) @login_required def profile(request): response = requests.get('http://127.0.0.1:8000/user_profile_info/') userData = response.json() print(userData) return render(request, 'profile.html') models.py from django.db import models #from django.contrib.auth.models import User #authentication system class User(models.Model): id = models.AutoField(primary_key=True) username = models.CharField(max_length=50) email = models.EmailField(max_length=100) password = models.CharField(max_length=128) # Hashed password settings = models.JSONField(default=dict) Serializers.py from rest_framework import serializers from .models import User, Subject, Project, Task, FocusSession, Tally, Badge, Streak, Reflection class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' The user models and its fields are shown on the django admin site but not in the tables of my postgresSQL db. Any guidance would be appreciated. -
HyperlinkedModelSerializer and ModelViewSet, could not resolve URL
# models.py class Test(models.Model): name = models.CharField(default="yolo", max_length=100) # serializers.py class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Test fields = '__all__' # views.py class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer # urls.py router.register(r'test', TestViewSet) # generated routes: ^test/$ [name='test-list'] ^test\.(?P<format>[a-z0-9]+)/?$ [name='test-list'] ^test/(?P<pk>[^/.]+)/$ [name='test-detail'] ^test/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='test-detail'] Error: File "\rest_framework\serializers.py", line 522, in to_representation ret[field.field_name] = field.to_representation(attribute) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "\rest_framework\relations.py", line 416, in to_representation raise ImproperlyConfigured(msg % self.view_name) django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "test-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. I did include the related model in the serializer's meta, and I didn't touch lookup_field either in the view or in the serializer (not that setting it manually seems to have any curative effect). What am I missing? -
Can't make gunicorn systemd service recognize change in code only by rebooting my linux computer
I have deployed a simple Django app locally on my ubuntu machine using systemd. I have created two files gunicorn.socket and gunicorn.service according to many tutorials on the web. When I change my app's python code, the only way to see the change on the browser is to reboot the computer. I have tried doing different combination of the following commands without success: systemctl daemon-reload systemctl restart gunicorn.service systemctl restart gunicorn.socket I get the message: Failed to restart gunicorn.service: Unit gunicorn.socket not found. although the file gunicorn.socket exists as usual Excerpt from my nginx config file: location /static/ { root /root/djdeploy/demo/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target My gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=nad Group=www-data WorkingDirectory=/home/nad/djdeploy/demo ExecStart=/home/nad/djdeploy/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ demo.wsgi:application [Install] WantedBy=multi-user.target -
Custom response decorator for model view set in django
I am trying to customize my response in CollectionViewSet for each http method. response would be different message and status code Problem, list, create, update method are identical to it's parent except delete method which has some extra logic # Working V-1 class CollectionViewSet(ModelViewSet): queryset = Collection.objects.annotate( products_count=Count('products')).all() serializer_class = CollectionSerializer def generate_response(self, message, status_code, data=[]): response_data = { 'message': message, 'status': status_code, 'data': data } return Response(response_data, status=status_code) def list(self, request, *args, **kwargs): collections = self.get_queryset() serializer = self.get_serializer(collections, many=True) return self.generate_response('Data fetched successfully', status.HTTP_200_OK, serializer.data) # no special logic it's identical to (super().create()) method def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return self.generate_response('Data created successfully', status.HTTP_201_CREATED, serializer.data) def update(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return self.generate_response('Data updated successfully', status.HTTP_202_ACCEPTED, serializer.data) def destroy(self, request, pk): collection = get_object_or_404(Collection, pk=pk) if collection.products.count() > 0: return self.generate_response('collection cannot be deleted because it includes one or more products.', status.HTTP_405_METHOD_NOT_ALLOWED) collection.delete() return self.generate_response('Data deleted successfully', status.HTTP_204_NO_CONTENT) I am trying to have some way to decorate the CollectionViewSet class so that I can utilize full feature of ModelViewSet and able to get response as before @generate_custom_response class CollectionViewSet(ModelViewSet): queryset = Collection.objects.annotate( products_count=Count('products')).all() serializer_class = … -
django-nvd3 not showing the chart
Recently I tried to make a dynamic website to show different charts of different types in one single html page, the following is my code views.py from django.shortcuts import render from dashboard.models import Data # Create your views here. def dashboard(request): data = Data.objects.all() piechart = pieChart() context = {'data':data, 'piechart': piechart} return render(request, 'dashboard/dashboard.html', context) def pieChart(): xdata = ["Apple", "Apricot", "Avocado", "Banana", "Boysenberries", "Blueberries", "Dates", "Grapefruit", "Kiwi", "Lemon"] ydata = [52, 48, 160, 94, 75, 71, 490, 82, 46, 17] chartdata = {'x': xdata, 'y': ydata} charttype = "pieChart" chartcontainer = 'piechart_container' data = { 'charttype': charttype, 'chartdata': chartdata, 'chartcontainer': chartcontainer, 'extra': { 'x_is_date': False, 'x_axis_format': '', 'tag_script_js': True, 'jquery_on_ready': False, } } return data and the html file is as follows {% load static %} <script type="text/javascript" src='{% static 'jquery/dist/jquery.js' %}'></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dashboard</title> </head> <body> <h1> Dashboard </h1> <h1>Fruits vs Calories</h1> {% load nvd3_tags %} {% include_chart_jscss %} <script> {% load_chart charttype chartdata chartcontainer extra %} </script> {% include_container chartcontainer %} </body> </html> Why is it not working? I' m trying to make a chart in different function n give it a call in dashboard so that … -
Docker & Django: Django is looking for a DB table before running migrations
When I run docker-compose, all containers start without errors except "catering-django-1". As I understand it, django looks for the "myapp_menu" table in the DB before running the migrations. However, everything works for me locally. That is, when I write "python3 manage.py migrate" in the console - everything works flawlessly. I can't figure out what the problem is for a long time and I hope for your help. Thank you! Docker-compose logs: Attaching to catering-django-1, catering-nginx-1, catering-postgres-1, catering-redis-1, catering-redis-commander-1, catering-worker-1 catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory condition. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect. catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 * Redis version=7.2.0, bits=64, commit=00000000, modified=0, pid=1, just started catering-redis-1 | 1:C 26 Aug 2023 17:55:06.942 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf catering-redis-1 … -
Django celery is not processing the task
I am trying to tigger a process that runs in the background. I am calling this process using ajax call. I have setup celery/rabbitmq/flower to achieve this. In my app ->views.py def sync_now(request,sync_id): sync_obj=Sync.objects.get(id=sync_id) synchronize_data.apply_async(args=[sync_id]) result = synchronize_data.apply_async(args=[sync_id]) # Get the task ID task_id = result.id print("task id") return render something Tasks.py app = Celery('sync', broker='pyamqp://xxx:xxxx@localhost:5672/myvhost') @shared_task def synchronize_data(sync_id): try: sync_obj = Sync.objects.get(id=sync_id) # Your synchronization logic goes here sync_data(sync_id, sync_obj) return 'Success' # Return a result to indicate success except Exception as e: return str(e) # Return an error message in case of failure When I run this command - celery -A ipass worker -l info --pool=solo -- it appears like all the queued process gets triggered and sync_data is called multiple times. I had to manually kill the cmd But when I trigger this from the template I get only [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[0c72b00b-acf1-48d2-ab44-6ddb678d62e8] received [2023-08-26 23:08:26,320: INFO/MainProcess] Task sync.tasks.synchronize_data[7c2c018f-cd6b-4dae-8cab-b18a572a5c92] received [2023-08-26 23:08:26,887: INFO/SpawnPoolWorker-32] child process 10588 calling self.run() [2023-08-26 23:08:26,888: INFO/SpawnPoolWorker-33] child process 11024 calling self.run() I am unable to debug, what is missing here ? Please let me know if you need more information.