Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to use chain and group with celery?
Im building a solution using python, django rest framework, celery and rabbitmq to run some tasks in my api project. However some tasks may be done in parallel and others not. I tried this solution using chord and group, but in these two ways the last task(task_9) never is executed, all the others previous tasks are executed with success. When i tried chord i put task_9 as a callback function, but even this doesn't work. Here is an example of my code. chain(task_1.si(registry_id, name) | task_2.si(registry_id, name) | task_3.si(registry_id, name) | group(task_4.s(task_3_result), task_5.s(task_3_result), task_6.s(task_3_result), task_7.s(task_3_result), task_8.s(task_3_result), ) | task_9.si(registry_id, name) ).apply_async() -
Django settings.py can't import my local module
My Django tree looks like this git/src ├── myproject │ ├── settings.py │ ├── mysharedlib.py │ └── urls.py └── www ├── urls.py └── views.py It works except that in settings.py I have import mysharedlib But this raises an exception ModuleNotFoundError: No module named 'mysharedlib' Why isn't this working? -
Forbidden: /api/v1/token/logout/ "POST /api/v1/token/logout/ HTTP/1.1" 403 58
I am experiencing this problem following a tutorial and I can't identify the error in my "MyAccountView.vue" page. I tried changing to re_path and it did not work. Forbidden: /api/v1/token/logout/ [16/Oct/2023 19:01:35] "POST /api/v1/token/logout/ HTTP/1.1" 403 58 CODE: URLS.PY from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('djoser.urls')), path('api/v1/', include('djoser.urls.authtoken')) ] SETTING.PY REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSESS':( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSESS':( 'rest_framework.permissions.IsAuthenticated', ) } ERROR IMAGES Getting this error in browser's console MyAccountView.vue If it works i'm supposed to forward on "/" or home page of my site. methods: { logout() { axios .post("/api/v1/token/logout/") .then(response => { axios.defaults.headers.common["Authorization"] = "" localStorage.removeItem("token") this.$store.commit('removeToken') this.$router.push('/') }) .catch(error => { if (error.response) { console.log(JSON.stringify(error.response.data)) } else if (error.message) { console.log(JSON.stringify(error.message)) } else { console.log(JSON.stringify(error)) } }) } } -
How can I serialize the Transaction model in django rest framework
There are two reasons why the Transaction model should have a sender and receiver and assign them to the CustomUser model with different related names. It could help answer questions like: Who initiated the Transaction? Who received the funds? We want to serialize this model because our company intends to use React.js as the frontend of the application. I would like to know how to validate the serialization to ensure that the sender can send funds from their account to another. As you can see this view, I created it based on django template: def transfer(request): if request.method == 'POST': account_number = request.POST['account_number'] amount = Decimal(request.POST['amount']) superuser_account = Account.objects.get(user='superuser username') # set this username to the admin username or your preferred account. sender_account = Account.objects.get(user=request.user) receiver_account = Account.objects.get(account_number=account_number) interest_rate = 0.02 deduction = amount * interest_rate if sender_account.account_balance >= amount: sender_account.account_balance -= amount sender_account.save() receiver_account.account_balance += amount receiver_account.save() superuser_account.account_balance += deduction superuser_account.save() Transaction.objects.create( sender=request.user, receiver=receiver_account.user, amount=amount, account_number=account_number ) return redirect ('Transfer') else: messages.error(request, 'Insufficient Funds') return redirect ('Transfer') return render(request, 'transfer.html') This view checks if the sender account balance is greater than or equal to the specified transfer amount. If the sender doesn't have enough funds, it sets an error … -
Regex for username allows for more than one special character
The regex I have is not working as I intend it to. It should not allow for more than one special character and the special character should not be the starting character of the username. The below regex allows for more than one special character and it also for the special character to be the starting character. regex=r'^(?=.{6,15})(?=.*[a-z])(?=.*[@-_]).*$', Valid Input : user@site Invalid Inputs, user@@site, @usersite I tried to alter the Regex it mulitple ways, but not able to achieve the desired output -
How to assign user and user.profile to the request object using a single database query in django?
Django assign user to request in the django.contrib.auth.middleware.py by calling request.user = SimpleLazyObject(lambda: get_user(request)) The get_user function is in the init.py file which in turns calls another get_user function in the backends.py def get_user(self, user_id): try: user = UserModel._default_manager.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None Here it is making a database call to get user by id. How can I get the user profile(related to user by a one to one field) in the same query and propagate it back so I can assign it to request.profile? -
Follow up to https://stackoverflow.com/questions/77300502/django-turn-off-on-pagination-for-one-filter-request/77300948#77300948
As mentioned in the question from title, I have 2 models, 1 Product and 1 for ProductImages. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My view for fetching list of products is, def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) results = [] for product in qs: images = models.ProductImages.objects.filter(product=product.id) results.append({'product': product, 'images': images}) return JsonResponse({ 'status': 'success', 'result': results, }) I am getting an error saying TypeError: Object of type Product is not JSON serializable on line return JsonResponse({ I couldn't find a solution for returning response which is combination of 2 different models. Can anybody please help me solving this issue? PS: I don't want to get the list of products in frontend and then make network call/calls to get images associated with them. -
DRF spectacular creates tags, can't figure out where to remove(
class EquipmentViewSet(ReadOnlyModelViewSet): queryset = Equipment.objects.all() serializer_class = EquipmentSerializer @extend_schema( summary='Получение списка всех объектов класса "Оборудование"', tags=['Equipment'], description=""" Получение списка всех оборудования. В ответе будет получен полный список объектов класса "Оборудование". """, request=EquipmentSerializer, responses=equipment_status_codes ) def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) In the swager, in addition to tags=['Equipment'], tag = v1 is created where /api/v1/equipment/{id}/ is located. I tried everything, I want to cry, extend_schema_view doesn't help in any way -
How to get rid of this extra gap in my Django website?
I deployed this website, which can be seen by pasting the URL in the browser. RFP Website If you see the homepage, you can see that on the right, it seems to scroll infinitely and I am getting a huge gap, which is not in other pages. How to get rid of this? -
How can I properly Query data from a django model without
im trying to create a simple django app for buying and selling shares but im having trouble querying my data properly specifically the amount of available shares. These are my models: from django.db import models from accounts.models import CustomUser class Share(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) quantity_available = models.PositiveIntegerField() def __str__(self): return self.name class Transaction(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) share = models.ForeignKey(Share, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() total_price = models.DecimalField(max_digits=10, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) is_purchase = models.BooleanField() then these are my views: from django.shortcuts import render, redirect from .models import Share, Transaction from .forms import BuyShareForm, SellShareForm def buy_share(request): share = Share.objects.filter(quantity_available__gt=100) form = BuyShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] if quantity <= share.quantity_available: transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=True) transaction.save() share.quantity_available -= quantity share.save() return redirect('shares:buy-success') else: form.add_error('quantity', 'Insufficient shares available') context = { 'share': share, 'form': form, } return render(request, 'shares/buy_share.html', context) def sell_share(request): share = Share.objects.all() form = SellShareForm(request.POST or None) if request.method == 'POST' and form.is_valid(): quantity = form.cleaned_data['quantity'] transaction = Transaction(user=request.user, share=share, quantity=quantity, total_price=quantity * share.price, is_purchase=False) transaction.save() share.quantity_available += quantity share.save() return redirect('shares:sell_success') return render(request, 'shares:sell_share.html', {'form': form}) when i try to get the … -
Cannot redirect with forwardauth Traefik middleware
How to actually switch(redirect) to another page (login page) with Traefik ForwardAuth ? I'm using the following docker labels: 'traefik.http.routers.my-route.rule=Host("main.int")' 'traefik.http.routers.my-route.entrypoints=https443' 'traefik.http.routers.my-route.tls=true' 'traefik.http.routers.my-route.middlewares=my-test-auth@docker 'traefik.http.middlewares.my-test-auth.forwardauth.address=https://auth.page.int/login/' 'traefik.http.middlewares.my-test-auth.forwardauth.tls.insecureSkipVerify=true' Traefik logs shows that is accessing the auth.page.int/login page: GET /accounts/login/ HTTP/2.0" 200 3459 but browser stays on the main page. BTW redirect works with RedirectRegex middleware for the same example. Documentation: https://doc.traefik.io/traefik/middlewares/overview/ -
React axios get parameter is undefined
I want to get some data from an api with a parameter current user's username. useEffect(()=>{ console.log(currentUser[0]?.id.toString()) if (currentUser) { console.log(currentUser[0]?.id.toString()) axios.get(`http://127.0.0.1:8000/get_chat2/?user1=${currentUser[0]?.id.toString()}&user2=`).then(res=>{ setUsers(res.data) console.log(res.data) }) },[currentUser]) When I print currentUser[0]?.id.toString() I get user's id but when I send the request it is undefined. I tried doing it a string but it still is undefined. Also when instead of id I use the username it isn't undefined. -
How to debug a 502 error for a Docker compose app?
An application that I'm maintaining (I'm not the one who created it, so my knowledge of it is limited) is deployed via Docker compose and consists of the following containers: name what is status servey_prod_bot a Telegram bot works ... helper services for bot, of no interest in this context servey_prod_stat reports new data works servey_prod_app admin web app not accessible (see below) servey_prod_nginx well, Nginx works servey_prod_db db works Recently, I was asked to modify the _stat component, and, long story short, that forced me to rebuild the whole thing and restart the containers, and some code changes might get applied. The _bot and the _stat seem to work nicely, the _app is also up, but now an attempt to get it via browser fails with 502. What I have done to debug this already: the _app (it's a Django app): I've checked docker logs and shows that it successfully started gunicorn, listens to http://0.0.0.0:9090 and has 3 workers (on restart workers exited and the app is shut down, then restarted successfully; no migrations involved); I've also checked nc -zv localhost 9090 and nc -zv 0.0.0.0 9090 inside the container, both report that the port is open; finally, I've … -
Django Turn off/on pagination for one filter request
I have 2 models, 1 for Product and 1 for ProductImages with pagination set to 10. For any product, we can have associated multiple images. class Product(models.Model): title = models.CharField(max_length=200) details = models.TextField(null = True) slug = models.CharField(max_length=300, unique=True, null=True) class ProductImages(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_imgs') image = models.ImageField(upload_to='product_imgs/', null=True) def __str__(self): return self.image.url My ProductList view looks like, class ProductList(generics.ListCreateAPIView): queryset = models.Product.objects.all() serializer_class = serializers.ProductListSerializer pagination_class = pagination.PageNumberPagination def get_queryset(self): qs = super().get_queryset() if self.request.method == 'GET': if 'category' in self.request.GET: category = self.request.GET['category'] category = models.ProductCategory.objects.get(id=category) qs = qs.filter(category=category) if 'owner' in self.request.GET: print('get_queryset Owner') owner = self.request.GET['owner'] qs = qs.filter(owner=owner) if 'available' in self.request.GET: available = self.request.GET['available'] == 'true' qs = qs.filter(available=available) ids = [] for product in qs: # images = models.ProductImages.objects.filter(id=product.id) print('Images: %d', product.id) ids.append(product.id) for id in ids: print('Id %d', id) images = models.ProductImages.objects.filter(product__in=ids) I am trying to fetch products and images associated with those products. When I fetch products I get 10 products (as per set pagination) and I get 10 images. But problem is I want to get all (say) 25 images associated with those 10 products, i.e. I want to turn off the pagination only for filter on ProductImages … -
How To Upload and Display Images in Django 4.2.5 on Whogohost
I have developed my Django application using Django 4.2.5. And locally it is uploading and displaying images fine but on production server it is uploading but not displaying the uploaded images. I have check the url of the images on my HTML Templates while on the server using DevTools but it seems to be pointing rightly. I don't know whether this has to do with some dependencies of sort. So someone should help. See my Model Code: from imagekit.models import ProcessedImageField from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from imagekit.processors import ResizeToFill, Transpose #File Extension Validator @deconstructible class FileExtensionValidator: """ImageKit Validation Decorator""" def __init__(self, extensions): self.extensions = extensions def __call__(self, value): extension = value.name.split('.')[-1].lower() if extension not in self.extensions: valid_extensions = ', '.join(self.extensions) raise ValidationError(f"Invalid file extension. Only {valid_extensions} files are allowed.") image_extensions = ['jpeg', 'jpg', 'gif', 'png'] class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=20, blank=True) # 'admin', 'cashier', 'customer' full_name = models.CharField(max_length=60, blank=True) phone = models.CharField(max_length=14, blank=True) address = models.CharField(max_length=160, blank=True) is_active = models.BooleanField(default=True) image = ProcessedImageField( upload_to='profile_images', processors=[Transpose(), ResizeToFill(150, 200)], format='JPEG', options={'quality': 97}, validators=[FileExtensionValidator(image_extensions)], default='avatar.jpg' ) last_updated = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.user.username}-Profile' See the url to displaying the images: <img class="img-thumbnail" src=" {{ user.profile.image.url … -
Django session cookie is not being set in production
I have a Django application I just moved to production. I am unable to make the site display I am logged in. It works fine on my local machine and I do not see any errors in production and the username and password is correct. The problem the session cookie is not being set and my settings are correct I believe. Here are my settings related to sessions: DEBUG = False ALLOWED_HOSTS = ["localhost","102.219.85.91","founderslooking.com","app.founderslooking.com"] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1", "http://localhost:file", "http://app.founderslooking.com", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN = "founderslooking.com" #SESSION_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://*.127.0.0.1", "http://app.founderslooking.com",] INTERNAL_IPS = [ "127.0.0.1", ] I am not using https because I am only testing the site until I am sure everything works, then I will switch over to https. Why is the session cookie not being set? The application is on a VPS using Ubuntu, Gunicorn, Nginx and Supervisord -
Postman request redirecting regardless of option and/or setting when run in GitHub
I'm experiencing some odd behaviour when running my postman collection through the CLI using Newman specifically when running in my GitHub Actions CI/CD environment. For my collection two requests are done to set both the CSRF token and the sessionid that are necessary for the other requests. In order to do this through the CLI I programmatically set the cookies based on the request's response headers. However the second request is redirected a few times before reaching it's end point and to get the value I need for the sessionid I specifically need the first redirected request. Postman/Newman has an option for this called --ignore-redirects which fixes this problem when running locally and even through docker. However when running it on the GitHub's CI/CD it seems that this options is ignored as the behaviour it shows is the same as not using the option at all. This then causes my post-request test script to not be able to find the sessionid and set it in the collection variable. This in turn causes all other requests to fail because of a lack of a sessionid. Is there a way around this? Or should I consider a different tool for API testing? … -
How to add a variable which pick up certain value dependent on other variable present in view.py in django
I want to make form2 variable in which we have to add condition that pick institute name from register table where institute code is equal to institute code present in form 1 variable and pass form2 in context so that it can be printed in template file. I have added code in view.py def view_eligibility_admin(request): form1 = Eligibility_Check.objects.all() form2 = {} # Initialize an empty dictionary to store institute names for item in form1: institute_code = item.Centre_code try: register_entry = Register.objects.get(institute_code=institute_code) institute_name = register_entry.institute_name form2[institute_code] = institute_name except Register.DoesNotExist: # Handle the case where the institute code doesn't exist in the Register model form2[institute_code] = "N/A" context = {'form1': form1, 'form2': form2} return render(request, 'view_eligibiity_admin.html', context) In my template.py I have used it like this. <tr> <td>{{ forloop.counter }}</td> <td>{{ i.Centre_code }} / {{ i.Serial_number }}</td> <td>{{ i.Date_of_survey }}</td> <td>{{ i.District }}</td> <td>{{ i.Voter_id }}</td> <td>{{ i.Ec }}</td> <td>{{ form2.item.institute_code }}</td> <td class="text-center"> <a class="btn btn-primary" href="{% url 'view_eligibility_pid' i.pk %}"><i class="fa fa-eye" aria-hidden="true"></i> </a> </td> </tr> {% endfor %}``` But i am getting blank value in place of institute name. -
Is it possible to get the all values of foreign key instead of id?
Is it possible to get all the values of foreign key instead of id? class WishlistSerializer(serializers.ModelSerializer): def to_representation(self, instance): rep = super(WishlistSerializer, self).to_representation(instance) rep['product'] = instance.product.name return rep -
Where can I host a Django website for free?
Guy's Is there any free hosting services available for python django application. I think AWS, Google Cloud and Azure are not completely free. Thanks in advance 😃 I had been using heroku for years but now heroku is changed their policy. -
Tastypie Django full hydrate returns an error when joining the protected Resource
I created here a small example to explain my problem for which I haven't find a solution on the web. I am using Django and Tastypie to implement a REST API. I have "MyUserResource" which is a descendant of Django's User model and this resource is protected with StaffAuthorization. Then I have "CommentsResource" which should be opened for Anonymous users as well. Now, my problem lies in the fact that during running Tastypie's full_hydrate operation within obj_create, Tastypie is trying to make a join on user table. That means that in case anonymous users are trying to fetch comments, the API returns Unauthorized error. For now I implement it to "open" MyUserResource" by using Authorization and checking within obj_create, obj_update and obj_delete if the user is staff or a superuser. But I wouldn't want that everyone is able to retrieve the list of users as well. Is it possible to protect User resource and still allow joins during hydration process? I still haven't tried to implement "my" obj_get function and there check if users are staff or superusers and for other types of user I might remove sensitive data? Here is the sample code, first Django models and then Tastypie … -
How to setup CSRF Trusted Origina domain on same server as Django docker app in plesk?
I currently have a django app installed on a Docker in Plesk. Id like to keep everything to basically localhost for any domain that I have hosted on the same server. The only thing that works is adding the actual domain https://subdomain.domain.com. Its not ideal to do this as Id like to use the Django app on multiple domains/subdomains that I have hosted on my plesk server. I tried the '*' option and it does not work either. Been breaking my head all day testing this and I cant seem to get it to work. :/ The error I receive is this in docker: django.security.csrf log Forbidden (Origin checking failed - https://subdomain.domain.com does not match any trusted origins.) Any help with experienced docker folks out there? I've tried https://localhost, https://127.0.0.1, the docker ip https://172.17.0.3 and a bunch of other options and nothing works. -
Updating celery workers code in production without distrupting currently running tasks?
I have a program that runs some tasks in the background, which can run for hours. I will have many tasks running at many different times. I cannot really kill the tasks, because the user is aspecting these tasks to finish. The basic gist of it is I have a frontend which sends a request to the backend to start a task. This task will scrape some data, and do some other stuff with that data. It could take many hours and they are important to keep running. I have thought of maybe shutting down the tasks and keeping track of where they left of from and just continueing. This could work, but I couldn't figure out how to do this and I would rather not kill the tasks at all as it may be half way through scraping the data. My current thought has been to have two queues. One with the old tasks and one with the new ones. But I don't know how I would redirect all the future tasks to the new queue. I would like to have a way to do this that is easy and I can do many times. Does anyone know any … -
GET /static/css/style.css?after HTTP/1.1 404 1820
During python web development using django, the contents of static are not applied.. Is there a way? Below is the code BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIR = [ BASE_DIR / 'static', os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'static/css'), os.path.join(BASE_DIR, 'static/image'), os.path.join(BASE_DIR, 'static/javascript'), ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] STATIC_URL = '/static/' STATIC_URL = 'static/' results are the same, and at the same time <link rel="stylesheet" href="{% static '/css/style.css' %}?after" /> and other than ?after output the same error this is errors my tree It is a situation where the codes of css were applied temporarily using the style tag of html. -
Trying to develop a spatial dashboard [closed]
I have been assigned the responsibility of developing a spatial data catalog that dynamically displays the count of available datasets within specified geographical boundaries. The datasets, comprising both vector and raster data, will be hosted and served through GeoServer. As new data is uploaded, the dataset count displayed on the catalog will automatically update to reflect the current total. I am keen to explore if anyone has undertaken a similar project and would be open to sharing insights or ideas to guide the successful execution of this initiative. I'm still research based on user-friendly, responsive, and interactive experience to users