Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to render right buttons (Like or Unlike) in a post based on user's choice using Javascript in a web app?
I'm working on a web app where a user has the option to like or unlike a post posted by another user. I created a button and wrote a Javascript function to change the text inside the button based on user's choice. If user clicks Like button it changes to Unlike and vice versa. Here's my code: models.py class Post(models.Model): """ Model representing a post. """ user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) no_of_likes = models.IntegerField(default=0) def __str__(self): return f"Post {self.id} by {self.user.username} on {self.timestamp}" class Like(models.Model): """ Model representing a like. """ user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} likes {self.post}" urls.py path("", views.index, name="index"), path("like/<int:post_id>", views.like, name="like"), path("unlike/<int:post_id>", views.unlike, name="unlike"), views.py def index(request): """ Home page. """ posts = Post.objects.all().order_by('-timestamp') paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) likes = Like.objects.all() # List of post ids. liked_posts = Like.objects.filter(user=request.user).values_list('post', flat=True) liked_posts = list(liked_posts) return render(request, "network/index.html", { "posts": posts, "page_obj": page_obj, "likes": likes, "liked_posts": liked_posts, }) @login_required def like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) like = Like.objects.create(user=user, post=post) like.save() post.no_of_likes = Like.objects.filter(post=post).count() post.save() return JsonResponse({"message": "successfully liked", "no_of_likes": post.no_of_likes}) @login_required def unlike(request, post_id): … -
Reverse lookup for fields with choices in django models
I have following model : class Role(models.Model) : class RoleTypes(models.TextChoices) : PAID = 'P', 'Paid' UNPAID = 'U', 'Unpaid' COLLABORATION = 'C', 'Collaboration' role_type = models.CharField(max_length=5, choices=RoleTypes.choices, default=RoleTypes.PAID) role_count = models.IntegerField(default = 1, validators=[MinValueValidator(1), MaxValueValidator(10)]) And following serializer : class RoleSerializer(serializers.ModelSerializer): class Meta : model = Role fields = '__all__' Now Role resource is created by passing following data in post request : {'role_type':'P', 'role_count':2} Is it possible that data sent in post request sets role_type = 'Paid' instead of 'P' -
Django + NextJs
How can I integrate django backend with NextJs frontend? Is it possible if yes can anyone please define me the steps... I saw some lectures on youtube and they were about react+django but not next+django Need guidance regarding this I am using Django Rest Framework at backend and NextJs at frontend. -
chat_message doesn't work in consumsers.py, when channel_name value is changed
I'm building a synchronous chat AI bot, there are 7 different models of them each serve for different purpose, therefore I assign a different channel_name during connection(connect). However, when I assign a new channel_name, my chat_message doesn't work at all, but the rest functions(receive, connect, disconnect) doing fine. import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer, AsyncWebsocketConsumer from .models import Message from .contants import SendType class ChatConsumer(WebsocketConsumer): def connect(self): self.group_name = str(self.scope["user"].pk) module_name = self.scope['url_route']['kwargs']['module'] self.channel_name = module_name #self.channel_name = "something" # print(self.scope) # print("-------") print(self.scope['url_route']) print(self.channel_name) self.user = self.scope["user"] async_to_sync(self.channel_layer.group_add)( self.group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.group_name, self.channel_name ) def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] event = { 'type':"chat.message", "message":message } print(message) print(self.channel_name) print(self.scope['user']) if len(message) > 0: async_to_sync(self.channel_layer.group_send)( self.group_name, event ) def chat_message(self, event): message = event["message"] print("CHECKING\n") message_obj = Message(text=message, user=self.user, sender_type=1) message_obj.save() self.send(text_data=json.dumps({"message": f"{self.user.username}: {message}"})) consumers.py from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ path("ws/chat/", consumers.ChatConsumer .as_asgi()), #re_path(r'ws/chat/(?P<module>\w+)/$', consumers.ChatConsumer.as_asgi()), ] routes.py <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Chat Room</title> </head> <body> <textarea id="chat-log" cols="100" rows="20"></textarea><br> <input id="chat-message-input" type="text" size="100"><br> <input id="chat-message-submit" type="button" value="Send"> <script> console.log("Script started."); const chatSocket = new WebSocket( 'ws://' + window.location.host + … -
is there a way of solving; TypeError: 'module' object is not iterable in django?
I am a beginner learning django. while doing my project, I encountered an error and now am stack. while running 'python manage.py makemigrations', the error below occured: TypeError: 'module' object is not iterable I need help where I can start to solve the problem as soon as possible. this is my code myapp/views.py from django.shortcuts import render, redirect from .models import Book, UserBook from django.contrib.auth.decorators import login_required # Create your views here. def home(request): books = Book.objects.all() return render(request, 'home.html', {'books': books}) def library(request): user_books = UserBook.objects.filter(user=request.user) return render(request, 'library.html', {'user_books': user_books}) def add_book(request, book_id): book = Book.objects.get(id=book_id) user_book = UserBook.objects.create(user=request.user, book=book) return redirect('library') myapp/urls.py '''Defines the urls for the library application''' from django.urls import path from . import views app_name = 'library' urlpatterns = [ #homepage path('', views.index, name='home'), path('library/', views.library, name='library'), path('add_book/<int:book_id>/', views.add_book, name='add_book'), ] traceback Traceback (most recent call last): File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/urls/resolvers.py", line 740, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/in/Desktop/ArenaStudy/manage.py", line 22, in <module> main() File "/Users/in/Desktop/ArenaStudy/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/in/.local/share/virtualenvs/ArenaStudy-g4tNO7nf/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) … -
My custom templatetag is not working. The output is empty
Here's the folder structure: homepage (this is the Django app) | |templatetags | __init__.py | shamsi_tags.py The content of shamsi_tags.py: from datetime import datetime from django import template from jdatetime import datetime as jdatetime register = template.Library() @register.simple_tag def shamsi_date(): """ This template tag returns the current date in Shamsi format. """ now = datetime.now() shamsi_date = jdatetime.fromgregorian(now.year, now.month, now.day) return shamsi_date.strftime('%Y/%m/%d') The index.html: {% load shamsi_tags %} ... <div>{{ shamsi_date }}</div> ... And nothing displays. I check the page source and it shows <div></div>. The rest of the page is displaying correctly so I guess there's nothing wrong with the URL or view. Obviously jdatetime is installed. It is Django 5.0.6 on Windows. I'm sure this is something easy but I can't figure it out. -
Validation of old standard Brazilian and Mercosur vehicle license plates in Django
I'm trying to validate Brazilian boards in Django (Python) for both the old ABC2546 standard and the Mercosul ABC1A35 standard. But when I type the Mercosur standard on the invalid plate. def validate_placa(placa): """ Valida se a placa do veículo está no formato correto. Args: placa (str): A placa do veículo a ser validada. Returns: None se a placa for válida, uma mensagem de erro se não for. """ placa_regex = r'^[A-Z]{3}-[0-9]{4}$|^([0-9]{3})-([0-9]{3})([A-Z]{1})$' # Formato: ABC-1234 validator = RegexValidator(regex=placa_regex, message='Placa inválida.') try: validator(placa) except ValidationError as error: return error.message class ClienteForm(forms.ModelForm): class Meta: model = Cliente fields = '__all__' veiculo_placa = forms.CharField( validators=[validate_placa], max_length=8, error_messages={'required': 'Placa é obrigatória.'} ) def validate_data(self, data): cleaned_data = super().validate_data(data) veiculo_placas = self.data.getlist('veiculo_placa') for placa in veiculo_placas: error_message = validate_placa(placa) if error_message: self.add_error('veiculo_placa', error_message) return cleaned_data I need to validate both standards -
I have problem whe loading this page in django project
enter image description here- it shows like this when i run the program I tried to change the model i created; in the model image_url with charset changed to image with imageset....( i did migrate though) but when I run the code took this then it shows like this -
How to display average ratings in the form of stars in django
I want to display the average rating on a product in the form of stars where i want to have 5 stars and then fill the stars with gold color on how much the average rating on the product is. This is my code and my relation b/w models class Product(models.Model): name = models.CharField(max_length=300) price = models.DecimalField(max_digits=7, decimal_places=2) image_url = models.CharField(max_length=400) digital = models.BooleanField(blank=False) sizes = models.ManyToManyField(Size, through='ProductSize') quantity = models.IntegerField(default=1) def __str__(self): return self.name @property def get_average_rating(self): average = self.comment_set.aggregate(Avg('rating'))['rating__avg'] if average is not None: return round(average, 1) else: return 0 class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) text = models.TextField() image = models.ImageField(upload_to='images/comment_images', null=True, blank=True) created_on = models.DateField(auto_now_add=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) I tried to run a loop like this but it did not work as the average rating is in float I do not know much javascript so if you can help me in js that will be appreciated too thank you!! {% for _ in product.get_average_rating %} &#9733; {% endfor %} -
Django Choices model field with choices of classes
The following code was working in python 3.10 but not in 3.11 due to a change in the enum module. Now the app won't launch with the following error message : File "/home/runner/work/e/e/certification/models.py", line 3, in <module> from .certifications.models import Certification, QuizzCertification # noqa: F401 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/runner/work/e/e/certification/certifications/models.py", line 17, in <module> class CertificationType(models.TextChoices): File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/site-packages/django/db/models/enums.py", line 49, in __new__ cls = super().__new__(metacls, classname, bases, classdict, **kwds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 560, in __new__ raise exc File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 259, in __set_name__ enum_member = enum_class._new_member_(enum_class, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 1278, in __new__ raise TypeError('%r is not a string' % (values[0], )) TypeError: <class 'certification.certifications.models.QuizzCertification'> is not a string How would you implement a model field with choices, where the first element is a Model class? class QuizzCertification(models.Model): ... class OtherCertification(models.Model): ... class CertificationType(models.TextChoices): QUIZZ = QuizzCertification, "Quizz" OTHER = OtherCertification, "Other" class Certification(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(_("Description"), blank=True, null=True) type_of = models.CharField( _("Type of certification"), max_length=100, choices=CertificationType, default=CertificationType.QUIZZ, ) -
i have this error on my django app i tried every solution possible but it remains the same
so im trying to build a realtime chat application for my college project and i used django because i heard that its preety flexible to use as webframewoke app but since i started i kept facing errors, i had a solution for most of them but i got stuck in this error so i need help #forms.py from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.models import User from django.db import models from django import forms class SignupForm(UserChangeForm): class Meta: model = User fields = ['username', 'password1', 'password2'] #urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('members/', views.members, name='members'), path('', views.frontpage, name='frontpage'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='members\login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), ] #views.py from django.contrib.auth import login from django.shortcuts import render, redirect from .forms import SignUpForm def frontpage(request): return render(request, 'members\frontpage.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() login(request) return redirect('frontpage') else: form = SignUpForm() return render(request, 'members/signup.html', {'form': form}) #models.py from django.db import models from django.contrib.auth.models import User class User(models.Model): username = models.CharField(max_length=255, blank= True, editable=True) password1 = models.CharField(max_length=30, null=True, blank=True, editable= True) password2 = models.CharField(max_length=30, null=True, blank=True, editable= True) #the error message Exception in … -
Best Solution for connecting to 2 diffreent databases with 2 diffrent access in Django by using ORM or query Script
I want to connect my django project to 2 diffrent databases, one of them is MS-SQL with read-only access and the other is a PostgreSQL with full access what I want to do is read from the MS-SQL by using celery beat and write the aggrigated data on the Postgres what is the best solution to update my Postgres DB with the most performance? What is the most sample way which is already said in django documentation is this: https://docs.djangoproject.com/en/5.0/topics/db/multi-db/ I want to know that is if i use router.py file is better of just create an API which I read the some functions as a python script which are contatains the SQL query and insert or update them into the PostgreSQl What is the best solution? -
Custom save() method not working any more in Django 5.0.4
I have this custom save() method in mt admin.py: def save_model(self, request, obj, form, change): if obj._state.adding: obj.added_by = request.user return super().save_model(request, obj, form, change) After a recent update this is not working any more; indeed, when I hit 'save' on the backend I get no errors and the data is not saved on the database. It has worked until a recent update (I think up until 5.0.2). -
What is the Django logic flow to show pdf inside HTML template after click the given link
I'm using Django to create a website to public my post, all of my post is pdf. As usual, I defined my view and view logic, it returns a context dictionary views.py class PageView(TemplateView): def get_context_data(self): context = super().get_context_data(**kwargs) highlightObject = Post.objects.filter(is_highlight = 1).order_by('-created_on') context['highlight'] = highlightObject return context Then, on my html file {% extends "base.html" %} {% for row in highlight %} <h3 class="mb-auto">{{ row. Title }}</h3> <div class="btn-group"> <a href="{{ row.pdfFile.url }}" class="icon-link">Reading more</a> </div> {% endfor %} Until now, when cliking on the "Reading more", it changes to pdf Viewer, but I want to show pdf viewer inside html template, for example, it should change to other html file which extend the template from base.html and show pdf viewer using path row.pdfFile.url So, how to write a new html file for reading pdf from directory row.pdfFile.url Or, if there is any other way to solve this problem. Thanks -
Custom User Model having ForeignKey to Customer with dj-stripe
I would like to have a Custom User Model in my django application, featuring a column to hold reference to Customer objects coming from stripe, being synced via dj-stripe. So my approach was to extend as follows: from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class StripeUserModel(AbstractUser): objects = UserManager() customer = models.ForeignKey("djstripe.Customer", null=True, blank=True, on_delete=models.SET_NULL) Setting the standard django User model to: AUTH_USER_MODEL = "billing_stripe_app.StripeUserModel" When I start with a clean new database by deleting the SQLite file and running python manage.py makemigrations, I observe following error: django.db.migrations.exceptions.CircularDependencyError: billing_stripe_app.0001_initial, djstripe.0001_initial, djstripe.0008_2_5, djstripe.0009_2_6, djstripe.0010_alter_customer_balance, djstripe.0011_2_7 Without the customer field in StripeUserModel, everything works. I wonder how to resolve this. I have run into circular dependency in Python before. It completely makes sense. In my application (billing_stripe_app), I reference dj-stripe customer field. And apparently this one relies on the AUTH_USER_MODEL user model itself again, creating that circular dep, as can be seen from the djstripe migration file 0001_initial.py (excerpt below). ... DJSTRIPE_SUBSCRIBER_MODEL: str = getattr( settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL ) # type: ignore # Needed here for external apps that have added the DJSTRIPE_SUBSCRIBER_MODEL # *not* in the '__first__' migration of the app, which results in: # ValueError: Related model 'DJSTRIPE_SUBSCRIBER_MODEL' … -
no item provider dropdown while adding social application to django admin
Django Admin PanelI'm currently learning web development with django and while trying to add soial authentication to my project with django-allauth i was met with an error saying invalid configuration after loading the social account tag and creating a link with the provider login url tag, I though it was because i hadn't added the social applications to the django admin yet so i tried that, i went to sites and added 127.0.0.1:8000 as my link with google as the name but when i tried to add the social application, there was no item in the dropdown menu where i'm normally supposed to select a provider even though i added the allauth.socialaccount.providers for google, faceboook and microsoft my settingss.py--> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #Third-Party 'allauth', 'allauth.account', "allauth.socialaccount", "allauth.socialaccount.providers.google", 'allauth.socialaccount.providers.microsoft', 'allauth.socialaccount.providers.facebook', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'EMAIL_AUTHENTICATION': True, 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'OAUTH_PKCE_ENABLED': True, } } LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT = 'home' #allauth config SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = "none" EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' urls.py --> urlpatterns = [ #admin path('admin/', … -
Django Mediapipe application: how to manage delays in realtime video processing?
I'm developing a Django application which opens the client camera via JS using navigator.MediaDevices.getUserMedia(), send a blob to the server through websocket and then the server should process the images through mediapose library. I'm using the following three functions respectively to: convert blob to cv image def blob2image(bytes_data): np_data = np.frombuffer(bytes_data, dtype=np.uint8) img = cv2.imdecode(np_data, cv2.IMREAD_COLOR) if img is None: raise ValueError("Could not decode image from bytes") return img extract markers from the img def extractMarkers(image, pose, mp_drawing, custom_connections): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = pose.process(image) mp_drawing.draw_landmarks( image, results.pose_landmarks, connections = custom_connections, ) return image, results convert back the annotated image to b64_img def image2b64(img): _, encoded_image = cv2.imencode('.jpg', img) b64_img = base64.b64encode(encoded_image).decode('utf-8') return b64_img The code runs, but keeps accumulating delay during the streaming. Is there any way to drop the buffer or to improve the performance of the code? I tried locally the code for extracting markers extractMarkers(), without using the Django server application getting images coming from a local camera and it works smootly. I also tried to use the Django application to get the images from the client and sending them to the server through websocket and then only sending back to the client the images … -
Web application using gunicorn in nginx server not working
I had 3 apps in a server running on Ubuntu 22.04. The first one was a Django app, the second a Flask appp under a subdomain and the third one a FastAPI under another subdomain. When I tried to add a fourth one (Flask) I don't know how I messed up but now none of them work. All the apps run perfectly in my computer. When I try to access the page through the browser in my computer it returns ERR_CONNECTION_REFUSED and when accessing throught my phone it returns a 502 Bad Gateway nginx/1.18.0 (Ubuntu) error. The first one doesn't log anything in the nginx's error.log but the second one does. My current server config is as follows: server { server_name host.es www.host.es; location ~ /\.ht { deny all; } location ~/\.git { deny all; } location = /favicon.ico { access_log off; log_not_found off; } location /media { alias /var/www/host.es/myapp/media; } location /static { alias /var/www/host.es/myapp/static; } location / { include proxy_params; proxy_pass http://unix:/run/myapp.sock; } # The next configuration applies to the 3 subdomain apps location /subdomain1 { include porxy_params; proxy_set_header SCRIPT_NAME /subdomain1; proxy_pass https://unix:/run/mysecondapp.sock; } } server { if ($host = www.host.es) { return 301 https://$host$request_uri; } if ($host … -
i have used to google provider in social auth in django but provider is not showing in django template
social app this provider name is not showing at provider field i am a new django developer. Now i used to Authentication using Social auth. When i used this code everythin ok but not working right now. i try to several time but not working. i have used this : INSTALLED_APPS = [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ]` MIDDLEWARE = [ 'allauth.account.middleware.AccountMiddleware', ] SITE_ID = 1 LOGIN_REDIRECT_URL='/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, } } -
Issue Adding "django.contrib.gis" to INSTALLED_APPS in Django
I'm currently developing an application using Django and aiming to integrate geospatial functionalities by adding "django.contrib.gis" to my project's INSTALLED_APPS. However, upon adding this module to INSTALLED_APPS in the settings.py file, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal307", "gdal306", "gdal305", "gdal304", "gdal303", "gdal302", "gdal301", "gdal300", "gdal204"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings Despite having the GDAL library installed in the directory C:\Program Files\PostgreSQL\16\gdal-data, specifying the GDAL_LIBRARY_PATH in the settings.py file doesn't seem to resolve the issue. Additionally, I have installed PostGIS via the Application Stack Builder in PostgreSQL. I'm seeking guidance on how to resolve this issue and successfully integrate "django.contrib.gis" into my Django project. Any insights or suggestions would be greatly appreciated. Thank you! -
RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS
when running python3 manage.py crontab run i get the above error error detials Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/crontab.py", line 126, in run_job job = self.__get_job_by_hash(job_hash) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/crontab.py", line 171, in __get_job_by_hash raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! aise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! can anyone please help me to fix this error. i am using ubuntu as os django as a framework. raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! can anyone please help me … -
How to send form data from frontend ReactJS to backend Django?
Here I want to send products values to the backend Django as Django have multi Serializers But i think i have sent proper formatted value data also i am getting error Please help me. class ProductSerializer(serializers.ModelSerializer): product_size = ProductSizeSerializer(many = True) product_color_stock = ProductSizeSerializer(many = True) product_image = ProductSizeSerializer(many = True) class Meta: model = Product fields = ["user","category","Slug","Name","size_Description","color_Description","Description","Main_Image","Banner","Rating","Date","archive","product_color_stock","product_size","product_image","secret_key"] extra_kwargs = { 'user': {'read_only': True}, 'Slug': {'read_only': True}, 'Rating': {'read_only': True}, 'Date': {'read_only': True}, 'product_color_stock': {'read_only': True}, 'product_image': {'read_only': True}, 'product_size': {'read_only': True}, 'secret_key':{'read_only': True}, } This is the Submit function that is sent from next js to django const handleSubmit = async (event) => { event.preventDefault(); const products = new FormData(); const times = 1; const secret_details = "details" + times ; const secret_size = "size" + times ; const secret_color_stock = "color_stock" + times ; const secret_img = "image" + times ; products.append("secret_key", secret_details); products.append("user", parseInt(2)); Object.keys(p_details).forEach((key) => products.append(key, p_details[key])); var parentObj = {}; for (var key in p_imgs.Image) { if (p_imgs.Image.hasOwnProperty(key)) { var file = p_imgs.Image[key]; var nameWithKey = p_imgs.Name + "[" + key + "]"; var obj = { "Name": nameWithKey, "user": 2, "image": file, "secret_key": secret_img }; parentObj[nameWithKey] = obj; } } products.append('product_image', JSON.stringify(parentObj)); parentObj … -
Internal Server Error when Querying Orders: ValueError Must be User instance
I encountered an Internal Server Error while querying orders in my Django application. The error message indicates a ValueError: "Must be User instance." This occurs when filtering orders by customer_id. I'm developing a Django application where users can place orders. I have models for Order, Customer, and User. Each order is associated with a customer, and customers are linked to users through a foreign key relationship. I have a viewset to handle order queries, and I'm trying to filter orders based on the customer_id. However, when attempting to filter, I encounter a ValueError stating that it must be a User instance. 1.Reviewed the models and viewset code to ensure proper relationships and filtering. 2.Checked the queryset and filtering logic in the viewset's get_queryset method. 3.Examined the Customer and User models to verify the foreign key relationship. -
Can't connect Django server to Cassandra DB (AstraDB)
I've hosted my Cassandra DB on AstraDB and am trying to connect my Django server to it. This is the first time I'm working with Django too so I'm a bit confused on how it works. In my settings.py file, this is my code from pathlib import Path from cassandra import ConsistencyLevel from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider import os from dotenv import load_dotenv import dse load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECURE_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogs', 'graphene_django', ] INSTALLED_APPS = ['django_cassandra_engine'] + INSTALLED_APPS SESSION_ENGINE = 'django_cassandra_engine.sessions.backends.db' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'core.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': … -
Why can docker not find my file when I run docker compose up
I have a Django application for the backend and a Vue application for the frontend. The app works 100% on my local machine. I am trying to dockerize the application so I can deploy it on a VPS just for someone to look at. The front end starts up when I run docker compose up but the back end gives me the same error every time: python3: can't open file '/app/manage.py': [Errno 2] No such file or directory My directory structure is as follows: back (directory) ... (django apps directories) -- manage.py -- Dockerfile -- requirements.txt front (directory) ... (vue directories) -- Dockerfile -- package.json -- vite.config.js -- index.html Here is my Dockerfile for the backend: FROM python:3.10 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . back EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Here is my Dockerfile for the front end: FROM node:20-alpine3.17 WORKDIR /app COPY package.json /app/ RUN npm install COPY . front/ EXPOSE 8080 CMD ["npm", "run", "dev:docker"] and here is my docker-compose.yml file: version: "1.1" services: db: image: postgres:15-alpine volumes: - ./db:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres back: build: ./back ports: - "8000:8000" volumes: - ./:/back env_file: ./back/.env command: …