Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
VARIABLE and DJANGO
I'm working on a project, in one function I make a random password, in another I want to send it. In the function where I generate a random password, I want to pick up a variable and put it in the function where I send it, but I know that Python does not allow this. Please tell me options on how to get around this and so that VIEW-PASSWORD can send a variable from VIEW-CONTACT def password(request): thepassword = '' for x in range(lenght): thepassword += random.choice(characters) return render(request, 'generator/password.html', {'password': thepassword}) MY CODE! (TWO VIEWS) VARIABLE "thepassword" i want give in func CONTACT def contact(request): sender = '\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*' password = '\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*' if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): subject = "Subject: YOUR PASSWORD" body = { 'first_name': form.cleaned_data['first_name'], 'last_name': form.cleaned_data['last_name'], 'email': form.cleaned_data['email_address'], } message = "Your generated password is -\n" + "\n".join(body.values()) server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() try: server.login(sender, password) server.sendmail(sender, form.cleaned_data['email_address'], f"{subject}\n {---!!!I WANT RETERN HERE MY VARIABLE--- >>>'thepassword'}") except BadHeaderError: return HttpResponse('Incorrect title found') return redirect("home") form = ContactForm() return render(request, "generator/contact.html", {'form': form}) -
Exclude user from an annotation query
I'm trying to query the users presents in a certain conversation. I finally got it working with this annotation: products = products.annotate( conversation_users=Subquery( Conversation.objects.filter( product=OuterRef('pk') ).annotate( users_array=ArrayAgg('users__username') ).values_list('users_array', flat=True)[:1] ) ) This is returning a list with the user present in the conversation (in most cases only two). I need to exclude from there the request.user so I get always the value of the user who I am having the conversation with. I tried using this Q query trying to exclude the request.user: .filter(~Q(users=user)).values_list('users_array', flat=True)[:1] ) but it is making the field now return None. How can I accomplish that? Edit 1: Those are the relevant models, Product model: class Product(models.Model): creator = models.ForeignKey( User, on_delete=models.CASCADE, related_name='anken') content = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) intouch = models.ManyToManyField( User, related_name='product_intouch', blank=True) And this is the Conversation model: class Conversation(models.Model): product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='conversations') users = models.ManyToManyField(User, related_name='conversations') def validate_unique(self, *args, **kwargs): super().validate_unique(*args, **kwargs) if Conversation.objects.filter(product=self.product, users__in=self.users.all()).exists(): raise ValidationError( 'A conversation with the same Product and user already exists.') -
Using sass preprocessor with a django+svelte project
I am creating a project using django and svelte framework mainly, I was wondering if it is possible to use sass preprocessor within my svelte components(not in the css files that are located in the static folder). I want to use it directly in the svelte component not in any other files. What is usually do is write code in svelte, build the code using "npm run build" then run the django server. Whenever I try to add sass by changing the rollupconfig, the command "npm run build" breaks and start giving error. Here is the files, in case you want to take a look. https://github.com/Ayush-vachhani/django_template/ -
Django Email Domain Validation with cleaned_email function works very slow after submitting
Hi i am trying to write email domain validation for sign up form in django syntax with following function code. I am using the function inside class meta: VALID_DOMAINS is a list = ['gmail.com', 'hotmail.com'] I am using Edge browser for test def clean_email(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) original_email = self.cleaned_data['email'] domain = self.cleaned_data["email"].split("@")[-1] if domain not in VALID_DOMAINS: raise ValidationError("E-mail addresses from %(domain)s are not allowed.", code="invalid", params={"domain": domain}) return original_email Problems are: After typing this function, sign up page works very slow when trying to check with any wrong domain (any outside of VALID_DOMAINS). (after submitting the form) After submitting sign up form with the wrong email domain, sign up from is not returning its original shape which is before submitting. There are also happening small corruptions, and password fields act as if passwords are not typed. I was not expecting to work very slow after submitting form. -
Celery console doesn't output a task result (Django / Redis)
While learning Celery stuck just on a running any task. My machine runs on Windows 11. To arrange a connection between Celery and Redis I've started a Docker container (using Docker desktop + WSL). Set Redis port for 6379. Created celery.py in project default app robot (same folder as settings.py) : import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'robot.settings') app = Celery('robot') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In the settings.py line added : CELERY_BROKER_URL = 'redis://localhost:6379/0' In the project's default app robot __init__ added lines: from .celery import app as celery_app __all__ = ['celery_app'] In custom django app user created tasks.py and following func for test: from celery import shared_task @shared_task() def simple_task(): print("SOME RESULT") When I run command in PowerShell celery -A robot worker I only get a message: [2023-05-10 12:42:23,232: WARNING/MainProcess] C:\Users\kosan\Documents\Python\venvs\robot_dreams_study\django\Lib\site- packages\celery\fixups\django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! Then I try to run a task (simple task with just printing a word) with Django Shell. As result I get an output in Django Shell: >>> simple_task.delay() <AsyncResult: a58d1627-7469-4a7a-b761-bca74dcb00c2> And that's all. No any output in celery consol or somewhere else. I have tried to run celery with celery -A robot … -
Celery beat cannot update currency exchange rates with django-money
I use django-money, then I ran celery beat to update currency exchange rates every 60 minutes with the code below. *I followed django-money doc: # "core/celery.py" import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') # "core/tasks.py" from celery import shared_task from djmoney import settings from django.utils.module_loading import import_string @shared_task def update_rates(backend=settings.EXCHANGE_BACKEND, **kwargs): backend = import_string(backend)() backend.update_rates(**kwargs) print("Successfully updated") # "core/settings.py" from celery.schedules import crontab OPEN_EXCHANGE_RATES_APP_ID = '5507ba2d9b8f4c46adca3169aef9c281' # Here CELERY_BEAT_SCHEDULE = { 'update_rates': { 'task': 'core.tasks.update_rates', 'schedule': crontab(minute='*/60'), 'kwargs': {} # For custom arguments } } But, I got the error below even though I set OPEN_EXCHANGE_RATES_APP_ID in settings.py as shown above: django.core.exceptions.ImproperlyConfigured: settings.OPEN_EXCHANGE_RATES_APP_ID should be set to use OpenExchangeRatesBackend So, how can I solve the error to update currency exchange rates every 60 minutes with celery beat? -
msal.acquire_token_by_username_password to get access token having issues with scope
I am trying to access a User's token using username of password, but I have an issue with the scope class AuthenticatedURLTestCase(TestCase): def setUp(self): self.journal_list_url = reverse('journalentry:journalcomptable_list', args=["slug_group", "slug_app"]) self.username = os.getenv('TEST_USER_EMAIL') self.password = os.getenv('TEST_USER_PASSWORD') self.auth0_client_id = os.getenv('ADD_B2C_CLIENT_ID') self.auth0_client_secret = os.getenv('ADD_B2C_CLIENT_SECRET') self.auth0_api_identifier = os.getenv('ADD_B2C_SUSI_AUTHORITY') self.auth0_api_scope = os.getenv('ADD_B2C_SCOPE') app = ConfidentialClientApplication( client_id=os.getenv("ADD_B2C_CLIENT_ID"), authority=os.getenv("ADD_B2C_SUSI_AUTHORITY") ) result = app.acquire_token_by_username_password( username=os.getenv('TEST_USER_EMAIL'), password=os.getenv('TEST_USER_PASSWORD'), scopes=['https://graph.microsoft.com/offline_access','https://graph.microsoft.com/openid'] ) if "access_token" in result: self.token = result["access_token"] print(self.token) print("got access token") else: print(result.get("error_description") or result.get("error")) def test_authenticated_url(self): response = self.client.get(self.journal_list_url,HTTP_AUTHORIZATION="Bearer " + self.token) self.assertEqual(response.status_code, 200) I am getting the error : The orchestration step '1' does not specify a CpimIssuerTechnicalProfileReferenceId when one was expected. Timestamp: 2023-05-10 09:51:38Z How do I modify the scope to get the access token ? -
Django Template not rendering data using when using for loop with index
I am implementing a functionality in Django which shows order details on a separate detail page I have also created a custom tag which return the range of length of the list given to it(Which is working fine): Here is my template : {% extends 'Verification/main.html' %} {% load custom_tags %} {% block content %} <div class="tableContainer" id="oVDId"> <h4>Order summary</h4> <table class="table"> <tr> <td>Purchase date</td> <td>{{order.orderCreated}}</td> </tr> <tr> <td>Fullfilment</td> <td>E-Bazar</td> </tr> <tr> <td>Sales channel</td> <td>E-bazar.com</td> </tr> </table> <h4>Order content</h4> <table class="table"> {% for i in order.products|get_range %} {{i}} <tr> <td>{{order.products.i.productId}}</td> <td> <tr> <td>Prodcut Name</td> <td>{{order.products_info.i.name}}</td> </tr> <tr> <td>Prduct SKU</td> <td>{{order.products_info.i.sku}}</td> </tr> <tr> <td>Prodcut Image</td> <tr> {% for image in order.products_info.i.images %} <td><a src="{{image}}" download><img src="{{image}}"></a></td> {% endfor %} </tr> </tr> <tr> <td>Prodcut Name</td> <td>{{order.products_info.i.name}}</td> </tr> </td> </tr> {% endfor %} </table> <h4>Ship to</h4> <table class="table"> <tr> <td>Name</td> <td>{{order.customer.name}}</td> </tr> <tr> <td>Address</td> <td>{{order.customer.address}}</td> </tr> <tr> <td>Address type</td> <td>Residential</td> </tr> <tr> <td>Phone number:</td> <td>{{order.customer.phone}}</td> </tr> </table> <a href="{% url 'oUnfulfilled' %}"> <button id='unfulfilledId'>Back to List</button></a> </div> {% endblock %} The problem I am facing is that data under the loop {% for i in order.products|get_range %} is not being rendered I replaced i with numbers 0,1,2 (as the list has length 3) … -
Missing argument in Django tutorial
I have been started learn Django right now and whlie doing tutorial i get some error. After changing views like in tutorial part 4 i started geting error that argument is missing. Reverse for 'votes' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/votes/\\Z'] I searched google about that problem and people had it but it was like problem with correct spelling. In my problem i had missing argument called question in details.html. I tried with the for loop and it helps but my answers didn't showing up. views.py: from django.shortcuts import render, get_object_or_404 from django.template import loader from django.http import HttpResponse, Http404, HttpResponseRedirect from django.urls import reverse from django.views import generic from .models import Questions, Choice class IndexView(generic.ListView): template_name = "polls/index.html" context_object_name = "latest_question_list" def get_queryset(self): "Return latest 5 questions" return Questions.objects.order_by("-pub_date")[:5] class DetailsView(generic.DetailView): model = Questions template_name = "polls/details.html" class ResponseView(generic.DetailView): model = Questions template_name = "polls/response.html" def votes(request, question_id): question = get_object_or_404(Questions, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST["choice"]) except (KeyError, Choice.DoesNotExist): return render( request, "polls/details.html", {"question": question, "error_message": "You didn't select a choice"}, ) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse("polls:response", args=(question.id,))) urls.py: from django.contrib import admin from django.urls import path, include from . import views app_name = … -
New users which are created by django-windowsauth upon first login are saved as DOMAIN\USERNAME, How can I change the default to USERNAME?
I'm creating a website with django for the first time and I needed the users to be authenticated with Active Directory so I used django-windowsauth package, but now when someone logs in for the first time their username is in DOMAIN\USERNAME format, therefore when I want to change their permissions in /admin/ it says the username can't contain backslash! I have read the django-windowsauth documentation but couldn't find anything on this. I tried changing the DOMAIN\USERNAME to USERNAME and I was able to save the changes but upon next login a new user was created as DOMAIN\USERNAME. to avoid this I used the database to change the username back to DOMAIN\USERNAME , but this is not practical after production. -
How to solve "attempted relative import with no known parent package"
from . import views ............ File "c:\Users\Asus\Desktop\mywebiie\base\migrations\tempCodeRunnerFile.py", line 1, in <module> from . import views ImportError: attempted relative import with no known parent package How to solve this problem? -
How to change text display with collapse in Django template
I'm using Django template and i added collapse to 2 half of text and i want to find a way to display them like normal sentence without wrap and breaks How can i solve that? template.html <table> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr> <td style="max-width: 50px;"> <div class="accordion accordion-flush" id="accordionFlushExample"> <div class="accordion-item"> <div class="accordion-body" style="padding: 0 !important; display: inline;"> {{ contractor.description|safe|slice:":9" }} <div id="flush-collapse{{ contractor.id }}" class="accordion-collapse collapse" data-bs-parent="#accordionFlush{{ contractor.id }}"> {{ contractor.description|safe|slice:"9:" }} </div> </div> {% if contractor.description|length > 10 %} <a data-bs-toggle="collapse" href="#collapse{{ contractor.id }}" role="button" aria-expanded="false" data-bs-target="#flush-collapse{{ contractor.id }}" aria-controls="flush-collapse{{ contractor.id }}"> More </a> {% endif %} </div> </div> </td> </tr> </tbody> </table> I want to change display of Hi i am bcs "am" is on another line -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte; Python-dotenv
After cloning a personal Django project from Github on to my computer, some environment variables were written to a .env file. The variables encompass a Django generated SECRET_KEY surrounded my single quotes and setting DEBUG to a string of 'False'. I installed python-dotenv as a part of my requirements for the purpose of passing in those variables into settings.py. Afterwards, I ran python manage.py migrate, yet I get the following error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte. I've researched the matter here: https://github.com/theskumar/python-dotenv/issues/207 As of python-dotenv 1.0.0 (the version which is installed), load_dotenv() has a default parameter of encoding=utf-8 https://github.com/theskumar/python-dotenv/blob/main/src/dotenv/main.py#L313 I'm doing all of this through Powershell on Windows 10 and using Python version 3.9.6. What else should I try to resolve this error? Traceback (most recent call last): File "C:\..\django_stackoverflow\manage.py", line 22, in <module> main() File "C:\..\django_stackoverflow\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\..\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\..\django\core\management\__init__.py", line 363, in execute settings.INSTALLED_APPS File "C:\..\site-packages\django\conf\__init__.py", line 82, in __getattr__ self._setup(name) File "C:\..\django\conf\__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "C:\..\django\conf\__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\..\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File … -
Save method of custom WagtailAdminPageForm called multiple times, even on page load: How to trigger custom save action only once on save?
I want to automatically generate field content based on another, editor-filled field for a wagtail page model on page save. I followed the wagtail docs and I am able to populate and save a field programmatically on page save/publish: from wagtail.models import Page from wagtail.admin.forms import WagtailAdminPageForm class TestPageForm(WagtailAdminPageForm): def clean(self): cleaned_data = super().clean() print("-> called TestPageForm.clean()") return cleaned_data def save(self, commit=True): page = super().save(commit=False) print("-> called TestPageForm.save()") # process something, save result to instance field, e.g.: # page.pdf_cover_image = get_cover_image(self.cleaned_data["pdf"]) return page class TestPage(Page): base_form_class = TestPageForm But the forms clean() and save() methods are called multiple times, even when I did not expect them to be called at all: Requesting the page instance via wagtail backend: http://127.0.0.1:8000/admin/pages/139/edit/ ⇒ [10/May/2023 09:03:50] "GET /admin/pages/139/edit/ HTTP/1.1" 200 71082 [...assets...] -> called TestPageForm.clean() -> called TestPageForm.save() [10/May/2023 09:03:51] "GET /admin/pages/139/edit/preview/?in_preview_panel=true&mode= HTTP/1.1" 200 0 [10/May/2023 09:03:51] "DELETE /admin/pages/139/edit/preview/ HTTP/1.1" 200 17 -> called TestPageForm.clean() [10/May/2023 09:03:51] "POST /admin/pages/139/edit/preview/ HTTP/1.1" 200 40 -> called TestPageForm.clean() -> called TestPageForm.save() -> called TestPageForm.clean() -> called TestPageForm.save() [10/May/2023 09:03:51] "GET /admin/pages/139/edit/preview/?in_preview_panel=true&mode= HTTP/1.1" 200 0 So how do I trigger a custom save()-action which will only be called once and only on page save()? -
Why is this django model coming undefined when using it in the same file?
I am using Django and trying to set a Foreign Key on a model that has its relating model under it. I have a foreign key called on Candidates Applied that is related to the Job model under it. The error is ""Job" is not defined", but its just under it. Does Django need a specific order when using model relations within the same file? I put stars around the highlighted error. class CandidatesApplied(models.Model): job = models.ForeignKey(**Job**, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.SET_NULL, null = True) resume = models.CharField(max_length=200) appliedAt = models.DateTimeField(auto_now_add=True, null=True) coverLetter = models.CharField(max_length=3000, null=True) class Meta: default_related_name = 'candidates_applied' class Job(models.Model): title = models.CharField(max_length=200, null=True) description = RichTextField(blank=True, null=True) email = models.EmailField(null=True) featured = models.BooleanField(default=False, auto_created=False) expiredAt = models.DateField(default=date.today, auto_now=False) address = models.CharField(max_length=100, null=True) job_country = models.JSONField(null=True) job_facebook = models.CharField(max_length=100, null=True) job_twitter = models.CharField(max_length=100, null=True) job_state = models.JSONField(null=True) jobType = ArrayField(models.JSONField()) education = models.CharField( max_length=100, choices=Education.choices, default=Education.Bachelors ) job_city = models.JSONField(null=True) industry = models.CharField( max_length=100, choices=Industry.choices, default=Industry.Business ) experience = models.CharField( max_length=100, choices=Experience.choices, default=Experience.NO_EXPERIENCE ) minSalary = models.IntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(1000000)]) maxSalary = models.IntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(1000000)], null=True) positions = models.IntegerField(default=1) company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True) responsibilities = RichTextField(blank=True, null=True) skills = RichTextField(blank=True, null=True) lat = models.DecimalField(max_digits=9, decimal_places=6, null=True) long … -
Problem with React + Docker (Extremely long loading time)
I can’t say after what exactly these problems started, but it started already at the stage of completion of my project, before that everything worked correctly. The crux of the problem: when I do "npm start" without docker, the application starts quickly and works correctly, and when I run the application from a docker container, it starts for several minutes and does not automatically reload when I make changes to the project. Previously, there was no such behavior, the app worked as fast from the docker container as without it. Here is my docker-compose settings of my react app: version: "3.8" services: frontend: build: ./frontend container_name: frontend ports: - "3000:3000" command: npm start volumes: - ./frontend:/usr/src/frontend depends_on: - backend environment: - HTTP_PROXY=http://backend:8000 Dockerfile: FROM node:18-alpine WORKDIR /usr/src/frontend COPY package.json . COPY package-lock.json . RUN npm install EXPOSE 3000 The problem is exacerbated by the fact that sometimes, due to such a slow work of the docker container containing the react app, docker desktop freezes tightly and cannot stop the running react app image, cannot remove it, and after a reboot, the docker engine cannot start, it has to be completely reinstalled every time. How I tried to solve this problem: … -
Why is the content of the test.html file not showing up?
I am trying to send a lot of GET requests to my back-end, but can not understand what happening here viws.py: from django.views.generic import TemplateView class HomePageView(TemplateView): template_name = "pages/home.html" class AboutPageView(TemplateView): template_name = "pages/about.html" class TestPageView(TemplateView): template_name = "pages/test.html" def get(self, request, *args, **kwargs): num = request.GET.get('num') result = f"test {num} - status: ok" return HttpResponse(result) test.html: {% load static %} {% block title %}Test{% endblock title %} {% block content %} <!DOCTYPE html> <html> <body> <h2>Test server</h2> <form id="function_form"> <button type="submit" id="start_btn">Start</button> </form> <div id="result"></div> <script> document.getElementById("function_form").addEventListener("submit", function (event) { event.preventDefault(); for (let i = 1; i <= 1000; i++) { fetch('/test/?num=' + i) .then(response => response.text()) .then(data => { document.getElementById("result").innerHTML += data + "<br>"; }); } }); </script> </body> </html> {% endblock content %} urls.py: from django.urls import path from .views import HomePageView, AboutPageView, TestPageView urlpatterns = [ path("", HomePageView.as_view(), name="home"), path("about/", AboutPageView.as_view(), name="about"), path("test/", TestPageView.as_view(), name="test"), ] After I path to /test/ or, for example, /test/?num=2 I receive a page which has only "test 2 - status: ok" and nothing common with test.html. Why on /test there is no content that I expected to see? -
How to change Django abstract model to a real model?
Currently I have an abstract base model: class Work(models.Model): creator = models.ForeignKey(Person, null=True, blank=True, on_delete=models.PROTECT) name = models.CharField(max_length=400, null=True, blank=True) class Meta: abstract = True From which two other model inherits from: class WorkMusic(MPTTModel, Work): key = models.CharField(max_length=10, null=True, blank=True) tonality = models.CharField(max_length=20, null=True, blank=True) tempo = models.CharField(max_length=500, null=True, blank=True) class WorkVisual(Work): material = models.CharField(max_length=100, null=True, blank=True) material_original = models.CharField(max_length=100, null=True, blank=True) I realize now that it would be nice to have a table all both Musical and Visual Work together. I should have NOT made my Work model abstract. Is there a way to convert the Work model into not an abstract model? I tried removing: class Meta: abstract = True and loading my WorkMusic fixture (with only the fields in the Work model), hoping it would also create regular inheritance instances in the Work model. But that gave me unique key conflicts. Any other solutions to this issue? -
Filter one joined query with result of another query if result exists without altering filters of outer joined tables
I have the following tables: apartment class Apartment(models.Model): name = models.CharField(max_length=250, verbose_name="Apartment Name") review class Review(models.Model): apartment = models.ForeignKey(Apartment, on_delete=models.CASCADE, null=True) review = models.TextField(null=True) author = models.CharField(max_length=255, null=True) review_date = models.DateField(null=True) response class Response(models.Model): response = models.TextField() review = models.ForeignKey(Review, on_delete=models.CASCADE) responded_on = models.DateTimeField(auto_now_add=True) author = models.CharField(max_length=255) note class Note(models.Model): review = models.ForeignKey(Review, on_delete=models.CASCADE, null=True) current_user = models.IntegerField(null=True) modified_on = models.DateTimeField( auto_now=True,verbose_name='Last Modified on' ) unread note: class UnreadNote(models.Model): current_user = models.IntegerField(null=True) review = models.ForeignKey(Review, on_delete=models.CASCADE) note = models.ForeignKey( Note, on_delete=models.CASCADE, verbose_name='Last Read Note' ) modified_on = models.DateTimeField( verbose_name='Modified Date Of Last Read Note' ) I want to insert below logic into my raw query that I have constructed: unread note count: def get_note_count_by_review(review_id, user_id, start_date="", end_date=""): unread_note = UnreadNote.objects.filter( review_id=review_id, current_user=user_id ).order_by("-modified_on").first() fields = {'review_id': review_id} fields.update({ 'modified_on__gt': unread_note.modified_on} if unread_note else {} ) fields.update( {'review__review_date__gte': start_date, 'review__review_date__lt': end_date} if start_date and end_date else {} ) unread_note_count = Note.objects.filter(**fields).exclude( current_user=user_id ).exclude( current_user__isnull=True ).count() return unread_note_count My raw query so far: SELECT rw.id, a.name apartment_name, p.id property_id, rw.review_date, un.modified_on modified_on FROM review rw LEFT JOIN response re ON rw.id = re.review_id INNER JOIN apartment a ON a.id = rw.apartment_id INNER JOIN note n ON n.review_id = rw.id AND n.current_user != … -
how to implement onchange event in django
I have a project where I have to implement the postcoder API, My API is working fine but I need that it should hit API when I am writing the text in that check box Below I have mentioned what I have tried <form method="get"> <div class="col-12 col-md-6 col-xl-6"> <div class="form-group local-forms"> <input class="form-control" id="api_test" type="text" name="address_line1" style="padding-left: 35px;" placeholder="Address line 1" value="{{clinic_values.address_line_1}}"></input> <button id="hit_api_btn" type="submit">hit api</button> <select name="clinic_name1" class="form-control form-select" , aria-placeholder="select Clinic"> <option value="" disabled selected>Select Clinic Unique User Name</option> {%for clinic_lists in data%} <option value="{{clinic_lists}}">{{clinic_lists}}</option> {%endfor%} </select> </form> my script <script> function getApiData(inputVal) { // Make an AJAX request to the API endpoint onchange = "getApiData(this.value)" $.ajax({ type: "GET", url: "https://ws.postcoder.com/pcw/{apikey}/address/uk/{searchterm}", data: { apikey: 'PCWYH-SKTHC-UU3YL-Q27A4', searchterm: 'inputVal', }, success: function (response) { // Handle the API response console.log(response); }, error: function (response) { // Handle any errors that occur during the AJAX request console.log(response); } }); } </script> <script> function myFunction() { var x = document.getElementById("clinic_api").value; document.getElementById("api_test").value = x; } </script> <script> document.getElementById("hit_api_btn").addEventListener("click", function () { // Create a new AJAX request var xhr = new XMLHttpRequest(); // Set the URL and request method xhr.open("GET", "/clinic/create_clinic/"); // Set the response type to JSON xhr.responseType = "json"; // … -
without app in project django models not showing in admin
I've not created any apps in my django project, when I try to register the models if doesn't show up in admin, I've made and applied migrations. If I do this while creating app it works fine, but without app I face issues. Here's the code to models.py; from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name and admin.py; from django.contrib import admin from .models import Customer admin.site.register(Customer) I've gone through other questions, what I found is all about models in apps, or maybe I'm missing something. -
Post data with field in django REST framework
I am designing my API using serializers.ModelSerializer and viewsets.ModelViewSet. I can post the foreignKey value using the id, but I want to post it using the name. Here is an example of what I mean: I can post on this: curl --request POST \ --url http://127.0.0.1:8000/api/book/ \ --header 'Content-Type: multipart/form-data' \ --form author=1 \ --form name=MY_BOOK but I want do this: curl --request POST \ --url http://127.0.0.1:8000/api/book/ \ --header 'Content-Type: multipart/form-data' \ --form author=AUTHOR_NAME \ --form name=MY_BOOK I have try use to_internal_value it's work, but I think it want to know is there a better plan: def to_internal_value(self, data): data = data.copy() data['author'] = get_object_or_404(Author, name=data['author']).id return super().to_internal_value(data) Here in my code: class Author(models.Model): name = models.CharField(max_length=128, unique=True) def __str__(self): return self.name class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.CharField(max_length=128, unique=True) def __str__(self): return self.name class AuthorSerializer(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' Any help or explanation is welcome! Thank you. -
Can I run an ORM module import in Django without setting up a database?
in our application (a big monolith), we have a lot of "unit tests" that inherit from django TestCase. They are something like this: from django.test import TestCase class SomeTestCase(TestCase): def test_something(self): self.assertTrue(1) Running this simple test in our codebase, it takes around 27 seconds. As you can say, this is a really high number given how simple is the code being run. Nonetheless, if instead we be just inherit from the TestCase from unittest module, like this: from unittest import TestCase class SomeTestCase(TestCase): def test_something(self): self.assertTrue(1) The time needed goes down to 4 seconds. Which is still a little bit high, but you need to consider that we are using PyCharm connected to a docker compose environment, so there is a little bit of overhead in that side. So what we want to achieve, is able to run tests just inheriting from unittest in the cases where we can, and inherit from django TestCase where we need some access to the ORM. The main problem we have faced is imports of models. Everytime we try to run a test file inheriting just from unittest, there is an import somewhere of a django model, which triggers the following error: django.core.exceptions.AppRegistryNotReady: Apps … -
Middleware request user return Anonymous User when using DRF
I don't think there is another way round this part from editing DRF source code. I want to add a custom middleware to Django, but I'm using DRF TokenAuthentication and my middleware interceptor require that request.user is authenticated. Please, is there a better way to do it apart from my answer? -
Wagtail - Using different templates with the same page model
I am building a website with Wagtail/Django. Most of my pages consist of some text followed by a graph or table generated with Bokeh. The way I found to add the Bokeh and codes to each page is by using custom template tags. I have created a function that outputs the Bokeh code and I call this function using a template tag. Therefore a typical template in this site looks like: {% load customtemplatetag %} {% block content %} <div class="container py-4"> <h1> {{ page.header|richtext }} </h1> <p class="lead"> {{ page.plead|richtext }} </p> {% bokehgraph as bokehg %} {{ bokehg.1| safe }} {{ bokehg.0| safe }} </div> {% endblock %} Therefore, I have a page model with a dedicated template for each different type of Bokeh Output. It does not feels like the best way of doing it. Is there any way I can use the same model with different templates, or maybe a totally different approach that will enable me to use less page models and less templates?