Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my Django database flush command not working?
I've been chasing an error message regarding the python manage.py flush command for several weeks. When I issue the command and confirm the flush....I get... CommandError: Database my_app_db couldn't be flushed. Possible reasons: The database isn't running or isn't configured correctly. At least one of the expected database tables doesn't exist. The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run. After chasing...upgrading various components...trying several different avenues....I still can't figure this out. -
Django: How to get tax amount for diffrent countries and multiply it by product price in django?
I am creating an ecommerce system where i would need to calculate taxes for diffrent countries during checkout. I have added a flat rate for the tax, but that is not how tax works, it need to be percentage based which i have done, but how do i know the country a user is about to order a product from and also get the tax amount for that country and do my basic calculation. please if you have done this before i would really appreciate any help as that would help me fix this issue. Right now, this is how i am performing the tax calculation with a fixed percentage for all users from all countries new_tax_amount = 0 tax_amount_by_percentage = 25 / 100 # 25% / 100 = 0.25 new_tax_amount += int(item['qty']) * float(tax_amount_by_percentage ) This works well for me, but i need to know how to get tax percentage based on the country the user is trying to order the product from -
Filter the swagger endpoints using tags when using drf_yasg in Django
When I generate the swagger ui using the default schema provided by documentation, it generates both api, api2 endpoints.I want to get only the api endpoints. I tried overriding the get_schema method as below but didn't work. class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, *args, **kwargs): """Generate a :class:`.Swagger` object with custom tags""" schema = super().get_schema(*args, **kwargs) schema.tags = [ { "name":"api" } ] return schema schema_view = get_schema_view( openapi.Info( title="API docs", default_version='v1', description="REST API", ), generator_class=CustomOpenAPISchemaGenerator, public=True, permission_classes=[permissions.AllowAny], ) Can someone give me a solution to get only the endpoints with tag of api? -
Forbidden (CSRF cookie not set.) - Django & React Web App
Any ideea why I get this error when trying to register an user? # views.py class SignupView(APIView): permission_classes = (permissions.AllowAny,) @method_decorator(csrf_protect) def post(self, request): try: data = request.data username = data.get('username') email = data.get('email') password = data.get('password') confirm_password = data.get('confirmPassword') if password != confirm_password: return Response({'error': 'Passwords do not match'}, status=status.HTTP_400_BAD_REQUEST) if User.objects.filter(username=username).exists(): return Response({'error': 'Username already exists'}, status=status.HTTP_400_BAD_REQUEST) user = User.objects.create_user(username=username, password=password) user_profile = UserProfile(user=user, email=email) user_profile.save() return Response({'success': 'User created successfully'}, status=status.HTTP_201_CREATED) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) """ # settings.py Django settings for daweb_project project. Generated by 'django-admin startproject' using Django 4.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # 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/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-_i9x#yg#qq9!#&uw3e7$86&#w%g1t)%ft@ebfv3$ai*x+%a137' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'RealEstateApp.apps.RealestateappConfig' ] CORS_ORIGIN_ALLOW_ALL = True MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', … -
Is it possible to configure CSRF_TRUSTED_ORIGINS in Django 4 to allow access from any IP address?
I have found several posts regarding this but did not find what I need. I have upgraded Django from 2.x to 4.x for an Angular/Django web app which will be packaged and distributed to users that will install in different hosts and domains. MOST IMPORTANTLY, they would need to access the app from multiple locations on a serving port via browser (i.e. HTTP://whereAppIsInstalled:PORT). This used to work in Django 2 used to work without CSRF_TRUSTED_ORIGINS and with the settings below: ALLOWED_HOSTS = ['*',] CORS_ORIGIN_ALLOW_ALL = True All the answers say that I need to add those hosts, IPs, or subdomains to the CSRF_TRUSTED_ORIGINS list in settings.py. This works, but impractical in my case since I don't know all the hosts and IPs. I also noticed in Django documentation that we could add "HTTP://..." to CSRF_TRUSTED_ORIGINS, but this does not seem to work. I have to explicitly list all the IPs of the machines I am using to access the app. What should I do in this situation? How do I make sure that my app allows requests from all IPs? -
Djano: how to update order tracker model using Django?
I am trying to build an order tracker using django, to track the delivery status and location of a order made by a buyer. i have a model that look like this class OrderTracker(models.Model): order_item = models.ForeignKey('store.CartOrderItem', on_delete=models.SET_NULL, null=True, related_name="cartorderitem_tracker") status = models.CharField(max_length=5000, null=True, blank=True) location = models.CharField(max_length=5000, null=True, blank=True) activity = models.CharField(max_length=5000, null=True, blank=True) date= models.DateField(auto_now_add=True) def __str__(self): return self.order_item When an order gets placed, the status of the OrderTracker changes to shipping. How do i update the location with the current location where the order is crrently and also the activity (activity is something like: "Left Warehouse") Should this is updated manully by the vendor in the dashboard, or do i need like an API to implement this feature -
How to make an app that Django Rest Framework Filter and Django-Filter with ModelViewSet
When I use generics ListAPIView filter and order departs are working but if I use ModelViewSet it is not working. I added my code examples. How can I fix this problem? Thanks in advance class MovieViewSet(generics.ListAPIView): queryset = Movie.objects.all().order_by('movie_id') serializer_class = serializers.MovieDetailSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] authentication_classes = [authentication.BasicAuthentication] # FILTER AND ORDER: filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter] filterset_fields = ['category', 'director', 'country'] search_fields = ['category__name', 'director__name', 'name'] ordering_fields = ['production_year', 'imdb', 'duration'] It is working! class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all().order_by('movie_id') serializer_class = serializers.MovieDetailSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] authentication_classes = [authentication.BasicAuthentication] # FILTER AND ORDER: filter_backends = [django_filters.DjangoFilterBackend, filters.OrderingFilter, filters.SearchFilter] filterset_fields = ['category', 'director', 'country'] search_fields = ['category__name', 'director__name', 'name'] ordering_fields = ['production_year', 'imdb', 'duration'] def list(self, request, **kwargs): queryset = Movie.objects.all().order_by('name') serializer = MovieSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk): queryset = Movie.objects.all() movie = get_object_or_404(queryset, pk=pk) serializer = serializers.MovieDetailSerializer(movie) return Response(serializer.data) def has_permission(self, request, **kwargs): if request.METHOD in permissions.SAFE_METHODS: return True else: return request.user.is_staff() It is not working!! -
How to find duplicates of django model on two fields?
Consider this django model setup: from django.db import models class Foo(models.Model): field_foo = models.CharField(max_length=20, null=False, blank=False, unique=True,) class Bar(models.Model): field_bar = models.CharField(max_length=20, null=False, blank=False, unique=True,) class Foobar(models.Model): field_foo = models.ForeignKey(foo,on_delete=models.CASCADE) field_bar = models.ForeignKey(bar,on_delete=models.CASCADE) I want to look for two rows that have the same field_foo and field_bar values. I can do this manually, but I want to know if there is a feature of django that takes care of that. The way I do this now is: for f in Foo.objects.all(): for b in Bar.objects.all(): fb = Foobar.objects.filter(foo=f, bar=b) if len(fb)>2: something='do' -
Using Pagination with JsonResponse
I'm currently working on CS50W Network project which is basically a social media clone. I want to get different objects via a fetch API request, which is working fine. But after I implemented Pagination I get a 404 not found. When The DOM of the index page is loaded I call the getPosts function passing in 'all' as the username and currentPage document.addEventListener('DOMContentLoaded', function() { // By default, getPosts getPosts('all', currentPage); }); let currentPage = 1; const itemsPerPage = 10; function getPosts(username, page) { // Make a GET request to the API endpoint fetch(`/get_post/${username}/?page=${page}&per_page=${itemsPerPage}`) .then(response => response.json()) .then(data => displayPosts(data.data)) .catch(error => console.error(error)); } the path for the API is: path("get_post/<str:username>", views.get_post, name="all_posts"), My view function to get the requested Posts and handle the Pagination: @login_required def get_post(request, username): # get all posts if username == "all": posts = Post.objects.all() elif username == "following": posts = Post.objects.exclude(user=request.user) else: # get user user = User.objects.get(username=username) posts = Post.objects.filter(user=user) # change button color for post in posts: if post.likes.filter(id=request.user.id).exists(): post.liked = True post.save() else: post.liked = False post.save() # order posts in reverse chronological order posts = posts.order_by("-timestamp").all() # Get the current page number and the number of items per page from … -
Django not submitting and updating form data
I can't seem to figure out why Django is not submitting form data to update the user profile. Profile.html should be reflecting the newly updated input data (i.e., first_name, last_name) from Edit-profile.html. forms.py class EditUserProfile(forms.ModelForm): first_name = forms.CharField(max_length=50, required=False) last_name = forms.CharField(max_length=50, required=False) phone_number = forms.CharField(max_length=20, required=False) email = forms.EmailField(max_length=100, required=False) address = forms.CharField(max_length=150, required=False) city = forms.CharField(max_length=50, required=False) state = forms.CharField(max_length=50, required=False) zip_code = forms.CharField(max_length=10, required=False) username = forms.CharField(max_length=30, required=False) password = forms.CharField(widget=forms.PasswordInput, required=False) credit_card_number = forms.CharField(max_length=16, required=False) expiration_date = forms.DateField(required=False) cvv = forms.CharField(max_length=3, required=False) class Meta: model = User fields = ['first_name', 'last_name', 'phone_number', 'email', 'address', 'city', 'state', 'zip_code', 'username', 'password', 'credit_card_number', 'expiration_date', 'cvv'] def save(self, commit=True): user = super(EditUserProfile, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.city = self.cleaned_data['city'] user.state = self.cleaned_data['state'] user.zip_code = self.cleaned_data['zip_code'] user.username = self.cleaned_data['username'] user.password = self.cleaned_data['password'] user.credit_card_number = self.cleaned_data['credit_card_number'] user.expiration_date = self.cleaned_data['expiration_date'] user.cvv = self.cleaned_data['cvv'] if commit: user.save() return user views.py @login_required def edit_profile_page(request): form = EditUserProfile(initial={ 'first_name': request.user.first_name if hasattr(request.user, 'first_name') else '', 'last_name': request.user.last_name if hasattr(request.user, 'last_name') else '', 'phone_number': request.user.phone_number if hasattr(request.user, 'phone_number') else '', 'email': request.user.email if hasattr(request.user, 'email') else '', 'address': request.user.address if hasattr(request.user, 'address') else '', 'city': request.user.city if hasattr(request.user, 'city') else '', … -
Why does jQuery script behave differently in webpack?
As a learning exercise I'm attempting to reproduce a PHP\Symfony project in Python\Django. While working in Django I rewrote a jQuery script that I think is more effective than what I used in Symfony. Oddly, the identical script (i.e., copied & pasted) does not perform the same as in Django. Here's the script and an outline of what it does. The page on which the script operates contains two versions of the same table. One side is the food that is "assigned" to a meal. The other side has the food items available to be added to the meal. When the page is rendered it receives a JSON array of data attributes of foods already assigned to the meal. The script steps through the assigned table, hiding the table rows of food not assigned. It also hides the table rows of food items available that are assigned. The script: var rArray = JSON.parse($("#rte").text()); $("table#ready_foods tbody tr").each(function () { f = $(this).find('td').data('foodid'); if (rArray.indexOf(f) == -1) { $(this).toggle(); } else { $("table#meal_pantry tbody tr td[data-foodid=" + f + "]").parent().toggle(); // never executed } }); In Symfony, the else statement is never executed. So regardless of the foods already assisgned, that table's … -
How to print actual number when using Aggregate(Max()) in a Django query
I have the following query set: max_latitude = Model.objects.aggregate(Max('latitude')) When I print it, it returns {'latitude__max': 51.6639002} and not 51.6639002. This is causing a problem when I want to add the latitudes together to calculate an average latitude. If I do print(max_latitude.latitude) (field of Model object) I get the following: error:'dict' object has no attribute 'latitude' How can I extract the actual number given from the queryset? -
How to use django channel to create a game lobby and matchmaking
I am using django channels to create a 2-player game like Tic Tac Toe or checkers. My main issue is how I can preserve the state of the players that joined the lobby waiting to be paired. Would this be something I need to do in the connect method in the channel consumer? If not what if the approach here? -
Download an xlrd book as an excel file throught a django view
I need to download an excel file generated in memory using the xlrd library thought a django view as a direct download. I'm trying the following but I don't know how to convert the book object into something I can include in the HttpResponse from django.http import HttpResponse from xlrd import Book def my view: ... book: Book = <CREATED WITH XLRD> response = HttpResponse(book, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="file.xls"' return response -
Django, Broken pipe from ('127.0.0.1', 55301)
I am encountering this problem when making fast requests for a Django == 4.0.5 project that I am still developing: [11 / Apr / 2023 18:50:14,703] - Broken pipe from ('127.0.0.1', 55300). I have 1 video on my page and it takes up 3mb. However, when I make quick transitions between pages, i.e. when I create too many requests, a spinner appears and it takes time for the video to load. I am using Django DEBUG True and not using any Nginx or WSGI Server. What is the solution? -
how to generalize query with more of two dates in ArrayField(models.DateTimeField()) field?
I have a Model: from django.contrib.postgres.fields import ArrayField class MyClass(models.Model): some_field = ArrayField(models.DateTimeField(), default=list) And have this query to filter for objects that has at least one of the date inside a range: date_range_for_reminders_check = [yesterday.date(), timezone.now().date()] MyClass.objects.filter(( Q(some_field__0__date__range=date_range_for_reminders_check) | Q(some_field__1__date__range=date_range_for_reminders_check) )) But this worked when every row of MyClass had only two dates in some_field, nowadays these may have more dates and need to be generalized take account diferent quantity of dates so i need something like: date_range_for_reminders_check = [two_days_ago.date(), timezone.now().date()] MyClass.objects.filter(( Q(some_field__0__date__range=date_range_for_reminders_check) | Q(some_field__1__date__range=date_range_for_reminders_check) | Q(some_field__2__date__range=date_range_for_reminders_check) | ... Q(some_field__X__date__range=date_range_for_reminders_check) | )) but without specifying indexs. -
Django Returning Items outside filter when filtering by time
I have a snippet of code designed to grab the entries that are <24 hours old yesterday = datetime.now() - timedelta(days=1) items = get_model(name=p).objects.filter(tagid=tag.id, t_stamp__gt=yesterday).order_by('t_stamp') for i in items: print(f'{i.t_stamp} - {i.t_stamp > yesterday}') print(yesterday) Yet for some reason, it returns 2 items, when it should return 0. Results of the print statement above: 2023-04-06 13:12:54.540000 - False 2023-04-06 14:12:46.976000 - False 2023-04-10 10:06:27.526066 As you can see, the timestamp is NOT greater than yesterday, so why is it being returned? -
django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.33). in Django
I have this error when performing migrations to my file command I tried this command python manage.py makemigrations but Error insist django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.33). Is there anyway to perform migration? or should I downgrade my python version to v.9? python version python v.3.10 -
Custom fonts working on development but not in production django
I have a project I'm working on that's hosted on Digital Ocean's app platform. In development my locally stored fonts work just fine. As soon as I load my project on Digital Ocean they no longer work. I use Digital Ocean's spaces for static files and uploaded files. My CSS looks like this: /* Fonts */ @font-face { font-family: 'canto'; src: url('../fonts/Canto-Bold.woff2') format('woff2'); } @font-face { font-family: 'Poppins'; src: url('../fonts/Poppins-Light.woff2') format('woff2'); } @font-face { font-family: 'canto-roman'; src: url('../fonts/Canto-Roman.woff2') format('woff2'); } @font-face { font-family: 'poppins-bold'; src: url('../fonts/Poppins-SemiBold.woff2') format('woff2'); } My folder structure looks like this: -Project --app --app --templates --media --static ---static/CSS -> .CSS file ---static/fonts/ font files All other files work fine, just the fonts don't. I've tested this with two seperate computers. Neither one has the fonts installed. Did I miss something? -
How to implement change in transfer_pin and receive an OTP
I am currently working on an application and using Django for the backend. It's a payment platform that requires a transfer_pin which can be reset or changed for security reasons by the user. When a user change the transfer_pin, an otp is sent to him/her to confirm he is the owner of the account. Below is what I have been able to do but I am having this error from Twillo that says: Unable to create record: The number is unverified. I will appreciate it if someone can help. I feel I am not doing something right. class TransferPin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) transfer_pin = models.CharField( max_length=100, null=True, blank=True, validators=[ RegexValidator(regex="^\d{4}$", message="PIN must be a 4-digit number.") ], ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def save(self, *args, **kwargs): self.transfer_pin = make_password(self.transfer_pin) super().save(*args, **kwargs) # This method checks if the pin matches the hashed pin in the TransferPin instance. def verify_pin(self, pin): return check_password(pin, self.transfer_pin) class TransferPinChangeSerializer(serializers.ModelSerializer): transfer_pin = serializers.CharField(max_length=4) class Meta: model = TransferPin fields = ['transfer_pin'] def create(self, validated_data): otp = random.randint(100000, 999999) # otp_expire = datetime.now() + timedelta(minutes=10) phone_number = self.context['request'].user.phone_number user = self.context['request'].user try: pin = TransferPin.objects.get(user=user) except TransferPin.DoesNotExist: pin = TransferPin(user=user) pin.transfer_pin = validated_data["transfer_pin"] pin.save() … -
NoReverseMatch at /processor/quantum-computing/ Reverse for 'post_detail'
I have a django blog site, but when a user adds a comment,the page returns an error page instead of the commented post. NoReverseMatch at /processor/quantum-computing/ Reverse for 'post_detail' with keyword arguments '{'slug': 'quantum-computing'}' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] URLs.py urlpatterns = [ path('search/', views.search, name='search'), path(r'<slug:category_slug>/<slug:slug>/', views.detail, name='post_detail'), path('<slug:slug>/', views.category, name='category_detail'), ] Models.py class Post(models.Model): ACTIVE = 'active' DRAFT = 'draft' CHOICES_STATUS = ( (ACTIVE, 'Active'), (DRAFT, 'Draft') ) category = models.ForeignKey(Category, related_name='posts', on_delete=models.CASCADE) title = models.CharField(max_length=255) slug = models.SlugField() intro = models.TextField() body = HTMLField() created_at = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=10, choices=CHOICES_STATUS, default=ACTIVE) image = models.ImageField(upload_to='uploads/', blank=True, null=True) class Meta: ordering = ('-created_at',) def __str__(self): return str(self.title) def get_absolute_url(self): return '/%s/%s/' % (self.category.slug, self.slug) Here is a look at my views.py file where after user posts comment, the user should be redirected to the post. Views.py def detail(request, category_slug, slug): post = get_object_or_404(Post, slug=slug, status=Post.ACTIVE) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', slug=slug) else: form = CommentForm() -
django views the cartItems which is called from Models is showing error
hello I'm trying to get cartitems from models with related name and the cartitem is getting error in views what so i do ? here is my view-- def cart(request): cart = None cartitems = [] if request.user.is_authenticated: cart, created = Cart.objects.get_or_create(user=request.user, completed=False) cartitems= cart.cartitems.all() context = {"cart": cart, "items": cartitems} return render(request, "cart.html", ) def add_to_cart(request): data = json.loads(request.body) products_id = data["id"] products = Product.objects.get(id=products_id) if request.user.is_authenticated: cart, created = Cart.objects.get_or_create(user=request.user, completed=False) cartitem, created = CartItem.objects.get_or_create(cart=cart, products=products) cartitem.quantity += 1 cartitem.save() print(cartitem) return JsonResponse('it works', safe=False) Models.py--- class Cart(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return str(self.id) class Meta: db_table = 'hatkesh_cart' class CartItem(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE , related_name='items') cart = models.ForeignKey(Cart, on_delete= models.CASCADE, related_name='cartitems') quantity = models.IntegerField(default=0) def __str__(self): return self.products.title class Meta: db_table = 'hatkesh_cartitems' and the error is------ `Cannot access member "cartitems" for type "Cart" Member "cartitems" is unknown` error is coming from views.py I have tried different related names but it still not works !! I was trying to call cart items to cart -
Cant' start gunicorn for a django project, due to failed (Result: resources) error
I can't figure out what's wrong. Spend almost 2 days on this error and I am not able to find if it is a typo or concept mistake. I want to mention that the app started perfectly using `python3 manage.py runserver 0.0.0.0:8080. My environment is on this path: home/paul/env My project directory is on this path: home/paul/project wsgi file is on this path: home/paul/project/application gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=paul Group=paul # i also used www-data WorkingDirectory=/home/paul/project ExecStart=/home/paul/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ application.wsgi:application [Install] WantedBy=multi-user.target When I run sudo systemctl status gunicorn.socket, as you can see below everything looks fine, enabled, active. ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; preset: enabled) Active: active (listening) since Tue 2023-04-11 12:31:59 UTC; 32min ago Until: Tue 2023-04-11 12:31:59 UTC; 32min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket But when I run sudo systemctl status gunicorn it fails. × gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; preset: enabled) Active: failed (Result: resources) TriggeredBy: ● gunicorn.socket CPU: 0 The error make you think about the resources, but I checked and there are enough resources. -
How to fix when sending email a local variable referenced before assignment problem in Django?
I like to send an email to an admin if a new user is filled out his profile. If the user choose an association from the form the queryset finds the admin's email and sends the message but It works not because of this error: local variable 'adminemail' referenced before assignment. I can understand what the problem is but I don't know how to fix it. If I add a static email address outside the POST method it works well but it's not right for me. Please show me the right solution! views.py def ProfileFun(request): form = ProfileForm(request.POST, request.FILES) if request.method == 'POST': assoc = form.instance.egyesulet for email in Association.objects.raw('SELECT * FROM szaknevsor_association WHERE rovidnev = %s', [assoc]): adminemail = email.admin.email if form.is_valid(): form.save() send_mail( 'New notification', 'This is amessage', 'e@mymail.com>', [adminemail], fail_silently=False, ) print (form.errors) return redirect('szaknevsor:szakemberek') else: print (form.errors) return render(request, 'szaknevsor/profile.html', {'form':form,}) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' exclude = ('valid',) models.py class Profile(models.Model): def __str__(self): return str(self.user) ASSOCIATION = [ ('first', 'First'), ('second', 'Second'), ] user = models.OneToOneField(User, unique=True, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Felhasználó") egyesulet = models.TextField(max_length=200, choices=ASSOCIATION, verbose_name="Melyik egyesületnek vagy tagja?* (csak ennek a logója jelenik meg)") datetime = models.DateTimeField(auto_now_add=True, auto_now=False) … -
How to use django channel and celery to send messages regularly?
Below are my consumer code and tasks code. I want the task to start when the first user opens the page and establishes a channel, which begins querying data and periodically broadcasting to the corresponding group's channel. When subsequent users create channels, there is no need to start new tasks again. I have considered making the Celery task a scheduled task that broadcasts to the specified group's channel regardless of whether any user has opened the channel or not. However, I am not sure if this is a good solution. # consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from app_monitor.tasks import monitor class MonitorConsumer(AsyncWebsocketConsumer): async def connect(self): self.group = 'monitor' await self.channel_layer.group_add(self.group, self.channel_name) monitor.delay(self.group) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] async def send_data(self, event): print(event) await self.send(text_data=json.dumps({"data": event['data']})) # tasks.py from dbaOps.celery import app from channels.layers import get_channel_layer from asgiref.sync import async_to_sync from django.db import connections from app_monitor.utils.sqlarea import MONITOR_SQL @app.task def monitor(group): try: with connections['tools'].cursor() as cur: cur.execute(MONITOR_SQL) data = cur.fetchall() channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)(group, {'type': 'send.data', 'data': data}) except Exception as e: print(e)