Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Media files are not shown: open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied) - Django Nginx
I'm trying to see my media files in my website, but I can't. Static files are OK but Media files, despite all my efforts are not visible. Here is nginx error log: 2023/10/17 11:59:33 [error] 48068#48068: *7 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_uWh54BB.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *6 open() "/home/shahriar/Amlak/real_estate/media/images/IMG_20230828_214539_i6yw2Zc.jpg" failed (13:> 2023/10/17 11:59:33 [error] 48068#48068: *5 open() "/home/shahriar/Amlak/real_estate/media/images/image1.jpg" failed (13: Permission denied), > 2023/10/17 11:59:33 [error] 48068#48068: *4 open() "/home/shahriar/Amlak/real_estate/media/images/ویلا-چمستان-1_0kmP7E3.jpg" failed (13: Permi> 2023/10/17 11:59:33 [error] 48068#48068: *3 open() "/home/shahriar/Amlak/real_estate/media/images/455008604_479875.jpg" failed (13: Permission> My nginx configuration file for website: location /static { alias /var/www/real_estate/static/; } location /media { root /home/shahriar/Amlak/real_estate/; } settings.py: STATIC_URL = 'static/' STATIC_ROOT = '/var/www/real_estate/static/' STATICFILES_DIRS = [BASE_DIR/'static/',] # Default primary key field type # https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Media Settings MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media/' I tried giving permission to my media folder like this: sudo chown -R www-data:www-data /var/www/real_estate/static sudo chown -R www-data:www-data /home/shahriar/Amlak/real_estate/media I tried restarting nginx.service and gunicorn.service. The path to media files is correct, but the website seems to be unable to get them. -
Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema
Im trying to merge two GraphQL outputs and I have this error when I try to load Could not import 'backend.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: Type "Mutation" not found in the Schema. I have two schemas within each corresponding apps from graphene_django import DjangoObjectType from careers import models import graphene class JobType(DjangoObjectType): class Meta: model = models.Job class CategoryType(DjangoObjectType): class Meta: model = models.Category class Query(graphene.ObjectType): all_jobs = graphene.List(JobType) job_by_slug = graphene.Field(CategoryType, slug=graphene.String()) def resolve_jobs_by_category(root, info, category): return ( models.Job.objects.prefetch_related("category") .select_related("title") .filter(category__name__iexact=category) ) schema = graphene.Schema(query=Query) and the 2nd on here: from django.contrib.auth import get_user_model from graphene_django import DjangoObjectType from blog import models import graphene class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: model = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag class ImageType(DjangoObjectType): class Meta: model = models.UploadImage class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_bt_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags").select_related("author").all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_image(self, info): if self.image: self.image = info.context.build_absolute_uri(self.image_url) return self.image def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, … -
Nginx is breaking While showing images
I have high quality images which I want to show on my web page. But whenever am running with nginx the django project breaks after some time when pages are loading. I have checked all the file paths and images are loading in django without nginx Tried to run in django was running bbut whenever nginx is configured webpage is breaking -
A task using django/heroku scheduler do nothing
I have used heroku to deploy using python-django. Following heroku documentation, i installed scheduler, create a python scrypt(tarefas.py), but nothing happened. the log show status 0. this is the heroku help answer: Anuj Pandey 20 hours ago Hi Carlos, The status 0 signifies that the entire process is completed and everything worked fine. As logs also show your tarefas.py and python tarefa2.py are executing completely. The issue seems to be with the code you have pushed, this appears to be an issue that falls outside the nature of the Heroku Support policy. I recommend searching our Help Center or asking the community on Stack Overflow for more answers. Regards, Anuj Pandey tarefas.py: import smtplib import email.message import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ERP.settings') def EnviarEmailTeste(): texto = '<h1>Teste de agendamento de tarefas a cada 10 minutos</h1>' msg = email.message.Message() msg['Subject'] = 'Teste de agendamento de tarefas' msg['From'] = '*****' msg['To'] = '****' password = '****' msg.add_header('Content-Type','text/html') msg.set_payload(texto) s = smtplib.SMTP('smtp.gmail.com: 587') s.starttls() s.login(msg['From'],password) s.sendmail(msg['From'],[msg['To']],msg.as_string().encode(('utf-8'))) s.quit() context = 'email enviado com sucesso.' return context my heroku scheduler: Job Dyno Size Frequency Last Run Next Due $ python tarefas.py Standard-1X Every 10 minutes October 17, 2023 11:32 AM UTC October 17, 2023 11:42 AM UTC … -
Guest checkout business logic for server/database with Stripe
I am making an a simple app which allows users to post ads to the website for a fee, as in pay per post. No account is required, it is in essence a guest checkout by default. The issue I am dealing with is the order and best way to implement the business logic on the server side. My flow is as follows: (Front end) User fills out a form with ad details (Front end) User hits submit (Back end) Post request is processed, new database entry is created (Back end) User is redirected to Stripe checkout Payment fails or succeeds Notice how in this flow I create an object/entry in my database before any payment has been made. This already feels wrong because I feel the entry shouldn't exist unless it has been paid for. Because spammer could in theory fill my database with endless entries by filling the form and not completing payment. So if Stripe payment fails in step 5, I have a choice: delete the entry, or return the user to the form prefilled. Clearly, the later is the better option, however if the user never finishes or fixes the payment I will still have a … -
Python Request save cookie response in browser
i have a django web app that use request to post to my gofiber api in response it get a session cookie i need that session cookie in my js fetch in the frontend but my request does not set the cookie in the browser def login(request): email = "" password = "" if request.method == 'POST': session = requests.Session() email = request.POST['email_test'] password = request.POST['password'] email = "test@test.com" password = "Test" url = "http://localhost:8006/auth/login" myobj = {'email': email, "password": password} x = session.post(url, json=myobj) if x.status_code == 200: print(x.cookies) session_cookies = dict(x.cookies) request.session['session_id'] = session_cookies print("Session cookies: " + str(session_cookies)) print(session_cookies) return HttpResponseRedirect(reverse("index")) return HttpResponse("Login failed") return render(request, "webadmin/login.html", { "email": email, "password": password }) print(x.cookies) <RequestsCookieJar[<Cookie kronborg_id=3f6be328-c4e1-4faf-a26b-7b04bc48d006 for localhost.local/>]> print(session_cookies) {'kronborg_id': '3f6be328-c4e1-4faf-a26b-7b04bc48d006'} -
How can I combine three docker images running on different ports to a single docker image
I am trying to create a Docker setup with multiple services including Django, Next.js, and Nginx, where Nginx serves as a reverse proxy for both Django (backend) and Next.js (frontend) applications. I want it to work in such a way that these 3 images are combined into one image for deployment. I have tried to used the multi-staged docker build, but i can't get the configuration right. PROJECT FILES: ./schoolduo-backend/Dockerfile.prod: ########### # BUILDER # ########### # pull official base image FROM python:3.11.4-slim-buster as builder # set work directory WORKDIR /usr/src/schoolduo-backend # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apt-get update && \ apt-get install -y --no-install-recommends gcc # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . /usr/src/schoolduo-backend/ RUN flake8 --exclude env --ignore=E501,F401 . # install python dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/schoolduo-backend/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.11.4-slim-buster # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup --system app && adduser --system --group app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN … -
How to create index condition on boolean field with `is`
When I create a composite index with condition like this class Meta: indexes = [ models.Index( name="test_boolean_idx", fields=["field1", "field2"], condition=Q(field2=False), ), ] the resulting SQL gives CREATE INDEX ON table (field1, field2) WHERE NOT field2; Trouble is this index is not used when filtering by SELECT * FROM table WHERE field2 IS false; only for SELECT * FROM table WHERE field2 = false; I can work around by creating an index manually with WHERE field2 is false Is there a way to create such an index condition with Django models? -
QuerySet when you have an instance
I have a query set which filters a resource based on whether a user has access to it or not: resources = Resource.objects.user_access(user).all() Let's say I have a single resource instance already. Should I then implement a property in my Resource model with the same logic as in my user_acesss Query Set. where I again check if they has access? Like this: resource.has_user_access(user) I suppose I'm conscious of the fact that I'm repeating the logic that checks if the user has access in two places. If I were to put that logic into its own method, I guess it would be a static method in the Resource class. -
Django routing integration with React
We have a Django React project. we are already in the step that when user enters home URL, the app will show(Django response the react project and the home page) and also my React Routing is working(im using React-router-dom for routing). i also know that react routing and Django routings are different and separately. now my problem is if someone(client) enters any other URL than homepage URL for example someone bookmarked a "example.com/shop" and so many others like this that they are not homepage URL, Django side question: how could django has to find out the client dont have react and send the application (my react app)to it in every URL. React side question: for example user in the example.com/shop and Django send the react to client but react how can find out whitch page is the rout we do R&D about the routing but everything is all about the homepage, but there is no other pages or when user bookmarked something else than homepage.... we also watches the courses for integration but they also working on just homepage... -
django.urls.exceptions.NoReverseMatch: 1 pattern(s) tried: ['link/edit/(?P<pk>[0-9]+)/\\Z']
I am trying to use Django with HTMX. My task is to do editable row in the link list with HTMX. When I click the edit button in the row, I am getting NoReverseMatch error. raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'link_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['link/edit/(?P[0-9]+)/\Z'] [17/Oct/2023 12:54:42] "GET /link/edit/97/ HTTP/1.1" 500 118059 I've tried so many methods on stackoverflow but I didn't figure it out. Here my code is: # urls.py in my project urlpatterns = [ path('', home, name='home'), path('admin/', admin.site.urls), path("user/", include("user_profile.urls", namespace="user")), path("link/", include("link.urls", namespace='link')), ] # urls.py in my link app from django.urls import path from link.views import tag_view, category_view, delete_links, delete_link, get_row_view, LinkUpdateView, LinkyListView app_name = 'link' urlpatterns = [ path('edit/<int:pk>/', LinkUpdateView.as_view(), name='link_update'), path('edit/<int:pk>/get_row_view/', get_row_view, name='get_row_view'), path('tag/<slug:tag_slug>/', tag_view, name='tag_view'), path('category/<slug:category_slug>/', category_view, name='category_view'), path('delete/', delete_links, name='delete_links'), path('delete-item/<int:pk>/', delete_link, name='delete_link'), path('list', LinkyListView.as_view(), name='link_list_view'), ] # views.py in my link app def get_row_view(request, pk): link = LinkUrl.objects.get(pk=pk) context = dict( link=link, ) return render(request, 'link/row.html', context) class LinkUpdateView(UpdateView): model = LinkUrl form_class = LinkModelForm template_name = 'link/edit_link_form.html' def get_success_url(self): return reverse_lazy('link:link_update', kwargs={'pk': self.object.pk}) row.html <tr id="link_list_{{link.pk}}"> <td>{{ link.title }}</td> <td>{{ link.get_full_url }}</td> <td> <span class="p-1 border fs-12 rounded text-light bg-primary"> <a … -
Why can't my terminal use the command "django-admin"(my system is windows and I have added path to the environment)
My terminal and cmd cannot identify the command "django-admin" in any folders. However, when I use the terminal inside pyCharm, it functions normally. Can someone help me with the problem and explain why it happens? Thanks a lot. I have added paths to my environment. enter image description here But it didn't help. -
Uploading file directly to Google Cloud Document AI
I am trying to upload a file directly to Google Cloud Document AI for processing. I am receiving the error 400 Request contains an invalid argument. [field_violations { field: "raw_document.content" description: "Inline document content must be provided." My code: def upload(request): template_name = "upload.html" # if this is a POST request we need to process the form data if request.method == "POST": # create a form instance and populate it with data from the request: form = UploadReceiptForm(request.POST, request.FILES) if form.is_valid: docai_client = documentai.DocumentProcessorServiceClient( client_options=ClientOptions( api_endpoint=globals.GOOGLE_CLOUD_DOCUMENT_AI_ENDPOINT ) ) # The full resource name of the processor version, e.g.: # `projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}` name = docai_client.processor_version_path( globals.GOOGLE_CLOUD_PROJECT_ID, globals.GOOGLE_CLOUD_DEFAULT_LOCATION, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_ID, globals.GOOGLE_CLOUD_DEFAULT_PROCESSOR_VERSION_ID ) # Configure the process request image_content = request.FILES["file"].read() request = documentai.ProcessRequest( name=name, raw_document=documentai.RawDocument(content=image_content, mime_type="image/jpeg"), ) result = docai_client.process_document(request=request) # redirect to a new URL: return HttpResponseRedirect("/upload/") # if a GET (or any other method) we'll create a blank form else: form = UploadReceiptForm() return render(request,template_name, {"form": form}) Thanks in advance for the help! -
how to make query in django pytest test user
I have a django code which is for reset password and if user is authenticated the process goes on as change password. I write a test in pytest for this code, and i use a test user to auth and check change password stage, in code for process we need user national id and when user is already online we take national id from profile. so is provided national id in test user as well but the problem is that it's not wrking and my test user not return national id. does anybody has any idea whats problem? andis this any oher way to make test user for this test. views.py @method_decorator(csrf_protect, name='dispatch') class ResetPassword(APIView): permission_classes = (permissions.AllowAny, ) try: # read input nid = request.data.get('nationalId') #....take more input to conside stage based on them .... if not request.user.is_anonymous and request.user.is_authenticated: user = request.user nid = user.profile.identity_number tests.py @pytest.fixture def test_user_nid(): user = User.objects.create_user( username="8835246563", password="upass123", ) profile = Profile.objects.update(user=user, identity_number="8835246563") return user @pytest.mark.django_db class Test: def test_change_password_stages(self, api_client, test_user_nid): api_client.force_authenticate(user=test_user_nid) print("User ID:", test_user_nid2.id) print("User Profile Identity Number:", test_user_nid2.profile.identity_number) data = { "tfaCode": 12345 } response = api_client.post(self.url, data, format='json') # assert response.status_code == status.HTTP_200_OK response_data = response.json() print(">>>>", response_data) … -
Monthly Celery Beat task also runs after celery restart
I have a task that is set to run on the first day of every month at 05:00 using celery beat. It has been set as follows in settings.py: CELERY_BEAT_SCHEDULE = { 'generate_monthly_reports': { 'task': 'api.tasks_reports.generate_monthly_reports', 'schedule': crontab(minute=0, hour=5, day_of_month=1) }, } This works well and runs reliably. However, I have recently discovered that it is also run whenever Celery is restarted, e.g. when a server code update is made and celery restarted via supervisor. I am using Celery 5.2.6, Python 3.8 and Django 4.0.4. How can I prevent this task running when Celery is restarted please? -
Deploy python django project on cyberpanel at hostinger using openlitespeed
I am trying to Deploy python django project on cyberpanel at hostinger using openlitespeed. I have setup all things but i am facing the 503, service unavailable error, My WSGI Script is runnig fine when i test it alone in a different directory. docRoot $VH_ROOT/public_html vhDomain $VH_NAME vhAliases www.$VH_NAME adminEmails aristonvillagepizza@gmail.com enableGzip 1 enableIpGeo 1 index { useServer 0 indexFiles index.php, index.html } errorlog $VH_ROOT/logs/$VH_NAME.error_log { useServer 0 logLevel WARN rollingSize 10M } accesslog $VH_ROOT/logs/$VH_NAME.access_log { useServer 0 logFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" logHeaders 5 rollingSize 10M keepDays 10 compressArchive 1 } scripthandler { add lsapi:arist7587 php } extprocessor arist7587 { type lsapi address UDS://tmp/lshttpd/arist7587.sock maxConns 10 env LSAPI_CHILDREN=10 initTimeout 600 retryTimeout 0 persistConn 1 pcKeepAliveTimeout 1 respBuffer 0 autoStart 1 path /usr/local/lsws/lsphp81/bin/lsphp extUser arist7587 extGroup arist7587 memSoftLimit 2047M memHardLimit 2047M procSoftLimit 400 procHardLimit 500 } phpIniOverride { } module cache { storagePath /usr/local/lsws/cachedata/$VH_NAME } rewrite { enable 1 autoLoadHtaccess 1 } context /.well-known/acme-challenge { location /usr/local/lsws/Example/html/.well-known/acme-challenge allowBrowse 1 rewrite { enable 0 } addDefaultCharset off phpIniOverride { } } vhssl { keyFile /etc/letsencrypt/live/aristonvillagepizza.uk/privkey.pem certFile /etc/letsencrypt/live/aristonvillagepizza.uk/fullchain.pem certChain 1 sslProtocol 24 enableECDHE 1 renegProtection 1 sslSessionCache 1 enableSpdy 15 enableStapling 1 ocspRespMaxAge 86400 } context / … -
Django proxy-model returning wrong ContentType
Let's say we have a model Company and subtype Client like so: class Company(models.Model): name = models.CharField(max_length=100) related_companies = models.ManyToManyField('self', symmetrical=True) is_customer = models.BooleanField(default=False) class ClientManager(Manager): def get_queryset(self): return QuerySet(self.model, using=self._db).filter(is_customer=True) class Client(Company): objects = ClientManager() class Meta: proxy = True Next you go into CLI, create an instance and fetch its content-type from django.contrib.contenttypes.models import ContentType In[38]: company = Company.objects.create(name='test', is_customer=True) In [39]: ContentType.objects.get_for_model(c) Out[39]: <ContentType: contacts | company> That returns the concrete model for the company class. So far so good. Next, according to the docs, the follows should return the Client content-type. In [40]: ContentType.objects.get_for_model(c, for_concrete_model=False) Out[40]: <ContentType: contacts | company> Yet, it does not. I'm still receiving the concrete model Company instead of Customer Do you see my mistake? -
Unable to generate Models using InspectDB
I am using Django inspectdb to auto generate models from an existing mongodb database deployed on the cloud. It was configured using NodeJS and now client wants to change it to Django. In my settings.py, I have: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'dbname', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://string' } } } When I run python manage.py inspectdb, I get the following error for each table: # The error was: 'NoneType' object is not table_name # Unable to inspect table 'table_name' I have the following packages installed in my virtualenv: Package Version ----------------- ------------ asgiref 3.7.2 Django 4.1.12 djongo 1.3.6 dnspython 2.4.2 pip 23.2.1 pymongo 3.12.3 pytz 2023.3.post1 setuptools 68.2.2 sqlparse 0.2.4 typing_extensions 4.8.0 wheel 0.41.2 -
How to add other field which related to many-to-many inline admin on Django
I have Transaction model and Match model which has many-to-many field relationship class Transaction(models.Model): amount = models.DecimalField(max_digits=16, decimal_places=2) card_no = CleanTextField(null=True, blank=True) date = models.DateField() class Match(models.Model): match_at = models.DateTimeField(auto_now_add=True) a_transactions = models.ManyToManyField(Transaction, related_name="a_matches") b_transactions = models.ManyToManyField(Transaction, related_name="b_matches") And also have admin inline and model admin class ATransactionInline(admin.TabularInline): model = Transaction.a_matches.through extra = 0 class BTransactionInline(admin.TabularInline): model = Transaction.b_matches.through extra = 0 class TransactionAdmin(admin.ModelAdmin): list_display = ["amount", "date"] inlines = [ATransactionInline, BTransactionInline] admin.site.register(Transaction, TransactionAdmin) So in Transaction admin page there're display the match object in inlines But I need to display a and b transactions which related to that match object Is there any solution? -
AWS Elastic Beanstalk/Django: How do I get static files to work?
I'm running the newest Django/Python version on Elastic Beanstalk, which I believe runs on Amazon Linux 2023. My Django website is finally deployed (after much blood, sweat and tears). My website correctly displays all HTML/Database info, but it's missing CSS/JS, which are contained within the static files. Some of the elastic beanstalk documentation is a bit deprecated - I tried following this guide: But my configuration contained absolutely no mentions of static files at all. What am I missing, and how can I add them? Thanks. -
How to succesfully make a POST request with JS fetch to a Django REST API
I've been trying unsuccesfully to make a POST request to my API end point, and I always get an error. My setup is a django server with a rest API, and I'm trying to add a reservation to the Booking Model, using fetch. This is the code inside my "onSubmit" js function (when the submit button is clicked): csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value; const formdata = new FormData(form); fetch('/api/booking/', { method: 'POST', headers: { "X-CSRF-Token":csrf, "Content-Type": "application/json" }, credentials: "same-origin", body: formdata }) .then(res => res.json()) .then(data => console.log(data)); models.py class Booking(models.Model): client = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date = models.DateField(null=True) hour = models.SmallIntegerField( null=False, default=12, validators=[ #from 8am to 10pm MaxValueValidator(22), MinValueValidator(8) ], ) class Meta: unique_together = ('date', 'hour') forms.py class BookingForm(ModelForm): class Meta: model = Booking fields = ['date', 'hour', 'client'] views.py (of the api endpoint /api/booking/ class BookingView(generics.ListCreateAPIView): queryset = Booking.objects.all() serializer_class = BookingSerializer So this is the error I get in the Chrome JS console: book:159 POST http://127.0.0.1:8000/api/booking/ 400 (Bad Request) onSubmit @ book:159 book:169 {detail: 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}detail: "JSON parse error - Expecting value: line 1 column 1 (char 0)"[[Prototype]]: Object Any idea what is the problem? -
Unit testing in Python on a function that doesn't have a return value? Is including test-specific code in a function bad practice?
I am writing a mock-up Auction site in Django as part of my self-learning to code. I'm at the point where I'm learning to write tests for my software but I've encountered the problem where a number of my functions used for the web app do not normally return a value. In this one example, I included a boolean parameter for a function that checks whether it is being tested or not. If the parameter is true, it executes a block of code that then does return value that I can then assert with unittest. This is the function: def cleantags(testing=False) -> None: """Executed on listing update, delete, or accept. Purges tags in 'Category' that are no longer used""" unused_tags = Category.objects.filter(Q(listing__isnull=True) | Q(listing__sold=True)) for _tag in unused_tags: _tag.delete() if testing: deleted_tags = [] for _tag in unused_tags: deleted_tags.append(_tag.__str__()) return deleted_tags This is the unittest: def test_tag_deleted(self): """Checking that cleantags() will purge tags in Catergories that don't belong to a listing or to one that has sold.""" # ['Lions','Tigers','Bears','Foo','Bar'] tag_objs = self.generate_tags() self.listing1.tags.add(tag_objs[0]) self.listing1.tags.add(tag_objs[1]) self.listing2.tags.add(tag_objs[2]) self.listing2.sold = True del_tags = listmng.cleantags(True) self.assertQuerySetEqual(del_tags, ['Foo','Bar']) I guess my main question is if this is considered bad coding practice, and if so is … -
Fetch user roles from keycloak using django-allauth
I've managed to get Django to login using Keycloak via openid-connect. I did this with django-allauth. The problem I have now is that I can't figure out how to determine (in Django) which roles a user has (these are defined in Keycloak), in order to give the user appropriate permissions to do things. -
mysqlclient Python Package stop working after Sonoma update
I'm working on a project that uses Django, which connects to a MySQL database, and one of the packages that is used to perform this operation is mysqlclient. But, early this day my laptop was forced to update his OS to Sonoma (I'm working on a Mac), and after that, when I tried to run the project again, it stopped working, and now it throws this error: enter image description here I've tried reinstalling my mysql-client with brew and exporting these variables into my .zshrc file without success. export LDFLAGS="-L/usr/local/opt/mysql-client/lib" export CPPFLAGS="-I/usr/local/opt/mysql-client/include" export PKG_CONFIG_PATH="/usr/local/opt/mysql-client/lib/pkgconfig" Could someone please help me with a solution about this issue? -
Django Orm implementation of connection between unrelated fields by geometry
I am trying to return the closest node locations to a starting node where the 2 database tables have no relation defined between one another. Therefore, I need to find a method to create a full cross join between the tables/subsets of data according to a filter or a facsimile of one. Models: class WaysVerticesPgr(models.Model): objects = CTEManager() id = models.BigAutoField(primary_key=True) cnt = models.IntegerField(blank=True, null=True) chk = models.IntegerField(blank=True, null=True) ein = models.IntegerField(blank=True, null=True) eout = models.IntegerField(blank=True, null=True) the_geom = models.PointField(srid=3857, blank=True, null=True) class Meta: managed = True db_table = 'ways_vertices_pgr' class Pois(models.Model): objects = CTEManager() id = models.BigIntegerField(primary_key=True) name = models.TextField(blank=True, null=True) tags = models.JSONField(blank=True, null=True) geom = models.PointField(srid=3857) class Meta: managed = False db_table = 'pois' Query 1 - q1 - is getting points from the Pois table that fit any criteria, the result I want is the nodes inside the waysverticespgr table of the routing section of the database and return each node reachable in a set time (i.e. within walking distance <= 10 min) with the minimum distance from any of the starting nodes and annotate the resulting nodes with the actual distance. I have working sql for this query but implementing with django orm or django_cte …