Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model dynamically query ManyToManyField for values
The following code works fine for an object that has a ManyToManyField called references like this: res = [] for ref in MyBook.objects.get(id=some_id).references.values("f_name", "l_name"): res.append(ref) My question is, how can I dynamically get a pointer to references, given just the string "references"? Once I have an instance of the MyBook class like this: my_book_model = MyBook.objects.get(id=some_id) I don't know how to get the pointer to my_book_model.references. Once I have that pointer, then I can just pass the values array to the pointer.values(values_array) -
Filter and group by user age - Django
I'm making a chart table which i would like to group and count by integer range (ages) of the users in that object. Table for example: Name Age John 21 Steve 24 Dan 29 Mike 31 and my expected result is: [20-25] [26-31] 2 2 I was playing around with the annotate function of Django but couldn't figure it out so far. Any suggestions aboout this? My views.py: qs = Post.objects.filter(spot=spot).annotate( age_group = Case( When(attendant__profile__age__range=[21, 27], then=Value('21-27')).count(), When(attendant__profile__age__range=[29, 33], then=Value('29-33')).count(), default=Value('No group'), output_field=CharField(), ) ).values('age', 'age_group') models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday = models.DateField(null=True, blank=False) def age(self): return int((datetime.date.today() - self.birthday).days / 365.25) -
HyperlinkedRelatedFIeld and OneToOne relationship - object has no attribute
For my app I have offices and HR users (users with an OneToOneField to HRProfile), and I want to be able to assign HRs to offices. The issue I'm facing is that I just can't access the User's 'email' field when trying to look it up through a HyperlinkedRelatedField on an OfficeSerializer. Relevant models: class User(AbstractBaseUser, PermissionsMixin): ... email = models.EmailField(unique=True) ... from polymorphic.models import PolymorphicModel class Profile(PolymorphicModel): ... related_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="profile", ) ... class HRProfile(Profile): some_hr_specific_field = models.CharField() def __str__(self) -> str: return self.related_user.email class Office(models.Model): ... assigned_hrs = models.ManyToManyField( "users.HRProfile", related_name="offices", blank=True ) ... View: class UserViewSet( GenericViewSet, ): serializer_class = UserSerializer queryset = User.objects.all() lookup_field = "email" lookup_url_kwarg = "email" lookup_value_regex = "[\\w@.]+" ... # the OfficeViewSet just has the two required fields (queryset and serializer) And the OfficeSerializer I'm having trouble with: class OfficeSerializer(serializers.HyperlinkedModelSerializer): ... assigned_hrs = serializers.HyperlinkedRelatedField( queryset=HRProfile.objects.all(), view_name="api:user-detail", lookup_field="related_user.email", many=True, ) ... The above raises 'HRProfile' object has no attribute 'related_user.email' which I don't know what to make of, since the HRProfile.__str__ has no issues resolving the self.related_user.email path correctly for a given user. I tried it with source='assigned_hrs.related_user', lookup_field='email' but to no avail. Also, I tried replacing the HyperlinkedRelatedField with an … -
Django Forms Validation Check is not working
I am giving this validation rule in my django forms, so when the field is none then it will rasie validation error but validationcoming ervey time , i meant when is none or not none i am getting the validationerror every time, How i solve this issue. models.py class Check(models.Model): use_for_car = models.BooleanField(default=False) Forms.py class CheckForm(forms.ModelForm): translated_names = TranslationField() def clean(self): cleaned_data = super(CheckForm, self).clean() use_for_car = self.cleaned_data.get("use_for_car") if use_for_car is None: raise ValidationError("Use For Car NEED TO BE FILLED ") return use_for_registrations class Meta: fields = "__all__" model = models.Check -
How can I shutdown the server when I exit the browser tab?
How can I shutdown the server when I exit the browser tab django open server django in django after server and open website in tab How can I make the server shutdown if all tabs on the site are closed? Also, can I control the server to be open in the background and not in the terminal? I have tried handling the beforeunload event window.addEventListener('beforeunload', function(e) { e.returnValue = 'if you exit?'; //required for Chrome }); But this event only works when the page is refreshed and does not work when the tab is closed -
Use model instance in custom templatetag
How can i get current instance model in templatetag, like: from django import template from users.models import Product register = template.Library() @register.simple_tag(name='description_tag') def description_tag(): custom_description = Product.product_description return custom_description with this a get the object : <django.db.models.query_utils.DeferredAttribute I have no ideia to get a current instance model, any tip? -
Has anyone had this error in manage django
could you help me? Thank you for this one already. I'm having a problem exiting the finish when I run manage, and the localhost "http://127.0.0.1:8000" is not active apparently, I'm using Opera GX, and in it the page appears as On the Local Server Page: Unable to access website Connection to 127.0.0.1 was refused. Try: check connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED" The error that appeared in the terminal is as follows: Note (I'm using Python 3.10 and localhost Django) (venv) PS C:\Users\gabri\OneDrive\Desktop\ProjectDjango> & "c:/Users/gabri/OneDrive/Desktop/ProjectDjango/venv/Scripts/python.exe" "c:/Users/ gabri/OneDrive/Desktop/ProjectDjango/manage.py" Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth] changepassword createsuperuser [contenttypes] remove_stale_contenttypes [django] check compilemessages createcachetable dbshell difsettings dumpdata flush inspectdb loaddata makemessages makemigrations migrate sendtestemail shell showmigrations sqlflush sqlmigrate sqlsequencereset squashmigrations startapp startproject test testserver [sessions] clearsessions [staticfiles] collectstatic findstatic runserver -
why am I getting 304 status code trying to get gif pic from cache
I made a blog on Django and added images to form. While I add .jpg or .png pics I have now problem, evrth works, but once I try to add a .gif pic - it doesn't add to post. Another interesting fact, that when I try to edit this post and add that very .gif pic or any other .gif - it works. when I press post button I see next logs: [21/Jun/2022 19:03:04] "POST /create/ HTTP/1.1" 302 0 [21/Jun/2022 19:03:05] "GET /profile/Natuska/ HTTP/1.1" 200 6925 [21/Jun/2022 19:03:05] "GET /media/cache/27/b6/27b6ff73a4d6cea2aa42a8ff16d888b6.jpg HTTP/1.1" 304 0 [21/Jun/2022 19:03:05] "GET /media/cache/3a/11/3a11ddc3f6d23b024579611a813df2f4.jpg HTTP/1.1" 304 0 [21/Jun/2022 19:03:10] "GET /profile/Natuska/ HTTP/1.1" 200 6925 [21/Jun/2022 19:17:09] "GET /posts/42/ HTTP/1.1" 200 2847 As I understand, I have some problems with cache. Obj not modified. But how it can be if it was just created here is my views.py file: @login_required def post_create(request): template = 'posts/create_post.html' is_edit = False form = PostForm(request.POST or None) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('posts:profile', username=request.user) context = { 'form': form, 'is_edit': is_edit } return render(request, template, context) @login_required def post_edit(request, post_id): template = 'posts/create_post.html' post = get_object_or_404(Post, pk=post_id) form = PostForm( request.POST or None, instance=post, files=request.FILES or None, … -
When an option selected I wanna change the other select tags options
In my Django template I have two select tag. I want to change the second tag to be linked to the first. For example when in first tag animals option select I want to show the animals on the second select tag. When plants select in first tag I want to show plants in the second select tag. How can I do this? (animals or plants) <select id="creatures"> {% for x in list %} <option value="{{x.creature}}">{{x.creature}}</option> {% endfor %} </select> <select id="instances"> {% for y in instances %} <option value="{{y.instance}}">{{x.instance}}</option> {% endfor %} </select> -
Configure VSCODE to step into Django Model
How to configure vscode to be able to step into Django Model? I use pipenv, django & vscod. The python path is setup correctly but it just cannot understand the methods within the django model. Here is a picture as a reference. Thank you! Note pm comes from People.objects.get... -
ERROR while ingegrating MongoDB with Django on windows
I am trying to integrate MongoDB and Django. but when i run the code python manage.py runmigrations app_name i am getting the error: File "C:\Users\Gourav\Envs\test\lib\site-packages\django\db\utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' and utils.py line 119 to 136 code looks like; builtin_backends = [ name for _, name, ispkg in pkgutil.iter_modules(django.db.backends.__path__) if ispkg and name not in {"base", "dummy"} ] if backend_name not in ["django.db.backends.%s" % b for b in builtin_backends]: backend_reprs = map(repr, sorted(builtin_backends)) raise ImproperlyConfigured( "%r isn't an available database backend or couldn't be " "imported. Check the above exception. To use one of the " "built-in backends, use 'django.db.backends.XXX', where XXX " "is one of:\n" " %s" % (backend_name, ", ".join(backend_reprs)) ) from e_user else: # If there's some other error, this must be an error in Django raise every required directories is already installed in my virtual environment. pip list gives following result; asgiref 3.5.2 Django 4.0.5 django-mongoengine 0.5.4 djongo 1.3.6 dnspython 2.2.1 mongoengine 0.24.1 Pillow 9.1.1 pip 22.1.2 psycopg2 2.9.3 pymongo 4.1.1 python-snappy … -
Django Class Based View - How to access POST data outside of post() method
I have a CBV based on a TemplateView It has a post(self) method to access user input. Also, it has a template_name property which should be populated with data from post(). No Django models or forms are used here. Attempt to extract data within post method: # views.py class ReturnCustomTemplateView(TemplateView): def post(self, *args, **kwargs): chosen_tmplt_nm = self.request.POST.get('tmplt_name') print(chosen_tmplt_nm) # correct value. # how do I use it outside this method? (like bellow) template_name = chosen_tmplt_nm ... or is there any other way I can get the data from request.POST without def post()? Thanks in advance! -
Can django AutoField be used for custom increment logic in addition to the separate automatic ID AutoField?
I have the following model: class Lot(models.Model): parent_lot_number = models.IntegerField(default=0) child_lot_number = models.IntegerField(null=True, blank=True) I want the following behavior: parent lot number should increment only when the user enters data in a specific form that is creating a new parent child lot number should increment all the time, within each parent For example, the following should be valid data for Lot records: parent_lot_number: 1, child_lot_number: null parent_lot_number: 1, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 2 parent_lot_number: 2, child_lot_number: null parent_lot_number: 2, child_lot_number: 1 parent_lot_number: 1, child_lot_number: 3 parent_lot_number: 3, child_lot_number: null Right now, I have working business logic to do this in my views/forms by getting the max of child_lot_number and parent_lot_number, then assigning the value after the record is created. Instead, can I accomplish this by removing the default=0 on parent_lot_number and using AutoField? When I set parent_lot_number = models.AutoField() I receive errors that "NOT NULL constraint failed: main_lot.parent_lot_number" or "ValueError: Model main.Lot can't have more than one auto-generated field." because of django's hidden ID column. This is a column I cannot drop. -
Can I access same django website on another computer connected with LAN with my computer?
Hey I am trying to access my django webapp on an external machine within my local network. but I am having issues. Below you are the things I have done. But no success. DEBUG = True ALLOWED_HOSTS = ['*'] at this point i've already added port 9595 as an inbound rule within windows firewall. Inbound rules were added on the machine running : python manage.py runserver 0.0.0.0:9595 second machine on network: second-machines-ip-address:9595 first-machines-ip-address:9595 result: empty page/no success. would you have any ideas as to why this is happening? -
How to create a query that shows cases for all status?
I have a problem in my Django project. I have some cases like; Case Type Status Sub Case Stage Volleyball 2020 finished win Basketball 2022 pending none Basketball 2021 finished loss Volleyball 2020 finished win I want to create a query for example are there how many cases is volleyball - 2020 - finished - win or are there how many cases is basketball - 2021 - finished - loss There are a lot of cases with different attributes, I have to count them with a dynamical query. Maybe pandas can help me with that but I don't know. Any idea can help me. -
What's the best way to load a ML model with Django
I'm deploying a Machine Learning model (Named Entity Recognition) with Django. In short, the user chooses a field (Politics or Science for example) and writes a text in a search area. Then the model identifies the named entities in the text. My problem is that the ML model (encoder) is loaded each time the view is triggered, which slows down the process. Any idea how to optimize this and load it only once ? My views.py : def search_view(request): if request.POST: field = request.POST['field'] query = request.POST['query'] encoder = load_encoder(field) results = Ner_model(query,encoder) context['result'] = results return render(request,'ner/results.html', context) Thanks! -
how to send flutter firebase notification using dcm-django
I am trying to send notification to flutter app from firebase. It sends notification well while sending from: https://console.firebase.google.com/project/nadir-d4ec4/notification/compose but I want to connect/control firebase with django. so, django will call firebase api asking it to send notification to flutter app. django package used: fcm-django settings.py is only file i have edited for that and settings.py contains: INSTALLED_APPS = [ # other apps "fcm_django" ] FIREBASE_APP = initialize_app() FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "87-digit string copied from:`project settings/cloud messenging` of firebase app", "APP_VERBOSE_NAME": "[string for AppConfig's verbose_name]", "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, # True/False } I could not find what APP_VERBOSE_NAME is supposed to be so left as it is. and I want to send notification using: python3 manage.py runserver from fcm_django.models import FCMDevice device = FCMDevice.objects.all().first() device.send_message("Title", "Message") device.send_message(data={"test": "test"}) device.send_message(title="Title", body="Message", icon=..., data={"test": "test"}) but # FCMDevice.objects.all() is giving empty list instead of users so no user to send notifications. I want list of user to send notifications to. code: django: https://github.com/Aananda-giri/uzme_backend/ flutter: https://github.com/Yogeshpanta/nadir -
How to update nested serializer field with many=True
I'm having trouble in updating the serializer data that have nested serializer field, please if someone have any idea to it with best practice i will appreciate your answer! class SerializerA(serializers.ModelSerializer): anyfielda = serializers.CharField() class SerializerB(serializers.ModelSerializer): anyfieldb = serializers.CharField() nested_field = SerializerA(required=True, many=True) How to implement the update method please guide! I'm able to do create but update does not allowed as it is asking for ListSerializer must, I want to know if there is any other way! -
Apache2 does not find python3.8 based virtual env and load python3.6 based env
i have an issue with a django based application deployment with apache2 on ubuntu18.04 with python3.8. I installed the mod_wsgi and apache2 as: sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi-py3 I setup venv folder in the project folder. I get error logs as: Error Log 1 [Tue Jun 21 08:34:13.966782 2022] [mpm_event:notice] [pid 660:tid 140673610189760] AH00491: caught SIGTERM, shutting down [Tue Jun 21 20:11:41.285936 2022] [mpm_event:notice] [pid 32599:tid 139678582156224] AH00489: Apache/2.4.29 (Ubuntu) mod_wsgi/4.5.17 Python/3.6 configured -- resuming normal operations [Tue Jun 21 20:11:41.287426 2022] [core:notice] [pid 32599:tid 139678582156224] AH00094: Command line: '/usr/sbin/apache2' Error Log 2 [Tue Jun 21 20:11:44.374973 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Target WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py' cannot be loaded as Python module. [Tue Jun 21 20:11:44.375046 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] mod_wsgi (pid=32600): Exception occurred processing WSGI script '/home/$USER/{{project_name}}/{{project_name}}/wsgi.py'. [Tue Jun 21 20:11:44.375175 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] Traceback (most recent call last): [Tue Jun 21 20:11:44.375230 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] File "/home/$USER/{{project_name}}/{{project_name}}/wsgi.py", line 12, in <module> [Tue Jun 21 20:11:44.375244 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] from django.core.wsgi import get_wsgi_application [Tue Jun 21 20:11:44.375272 2022] [wsgi:error] [pid 32600:tid 139678384367360] [remote 78.180.30.203:4742] ModuleNotFoundError: No module … -
How to render non-model objects in django admin?
I have the following model listed in Django admin already with the following view: class BookTabularInline(admin.TabularInline): model = Book @register(Bookcase) class BookcaseAdmin(admin.ModelAdmin): inlines = [BookTabularInline] The changes I want to make is: Instead of returning all the Books associated with Bookcase, I only want to return specific ones via queryset for example: Books.objects.filter(isAvailable=True, bookcase=bookcase).order_by("name"). How can I accomplish this? Instead of returning the model (Book) from this queryset, I want to return a BookPublicObject with different attributes inline, but BookPublicObject is a dataclass and not a Django model. Is this possible? -
Getting 500 error with Django via Ajax request, even though Django receives the request and is returning data
I have a click function that calls the Ajax request as shown to a url defined in urls.py. I can see that django is getting the data because I have print statements in views.py which print the data that will be passed back to frontend, but I end up getting this error: "GET /comment-data/?asset=total&timestamp=1654957681 HTTP/1.1" 500 145. If anyone's run into this before, much help is appreciated! Ajax call urls.py views.py (yes I know I have a bunch of unused variables) -
Unable to log in with provided credentials in DRF
I get the error { "non_field_errors": [ "Unable to log in with provided credentials." ] } whenever I do http://127.0.0.1:8000/api-token-auth/ and pass in my username and password. what's confusing is that when i run the post with my superuser account it works (i get my account token) though i noticed that my superuser's password is hashed but my normal account password isn't models.py def create_user(self, email, password, **other_fields ): if not email: raise ValueError("you must add an email") email = self.normalize_email(email) user = self.model(email =email, password = password, **other_fields) user.set_password(password) user.save(using=self._db) return user.email def create_candidate(self, email, password, **other_fields ): user = self.create_user(email, password, **other_fields) user.is_candidate = True user.save(using=self._db) return user.email def create_superuser(self, email, password, **other_fields ): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_candidate', False) if other_fields.get('is_staff') is not True: raise ValueError('superuser must be assigned is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('superuser must be assigned is_superuser=True') return self.create_user(email, password, **other_fields) -
Bootstrap 5 - Navbar - Logo/Brand Text Left - Menu Center - Search Right
I am trying to make a Navbar in Bootstrap 5. I would like to have the Logo (In my case this is just some fancy text) on the left. I would then like the menu centered and my search field on the right. The issue I seem to be having is when I have managed to get them lined up like this, the menu is going in the center of the search and logo divs, which due to logo size etc hasn't necessarily been the middle of my screen like I want. I have been at it for days trying different things on her but just can't seem to get it right. I also want the mobile menu to collapse and include the search. The mobile menu should then have the logo aligned in the center and the collapse button just below it also centered. The latest code I have tried is this: index.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{% endblock %}Life With Vicky</title> <meta name="description" content="{% block meta_description %}{%endblock %}"> {% block canonical %}{%endblock %} {% block opengraph %}{%endblock %} <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> <link … -
How to manage session with 3rd party API in Django?
Context: I have a Django based application. This application has various REST API endpoints where users can gather data. Some of this data needs to be pulled from a third-party API. This external API uses basic authentication. In order to fetch this data, I have the following code implemented in my endpoint logic. def metadata(jira_key: str, format=None): username = "example" password = "example" try: print(f"fetching {jira_key} with '{username}' credentials") url = f"https://external.api.com/issue/{jira_key}" session = requests.Session() session.auth = username, password headers = {'Content-Type': 'application/json'} response = session.get( url, headers=headers) print(f"response: {response.status_code}") return response except Exception as e: message = {"error": "Uncaught error", "message": str(e)} return message Long story short; it works! This endpoint is essentially just a proxy for another API. This is done for security purposes. However, I have been experiencing lock-outs where permission for the service account needs to be reinstated periodically... I suspect the session is being generated every time the endpoint is hit. So my question is this: How can I implement a persisted request.Session() with basic auth that is established at build time, and reused for each requests? Thanks for your help in advance! :) -
Timeout error in django send_mail program
I am doing a send_mail function in django and connected mysql database with it to store the name and subject values. I am using the smtp backend server to connect the mail and django. The port used is 587. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mail_test', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', 'OPTIONS':{ 'init_command':"SET sql_mode='STRICT_TRANS_TABLES'" } } } ---- DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'swarai.bot@gmail.com' EMAIL_HOST_PASSWORD = 'pfxbswfjgligavgb' ** This is my views.py** from django.views.generic import FormView, TemplateView from .forms import EmailForm from django.urls import reverse_lazy from mailapp.models import Email from django.shortcuts import render class MailView(FormView): template_name = 'index.html' form_class = EmailForm success_url = reverse_lazy('mailapp:success') def form_valid(self, form): # Calls the custom send method form.send() return super().form_valid(form) def registered(request): name = request.POST['name'] email = request.POST['email'] inquiry = request.POST['inquiry'] message = request.POST['message'] person = Email(name=name, email=email, inquiry=inquiry, message=message) person.save() return render(request, 'success.html') class MailSuccessView(TemplateView): template_name = 'success.html' I am getting timeout error whenever I submit the page. I tried to add the port 587 using control panel. But then also, I am getting the same error. I don't know whether this error is …