Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django JSONField Aggregate and Sum
I have the below JSON saved in PostgreSQL 9.4 DB and running Django 2.2 [{"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 7, "companyvalue_id": 207, "team_members_name": "pidofod tester", "users_teammember_id": 2793}, {"rating": 4, "companyvalue_id": 207, "team_members_name": "xakir tester", "users_teammember_id": 2795}] There is many database entries. I would like to aggregate all instances of team_members_name and Sum to find out the total rating. The JSON data is saved in a model field data = JSONField(null=True, blank=True) The closest I have is def data_rating(self): model = apps.get_model('model', 'ModelName') model_count = rating_tool.objects.all() return model_count.objects.annotate( rating=Cast( KeyTextTransform("rating", "data"), IntegerField(), ) ).values("rating").distinct().aggregate(Sum("rating"))["rating__sum"] The above only works for single JSON object, i.e. {"rating": 6, "companyvalue_id": 188, "team_members_name": "pidofod tester", "users_teammember_id": 2793} however I need KeyTextTransform to work across many JSON objects and in many database rows. I also need to filter/aggregate each user, i.e. what is "team_members_name": "pidofod tester" total rating Sum. End result is to return this result in a DRF endpoint. Have tried many options as below but none work or seem close, feel a model re-work may be needed. Any ideas or suggestions appreciated! #return rating_tool_count.annotate(numbers_len=Func(F('rating_tool_data'), function='jsonb_array_length')).aggregate(rating_total=Sum(F("rating"))) #return rating_tool_count.annotate(single_nested_value=F("rating_tool_data__team_members_name"),array_access=F("rating_tool_data__rating"),) #return rating_tool.objects.aggregate(Sum('rating_tool_data__rating')) #.values('rating_tool_data__rating').annotate(rating_total=Sum(Cast(KeyTextTransform("rating", "rating_tool_data"), models.IntegerField()))) #return rating_tool_count.annotate(team_members_name=Cast(KeyTextTransform( #"team_members_name", "rating_tool_data"), models.TextField())).values("rating_tool_data").annotate(rating_total=Sum(Cast(KeyTextTransform("rating", "rating_tool_data"), #models.IntegerField())),).order_by("-rating_total") #return … -
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'mysite.routing'
I am trying to create a webapp using django and while running it on my local system, I am getting stucked here because of this issue.Even though the asgi,wsgi and settings are configured properly.Its showing that it cant import asgi application.Can someone check what's the issue is ? asgi.py """ ASGI config for mysite project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os import sys import django from channels.routing import get_default_application from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') # django.setup() application = get_asgi_application() wsgi.py """ WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() At first I thought it was about the Base dir not getting initialised, show I tried using pathlib, but still it didnt work setting.py """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.8. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Adding a url field linking to an action in serializer in DRF
I am using django rest framework. I want to include the url of an action defined in a view in its serializer. My serializers.py: from rest_framework import serializers class CommentSerializer(serializers.ModelSerializer): """Serializer for comments.""" class Meta: model = Comment fields = ["id", "item", "author", "content", "date_commented", "parent"] class ItemDetailSerializer(serializers.ModelSerializer): """Serializer for items (for retrieving/detail purpose).""" category = CategorySerializer(many=True, read_only=True) media = MediaSerializer(many=True, read_only=True) brand = BrandSerializer(many=False, read_only=True) specifications = serializers.SerializerMethodField(source="get_specifications") comments = ?????????????????????????????????????????????????? class Meta: model = Item fields = [ "id", "slug", "name", "description", "brand", "show_price", "location", "specifications", "is_visible", "is_blocked", "created_at", "updated_at", "seller", "category", "media", "comments", "users_wishlist", "reported_by", ] read_only = True editable = False lookup_field = "slug" def get_specifications(self, obj): return ItemSpecificationSerializer(obj.item_specification.all(), many=True).data My views.py: from rest_framework import viewsets, mixins, status from ramrobazar.inventory.models import Item, Comment from ramrobazar.drf.serializers ItemSerializer, ItemDetailSerializer, CommentSerializer from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.filters import SearchFilter from django_filters.rest_framework import DjangoFilterBackend class ItemList(viewsets.GenericViewSet, mixins.ListModelMixin): """View for listing and retrieving all items for sale.""" queryset = Item.objects.all() serializer_class = ItemSerializer serializer_action_classes = { "retrieve": ItemDetailSerializer, } permission_classes = [IsAuthenticatedOrReadOnly] lookup_field = "slug" filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = [ "category__slug", "brand__name", ] search_fields = ["name", "description", "category__name", "brand__name", "location"] def get_serializer_class(self): try: return self.serializer_action_classes[self.action] except: return self.serializer_class def … -
raise InvalidSchema("No connection adapters were found for {!r}".format(url) while using requests module
I'm getting this error every time my for-loop makes a call to the API. The curious thing is I'm still getting an json object result for the first query the call has an issue with as such, requests.exceptions.InvalidSchema: No connection adapters were found for '{\'page\': 1, \'results\': [{\'backdrop_path\': \'/c4CSgKL6QfkJxsWcGYDyTxpbzpW.jpg\', \'first_air_date\': \'2017-03-31\', \'genre_ids\': [18, 9648], \'id\': 66788, \' and etc. After doing some research, I'm starting to think somewhere down the line my url added an extra "" or '' or perhaps its confusing the strings data type due it having integers in the title: "12 Monkeys", "90210". How do I check for this and also fix it? Here is my relevant code: from email.mime import base import pprint from pkgutil import get_data from pydoc import pager from unittest import result from django.http import JsonResponse from django.shortcuts import render, HttpResponse, redirect from .models import * import json from django.core.paginator import Paginator from django.db.models import Q import requests from pprint import pp, pprint ... for lists in post: data = requests.get(F'https://api.themoviedb.org/3/search/tv?api_key={api_key}&language=en-US&page=1&include_adult=false&query={lists}') r = data.json() response = requests.get(r) response.raise_for_status() # raises exception when not a 2xx response if response.status_code != 204: return response.json() -
How can I use slugs in Django url like mysite.com/user
I want to create a directory like website.com/user after the user get logged in! And I'm not sure which url pattern should call this myfun def myfun(request, user): user = get_user_model().objects.get(slug=user) return render(request, 'authorization/home.html', {'user' : user}) models.py class TwitterUser(models.Model): screen_name = models.CharField(max_length=255) name = models.CharField(max_length=255) user = models.SlugField('auth.User', unique=True, null=True) app/urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] view.py def twitter_login(request): twitter_api = TwitterAPI() url, oauth_token, oauth_token_secret = twitter_api.twitter_login() if url is None or url == '': messages.add_message(request, messages.ERROR, 'Unable to login. Please try again.') return render(request, 'authorization/error_page.html') else: twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is None: twitter_auth_token = TwitterAuthToken(oauth_token=oauth_token, oauth_token_secret=oauth_token_secret) twitter_auth_token.save() else: twitter_auth_token.oauth_token_secret = oauth_token_secret twitter_auth_token.save() return redirect(url) def twitter_callback(request): if 'denied' in request.GET: messages.add_message(request, messages.ERROR, 'Unable to login or login canceled. Please try again.') return render(request, 'authorization/error_page.html') twitter_api = TwitterAPI() oauth_verifier = request.GET.get('oauth_verifier') oauth_token = request.GET.get('oauth_token') twitter_auth_token = TwitterAuthToken.objects.filter(oauth_token=oauth_token).first() if twitter_auth_token is not None: access_token, access_token_secret = twitter_api.twitter_callback(oauth_verifier, oauth_token, twitter_auth_token.oauth_token_secret) if access_token is not None and access_token_secret is not None: twitter_auth_token.oauth_token = access_token twitter_auth_token.oauth_token_secret = access_token_secret twitter_auth_token.save() # Create user info = twitter_api.get_me(access_token, access_token_secret) if info is not None: twitter_user_new = TwitterUser(twitter_id=info[0]['id'], screen_name=info[0]['username'], name=info[0]['name'], profile_image_url=info[0]['profile_image_url']) twitter_user_new.twitter_oauth_token = twitter_auth_token user, … -
How to use "\dt" in cursor.execute() to get the tables in PostgreSQL? (Django)
In Django, I'm trying to use \dt in cursor.execute() to get the tables in PostgreSQL as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): cursor = connection.cursor() cursor.execute('''\dt''') # Here row = cursor.fetchone() print(row) return HttpResponse("Test") But, I got the error below: django.db.utils.ProgrammingError: syntax error at or near "" LINE 1: \dt So, I replaced cursor.execute('''\dt''') with cursor.execute('''\\dt''') as shown below: # "views.py" from django.http import HttpResponse from django.db import connection def test(request): # ... cursor.execute('''\\dt''') # Here # ... return HttpResponse("Test") But, I still got the error below: django.db.utils.ProgrammingError: syntax error at or near "" LINE 1: \dt So, how do I use \dt in cursor.execute() to get the tables in PostgreSQL? -
Generating PDF with filter dates
I am trying to generate pdf with filter dates using modal. If there is no filter dates, I can generate the PDF but if there is a filter date there is an error [22/Oct/2022 08:59:38] "POST /generateinvoicevehicle/ HTTP/1.1" 405 0 Internal Server Error: /generateinvoicevehicle/ If I refresh the page, "UnboundLocalError: local variable 'incident_vehicle' referenced before assignment [22/Oct/2022 08:59:41] "GET /generateinvoicevehicle/ HTTP/1.1" 500 72789" How can I generate the report correctly with filter dates? Thank you Views class GenerateInvoiceVehicle(View): def get(self, request, *args, **kwargs): try: if request.method == 'POST': fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') if fromdate: incident_general = IncidentGeneral.objects.filter(user_report__date__gte=fromdate) incident_vehicle = IncidentVehicle.objects.filter(incident_general__user_report__date__gte=fromdate) if todate: incident_general = IncidentGeneral.objects.filter(user_report__date__lte=todate) incident_vehicle = IncidentVehicle.objects.filter(incident_general__user_report__date__gte=fromdate) # incident_general_accident = IncidentGeneral.objects.filter(user_report__status = 2).values('accident_factor__category').annotate(Count('severity'), filter=Q(severity='Damage to Property')) incident_vehicle = incident_vehicle.filter(incident_general__user_report__status = 2) incident_vehicle1 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Fatal' ).annotate(Count('incident_general__severity')) incident_vehicle2 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Damage to Property' ).annotate(Count('incident_general__severity')) incident_vehicle3 = incident_vehicle.filter(incident_general__user_report__status = 2,incident_general__severity='Non-Fatal' ).annotate(Count('incident_general__severity')) # incident_general_classification = IncidentGeneral.objects.filter(user_report__status = 2, severity="Damage to Property").distinct('accident_factor') except: return HttpResponse("505 Not Found") data = { 'incident_vehicle': incident_vehicle, # 'incident_general_classification': incident_general_classification, 'incident_vehicle1': incident_vehicle1, 'incident_vehicle2': incident_vehicle2, 'incident_vehicle3': incident_vehicle3, # 'incident_general_collision3': incident_general_collision3, # 'amount': order_db.total_amount, } pdf = render_to_pdf('pages/generate_report_pdf_vehicle.html', data) #return HttpResponse(pdf, content_type='application/pdf') # force download if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Vehicle_Classification.pdf" #%(data['incident_general.id']) content … -
"GET / HTTP/1.1" 500 145
Anytime I turn debug to false in my settings.py my site gives a server error. This is what my server shows and the site doesn't work again Performing system checks... System check identified no issues (0 silenced). October 21, 2022 - 23:47:07 Django version 4.1.2, using settings 'dlcfogbomoso.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [21/Oct/2022 23:47:09] "GET / HTTP/1.1" 500 145 [21/Oct/2022 23:54:18] "GET / HTTP/1.1" 500 145 Please any help? -
Cross-Origin Resource Sharing (CORS) headers not being added to responses
Cross-Origin Resource Sharing (CORS) headers not being added to responses, in-browser requests to my Django application from other origins not seeming possible. I have followed the instructions here on PyPi with no help. I have included the console area I receive. https://pypi.org/project/django-cors-headers/ I am looking to fetch a json file. Console errors: Access to fetch at 'http://localhost:8000/api/cats' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. App.vue:59 GET http://localhost:8000/api/cats net::ERR_FAILED 301 fetchcats @ App.vue:59 _createElementVNode.onClick._cache.<computed>._cache.<computed> @ App.vue:29 callWithErrorHandling @ runtime-core.esm-bundler.js:155 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:164 invoker @ runtime-dom.esm-bundler.js:339 runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of native event handler at <App> warn2 @ runtime-core.esm-bundler.js:38 logError @ runtime-core.esm-bundler.js:212 handleError @ runtime-core.esm-bundler.js:204 (anonymous) @ runtime-core.esm-bundler.js:167 Promise.catch (async) callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:339 App.vue:59 Uncaught (in promise) TypeError: Failed to fetch at Proxy.fetchcats (App.vue:59:28) at _createElementVNode.onClick._cache.<computed>._cache. <computed> (App.vue:29:18) at callWithErrorHandling (runtime-core.esm-bundler.js:155:22) at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:21) at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:339:9) fetchcats @ App.vue:59 _createElementVNode.onClick._cache.<computed>._cache.<computed> @ App.vue:29 callWithErrorHandling @ runtime-core.esm-bundler.js:155 callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:164 invoker @ runtime-dom.esm-bundler.js:339 Promise.catch (async) callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:166 invoker @ runtime-dom.esm-bundler.js:339 -
save() saves all fields except ManyToMany field
I have a model "Contest" with one m2m field called "teams" which is related to a model "Team". I overrided the method save. In my save() function (the one that's overriding), I need a queryset (in my save overrinding function) with all the objects related to my team m2m field. The code is self.teams.all() but it won't work because my models is not yet registered in database right ? So I call super().save(*args, **kwargs) now my models is saved and I can get my queryset ? I can't. The queryset is empty, even if I registered team(s). <QuerySet []> Why does super.save() save immediately all the fields except the m2m ? I use exclusively the django admin web site to create models. No manage.py shell or form. My model : class Contest(models.Model): name = models.CharField(max_length=16, primary_key=True, unique=True, default="InactiveContest", blank=True) # Ex: PSGvMNC_09/2017 id = models.IntegerField(default=1) teams = models.ManyToManyField(Team, verbose_name="opposants") date = models.DateTimeField(blank=True) winner = models.ForeignKey(Team, verbose_name='gagnant', related_name='winner', on_delete=models.SET_NULL, blank=True, null=True) loser = models.ForeignKey(Team, verbose_name='perdant', related_name='loser', on_delete=models.SET_NULL, blank=True, null=True) bet = models.IntegerField(verbose_name='Nombre de paris', default=0, blank=True, null=0) active = models.BooleanField(default=False) def save(self, *args, **kwargs): if self._state.adding: self.active = False # Django's id field immitation last_id = Contest.objects.all().aggregate(Max('id')).get('id__max') if last_id is not … -
What's the best way to desplay list of inons using Django?
I'm working on a small project where I have a table named 'icons' that contains paths for stored icons inside folder 'mydjangoproject/app/icons' and I have an endpoint "mydomainname.com/user/icon/< name >" I want the user to be able to replace with the icon that he wants and he gets in return the icon For example if the user took this link mydomainname/user/icon/car.png and used it in an tag or typed it in the browser it would work and show that specific icon What is the best way to do that? -
POST http://localhost:8000/add_new/ 500 - Django
I have a question about django. In my ecommerce website I am trying to add add to cart function. My code is working and I can add to the cart with AnonymousUser. But, when i try to add to cart when I logged in with account, I am having this error: error: Internal Server Error So, it's adding to the cart, but location.reload is not working. I need to restart manually. What is the problem? Please, help! -
Django DetailView dont show data in template
I am completely new to Django CBV and I don't understand why I can't display data in template with using DetailView. I have no errors, just can't display any data in template. I have spent hours trying to figure it out, but I am slowly giving up This is my model: class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title views.py: class ProjectListView(ListView): model = Project class ProjectView(DetailView): model = Project template_name = 'base/single-project.html' (I have tried with get_context_data() and get_object() but the effect was the same) urls.py: urlpatterns = [ path('', ProjectListView.as_view(), name='projects'), path('project/<str:pk>/', ProjectView.as_view(), name='project'),] and the template: {% extends 'main.html' %} <p>{{ object }}</p> <p>{{ object.title }}</p> <p>{{ project.title }}</p> <p>{{ project }}</p> (Here I just tried to see anything) -
My images are not displaying the post.photo.url call on my cpanel hosting
Hello I just put my blog online on cpanel hosting. I managed the display with the whitenoise library of python. The static images work normally. But when I call the image from blogpost to display my image does not appear with post.photo.url. I am under cpanel and I would like to ask for your help to display the images of my blog on my site class Photo(models.Model): image = models.ImageField(verbose_name='image') caption = models.CharField(max_length=128, blank=True, verbose_name='légende') date_created = models.DateTimeField(auto_now_add=True) IMAGE_MAX_SIZE = (1900, 1265) def resize_image(self): image = Image.open(self.image) image.thumbnail(self.IMAGE_MAX_SIZE) image.save(self.image.path) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.resize_image() def __str__(self): return self.caption My models.py class BlogPost(models.Model): slug = models.SlugField() categorie = models.ForeignKey(CategorieBlogs, on_delete=models.CASCADE) image = models.ForeignKey(Photo, on_delete=models.CASCADE) title = models.CharField(max_length=500, verbose_name="titre blog") subtitle = models.CharField(max_length=500, verbose_name="sous titre") contenu = models.TextField(max_length=1500, verbose_name="contenu blog") description = models.TextField(max_length=2000, verbose_name="contenu blog 2") titles = models.CharField(max_length=500, verbose_name="titre 2") photo = models.ImageField(upload_to="photo blog") contenus = models.TextField(max_length=2000, verbose_name="paragraph 2", blank=True) descriptions = models.TextField(max_length=2000, verbose_name="paragraph contenu 2", blank=True) datepub = models.DateField(verbose_name="Date de publication", auto_now_add=True) published = models.BooleanField(default=False) auteur = models.ForeignKey(AuteurPost, on_delete=models.CASCADE) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("posts:home") def __str__(self): return self.title class Meta: ordering = ['-datepub'] verbose_name = "Blog" My … -
Django apache doesn't work when using a virtual environment
I am trying to deploy my django project on a linux ubuntu server using apache2. I can deploy it correclty when I dont use a virtual venv. I rebuilt my VM and did the same thing but with using a virtual env and it not working. When I visit my website url it give me this error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. here is my /etc/apache2/sites-available/mysite.conf <VirtualHost *:80> ServerName MYIPSERVER ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite/venv/lib/python3.10/site-packages WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /static/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> Before without the venv the WSGIDaemonProcess was setup like this WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite but it wasn't working so I changed it for that: WSGIDaemonProcess mysite processes=2 threads=25 python-path=/var/www/mysite/venv/lib/python3.10/site-packages and it still not working. I am not sure where the problem is coming from. my project folder is located into /var/www -
Django - Keep specific fields on form after submit
I have a view that has a simple "save and add another" functionality, that redirects the user to the same page after submit the form. View: def new_planning(request): form = PlanningForm(request.POST) if form.is_valid(): form.save() if 'another' in request.POST: messages.success(request, ('Success!')) return redirect('new_planning') else: return redirect('list_planning') return render(request, 'pages/planning/new_planning.html', context={ 'form': form, }) Form: class PlanningForm(forms.ModelForm): accountplan = ModelChoiceField( queryset=AccountsPlan.objects.filter(active=True).order_by('code'), ) month = forms.DateField( required=True, error_messages={'required': '', }, ) amount = forms.DecimalField( max_digits=9, decimal_places=2, required=True, validators=[ error_messages={'required': '', }, ) class Meta: model = Planning fields = '__all__' The function works as expected and after the submit, the same page is rendered with a blank form. What I want is to keep just the "amount" field blank and keep the data typed in the "accountplan" and "month" fields. Is there a way to do this? I read about instance in the docs, but it doesn't seem to be what I looking for, since I don't want to get the data from the database (if that's possible), but simply keep the last inputs typed in both fields. -
DJANGO - How can i make the statics folder accessible on deploy
in the admin screen, I can access CSS and JS files by typing their url locally but i can't when it is deployed. this is how it works locally this is how it works deployed Online it takes me to the 404 screen while locally it returns the raw file (as i am trying to do) these are my settings for static files in Settings.py STATIC_URL = 'guias/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'guias/static') thanks everyone :D -
Django ._meta and adding to ManyToMany fields
I haven't had much luck finding other questions that helped with this, but apologies if I missed something and this is a duplicate. I'm trying to add to some ManyToMany fields, without having to explicitly type out the names of the fields in the code (because the function I'm working on will be used to add to multiple fields and I'd rather not have to repeat the same code for every field). I'm having a hard time using ._meta to reference the model and field objects correctly so that .add() doesn't throw an "AttributeError: 'ManyToManyField' object has no attribute 'add'". This is simplified because the full body of code is too long to post it all here, but in models.py, I have models defined similar to this: class Sandwich(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) veggies = models.ManyToManyField(Veggie) meats = models.ManyToManyField(Meat) class Veggie(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) class Meat(models.Model): name = models.CharField(max_length=MAX_CHAR_FIELD) Once instances of these are created and saved, I can successfully use .add() like this: blt = Sandwich(name='blt') blt.save() lettuce = Veggies(name='lettuce') lettuce.save() tomato = Veggies(name='tomato') tomato.save() bacon = Meat(name='bacon') bacon.save() blt.veggies.add(lettuce) blt.veggies.add(tomato) blt.meats.add(bacon) But if I try to use ._meta to get blt's fields and add to them that way, I … -
Django signals don't work with DEBUG=False
I have the following code that work fine in development mode with DEBUG=True. In a nutshell - signal should invalidate a cache. The project running Django 4.0, Python 3.9. signals.py from django.core.cache import cache from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from apps.hub.models import Comment, Marker @receiver(signal=post_delete, sender=Marker, dispatch_uid="marker_deleted") def clear_cache_delete_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been deleted.""" cache.delete("markers_frontend") @receiver(signal=post_save, sender=Marker, dispatch_uid="marker_updated") def clear_cache_save_handler(sender, **kwargs): """Method for clearing a cache on home page after Marker instance has been updated.""" cache.delete("markers_frontend") I connect them in apps.py from django.apps import AppConfig class HubConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.hub' def ready(self): """Register all signals.""" # Implicitly connect a signal handlers decorated with @receiver. from . import signals But whether I set DEBUG=False, signals don't work and as a result cache is not invalidates. I tried both - local machine and a hosting server. Result is the same. What is wrong? -
Django doesn't redirect to the same page
I'm working on a django project website. When submitting a form I need to save the data and show a message with from django.contrib import messagesmodule. It works perfectly with saving data but it never shows the message and redirecting to the same page. Views.py class. def showIndex(request): if request.method == 'POST': contact = Contact() name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') contact.name = name contact.email = email contact.message = message print('yes and no ') messages.success(request, 'Profile details updated.') contact.save() return render(request,'index.html') return render(request,'index.html') and this is the codes in index.html. I have created the form here. <form method="POST" class="u-clearfix u-form-spacing-30 u-form-vertical u-inner-form" style="padding: 10px"> {% csrf_token %} <div class="u-form-email u-form-group u-form-partition-factor-2"> <label for="email-319a" class="u-label u-text-body-alt-color u-label-1">Email</label> <input type="email" placeholder="Enter a valid email address" id="email-319a" name="email" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-name u-form-partition-factor-2"> <label for="name-319a" class="u-label u-text-body-alt-color u-label-2">Name</label> <input type="text" placeholder="Enter your Name" id="name-319a" name="name" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required="" /> </div> <div class="u-form-group u-form-message"> <label for="message-319a" class="u-label u-text-body-alt-color u-label-3">Message</label> <textarea placeholder="Enter your message" rows="4" cols="50" id="message-319a" name="message" class="u-border-2 u-border-no-left u-border-no-right u-border-no-top u-border-white u-input u-input-rectangle" required=""></textarea> </div> <div class="u-align-left u-form-group u-form-submit"> <a href="#" class="u-btn u-btn-submit u-button-style u-white u-btn-2">Submit</a> … -
How to access return value from apscheduler in a long process function?
Similar topic has been asked before, but my question is different. I want to get the fisrt function's return as a signal to trigger the second function, and the first function need run 2 minutes before it completed. def first_func: #long time run logic here #then has a return return signal def second_func: if 'success string' in signal: #do something def scheduler_func(request): try: scheduler = BackgroundScheduler() # Schedule the load process scheduler.add_job(first_function) scheduler.start() return render(request, 'customer/customer_base.html') except: pass finally: second_func() I have tried use global signal,but the second function not able to get the signal. -
Django ModuleNotFoundError: No module named 'fcm-django' error
I am trying to set up Firebase Cloud Messaging with my Django Rest Framework Backend for sending push notifications, however I keep getting ModuleNotFoundError: No module named 'fcm-django' error when I run python manage.py migrate I have already installed fcm-django using pip install fcm-django This is the error: Traceback (most recent call last): File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 22, in <module> main() File "C:\Users\Admin\Desktop\DigiLab-Back-End\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Admin\AppData\Roaming\Python\Python310\site-packages\django\apps\config.py", line 228, in create import_module(entry) File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'fcm-django' This is what I have done in my Settings.py to integrate FCM from firebase_admin import initialize_app INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Profiling.apps.ProfilingConfig', 'Appointments.apps.AppointmentsConfig', 'Chattings.apps.ChattingsConfig', 'Finance.apps.FinanceConfig', 'Feedbacks.apps.FeedbacksConfig', 'Inventory.apps.InventoryConfig', 'Settings.apps.SettingsConfig', 'Authentication.apps.AuthenticationConfig', 'fcm-django', 'rest_framework', 'corsheaders', ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { # default: _('FCM Django') "APP_VERBOSE_NAME": "test", # true if you want to have only one … -
Why is Django test throwing an error complaining about a column size that is incorrect when I try to run tests?
I have an old project that I'm resurrecting that was built with Python 2. I'm getting it going with a more current version of Python and Django (v3.9 and v4.1.2 respectively). I have the app basically up and running and I just tried to get the automated testing going. But I'm getting this error: django.db.utils.OperationalError: (1074, "Column length too big for column 'body' (max = 16383); use BLOB or TEXT instead") Unfortunately, I have the 'body' column in multiple objects in my models.py, AND each of them is defined as a TextField (e.g. body = models.TextField()). I'm not sure how to post the offending code since the error doesn't specify the exact object. My test is simple as I'm just trying to get testing going: from django.test import TestCase class Test_Countries(TestCase): def setUp(self): pass def test_basicCompare(self): self.assertEqual(1, 1) Before running the test (python manage.py test IFSServices/tests), I've ensured that makemigrations and migrate have succeeded. Any help that anybody could provide to help (incl how to ask a more useful question) would be greatly appreciated. -
django filter: How to filter results with multiple values
I am working on Django and I need to filter records eg: table: Person name age David Abraham Benj 18 so, if I run this, Person.objects.filter(name__icontains="David Abraham") it is working but if I run this, Person.objects.filter(name__icontains="David Benj") it is not working any idea how it works? framework: Django and SQL: Postgres -
Django huey file not processing all tasks
This is very strange. I don't want to setup a Redis service and since my queue has only very little requirements file or sqlite would work just fine. The both work fine on localhost, but when I deploy it to a docker container there are the following issues: SQLite compains that there is an I/O error. The path is set to /tmp, which has read/write permissions. I read that there are issues with CIFS filesystem, not sure if this is the case. Fact it, it doesn't work. Filesystem queue. Tasks are created in the folder, the consumer is starting to process them, but then just stops. Consumer is still running, but not processing any files anymore. Any advice on where to start looking would be appreciated.