Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating subdomain in django
I want to know the proper way of creating subdomain in django. Take for instance, a django project that has more than one apps and you want to assign subdomain to each. Apart from using django-hosts; what can one do in production especially if one deploys to digitalocean with gunicorn and nginx? Note: I've tried django-hosts which worked well locally but did flopped in production as my static files couldn't be located. I've search online and I don't seem to see a solution to this. Thanks in advance -
Django objects filter to search both unique and combined fields with exclusivity
I am trying to create a search function for a Django query set, which is able to search by unique keywords but also have exclusivity. For example, if I search 'John' I would like all Johns returned, if I search 'Smith' I would like all the Smiths returned, but if I search 'John Smith', I only want 'John Smith(s)' returned. I have tried several methods: Attempt 1 - views.py This only returns results with an identical keyword. i.e. returns all John's or Smith's only, but search John Smith returns nothing: if query: data = Profile.objects.filter( Q(first_name__icontains=query) | Q(last_name__icontains=query) | Q(username__username__icontains=query) | Q(email__icontains=query) | Q(telephone__icontains=query) | Q(mobile__icontains=query) | Q(job_title__icontains=query) | Q(department__icontains=query) | Q(address__address__icontains=query) ).distinct() Attempt 2 - views.py This returns all John's and Smith's, and searching John Smith still returns all John's and Smith's. if query: search = [] query_set = query.split() for word in query_set: search = Profile.objects.filter( Q(first_name__icontains=word) | Q(last_name__icontains=word) | Q(username__username__icontains=word) | Q(email__icontains=word) | Q(telephone__icontains=word) | Q(mobile__icontains=word) | Q(job_title__icontains=word) | Q(department__icontains=word) | Q(address__address__icontains=word) ).distinct() data = list(set(search)) Are there any ideas on how to solve this? -
"python manage.py dbshell" for other DB Command-Line Clients (Django)
I read the documentation about "dbshell". Then, it says: Runs the command-line client for the database engine specified in your ENGINE setting, with the connection parameters specified in your USER, PASSWORD, etc., settings. For PostgreSQL, this runs the psql command-line client. For MySQL, this runs the mysql command-line client. For SQLite, this runs the sqlite3 command-line client. For Oracle, this runs the sqlplus command-line client. So, as the documentation says, with the command below, it's possible to run(open) DB Command-Line Clients for PostgreSQL, MySQL, SQLite and Oracle: python manage.py dbshell My question: Is it possible to run(open) DB Command-Line Clients for other databases such as MSSQL, MongoDB, etc? -
Django dumpdata can`t put Cyrillic characters into data file
while making python manage.py dumpdata(doesnt matter what format I choose) I got strange data instead of Cyrillic words: pk: 5 fields: name: ┼ъчюЄшўэ│ Ёюёышэш slug: exotic-plants parent: null lft: 1 rght: 2 tree_id: 5 level: 0 model: store.category Maybe someone can know how to overcome this problem -
Formatting paragraphs with Django and html
I am makeing a blog and I have a problem Whenever I type out a long essay to post that has paragraphs the formatting of the paragraphs does not show up. For example: I type: Paragraph one Paragraph two What gets put on the page: Paragraph one Paragraph two How do I incorporate the proper formatting into the HTML? Any help would be apriceated -
Subdomain created with django-host not styled on prodluction
I recently deployed a django project to digitalocean. This project has some django apps and implemented django-hosts for subdomain configuration. While this worked well locally, static files could not be found on navigating to the subdomain after deploy to digitalocean. All the other parts of the websites are styled properly. Question: Is there anything I can do to correct this anomaly? Is there any other way to do this without having to use django-hosts. Here is the website: kingdomleadsafrica.org The subdomain is: executives.kingdomleadsafrica.org Thanks -
ProgrammingError at /: relation "news_news" does not exist LINE 1: ...news"."image", "news_news"."image_thumbnail" FROM "news_news
https://valia-app.herokuapp.com/ I got a ProgrammingError in my project. What should I do? base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}Новости{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/style.css' %}"> </head> <body> {% include "navbar.html" %} {% block content %} {% endblock %} {% block js %} {% endblock %} </body> </html> views.py: def index(request, *args, **kwargs) : qs = News.objects.order_by("-id") return render(request, "index.html", {"news_list": qs}) What I did wrong? -
pass variable from view to form initial in django
Sorry, I am new to django. I don't know how to do: #Main objective: read yaml file, pass the Resize variable from view to form, and set the form resize field to inital value. please help. thanks. #views class preprocessing(FormView): video_para = read_yaml() Resize = video_para['Resize'] def preprocessing_view(request): if request.method == 'POST': form = preprocessing_form(request.POST or None) if form.is_valid(): new_form = form.save(commit=False) Resize_new = form.cleaned_data['Resize'] new_form.Resize_new = form.cleaned_data['Resize'] new_form.save() else: form = preprocessing_form() context= { 'form': form, 'Resize' : Resize } return render(request,'preprocessing.html', context) #forms class preproces sing_form(forms.ModelForm): def __init__(self, *args, **kwargs): self.Resize = kwargs.pop('Resize') super().__init__(*args, **kwargs) Resize = forms.BooleanField(initial=Resize) def save(self): Resize = self.Resize class Meta: model= preprocessing_class fields= ["Resize"] -
How to query a Django Model with ForeignKey attribute
I have this simple Django Model with a ForeignKey attribute that I want to query to get a single object from. It is returning DoesNotExit although the object I want is in there, I'm confused. Here's the Model: class MemberBio(models.Model): member_id = models.ForeignKey(User, on_delete=models.CASCADE) form_no = models.IntegerField() middle_name = models.CharField(max_length=50) staff_no = models.CharField(max_length=10) gender = models.CharField(max_length=10) location = models.CharField(max_length=200) phone = models.CharField(max_length=11) def __str__(self): return self.staff_no This is the query: member_bio = MemberBio.objects.get(member_id=pk) where pk is a value which I know exist in the Model -
cannot import name 'EpollSelector' from 'selectors'
When I run the command python manage.py runserver in Django, it throws the error - "ImportError: cannot import name 'EpollSelector' from 'selectors' (C:\Users\abcd\Anaconda3\lib\selectors.py)" Can anyone please help me understand this and how to resolve this? -
Django forum submit not picked up by view
So I thought when I press submit on the form (login page), that it would trigger my loginPage View and hit the request.POST == 'Method' becuase the form method is post but it is not doing this and I cannot login. Bit confused since this worked before and I haven't touched it since. Any ideas guys? I have a html login page called login_register.html. Below, <form method="POST" action=""> {% csrf_token %} <div class="row center"> <input type="text" name="username" placeholder="Username" autocomplete="off"></input>&nbsp; <input type="password" name="password" placeholder="Password" autocomplete="off"></input>&nbsp; <input type="submit" class="button-6-custom" value="login"></input>&nbsp; </div> </form> I have the urls.py file as well. Below, path('login/', views.loginPage, name='login'), And lastly, I have the View. Below, from django.contrib.auth.models import User def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username = user) except: print("Error - user / password incorrect, does not exist.") user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: print("User does not exist.") return render(request, 'base/login_register.html') -
'NoneType' object has no attribute 'id' after customizing authentication through simplejwt
I customized the validate function inside rest_framework_simplejwt so that when a user is authenticated it can trigger the user_logged_in signal so I can see if a user is logged in or not. The problem I have now is that when a user logs in but enters the incorrect login details I get the error message: AttributeError at /api/token/ 'NoneType' object has no attribute 'id' This is the full trace back: Traceback (most recent call last): File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\15512\anaconda3\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\15512\anaconda3\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\15512\anaconda3\lib\site-packages\rest_framework\views.py", line 469, in handle_exception \tokens.py", line 176, in for_user user_id = getattr(user, api_settings.USER_ID_FIELD) AttributeError: 'NoneType' object has no attribute 'id' Here is my validate function : class CustomTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], "password": attrs["password"], } try: authenticate_kwargs["request"] = self.context["request"] except KeyError: pass user = authenticate(**authenticate_kwargs) tokens = RefreshToken.for_user(user) user_logged_in.send(sender=user.__class__, request=self.context['request'], user=user) if not api_settings.USER_AUTHENTICATION_RULE(user): raise exceptions.AuthenticationFailed( self.error_messages["no_active_account"], "no_active_account", ) return { 'refresh': str(tokens), 'access': str(tokens.access_token), 'user': str(user), } This is the … -
Is there a way to get all subclasses of a class without having to import the modules the classes are in?
Using __subclasses__ only seems to work if the module where the subclasses are is imported somewhere. I want to be able to find all the subclasses of a certain class without importing them anywhere class A: pass class B(A): pass class C(A): pass In this example I would want to grab classes B and C and put them into a list. And to reiterate I want to do this without needing to do this anywhere in the project: from x.x.x import B. Background I am trying to create a library that when a request is made it sends a string with the request. With that string I want to do if subclass.name == string, instantiate sublclass and do something. I need the list of subclasses so I can loop over them and check this condition. -
how to load a img from static folder in python-Django
i try to build a portofolio website using html, css, js and django but i don't know how to load an image from assets in static folder this is the div code in html , i load the static block {% load static%} and also another images but in this i can't load it because A Syntax error will occur <div class="col-lg-5 align-items-stretch order-1 order-lg-2 img" style='background-image: url("assets/img/why-us.png");' data-aos="zoom-in" data-aos-delay="150">&nbsp;</div> -
Django: Resolve a related field to QuerySet type
Based on the official documentation: # Declare the ForeignKey with related_name class Tag(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="tags" ) name = models.CharField(max_length=255) # Return all tags Article.tags.all() My linter (django-pylint) is unable to type it porperly: Article.tags is Any, I expected a QuerySet[Tag]. Can I declare the Article.tags reference in the Article class? (preferred approach) from django.db.models.query import QuerySet class Article(models.Model): ... # Related field declaration tags: QuerySet[Tag] Article.tags.all() Or maybe I need to convert it every time I need it? tags_qs: QuerySet[Tag] = Article.tags tags_qs.all() In both scenarios, it looks heavy to implement for each related field. Of course, it's more a question for comfortable development experience than a critical issue. The goal is to allow my linter and other autocompletion/discovery tools to resolve related fields as QuerySet[T] type. Maybe I can't due to the design of the Python implementation, more than a Django issue. Is there any other alternative to fix this problem? -
I need help Template Django "for" "if"
I need to search for a particular object with the if conditions, in case nothing is found, the else is executed, the problem with this is that the else is executed for each object in the array, and I need it to only be executed after having traversed the entire array and the if condition has not been met, I have 4 objects in that array {% for horario in horarios %} <!--Lunes--> {% if horario.dia == 'Lunes' and horario.hora_inicio == '8:00' %} <td> Asignatura: {{horario.id_asignatura.nombre}}<br> Profesor: {{horario.rut_profesor.p_nombre}} {{horario.rut_profesor.ap_paterno}}<br> Sala: {{horario.id_sala.id_sala}} </td> {% else %} <td>Horario no disponible</td> {% endif %} {% endfor %} how I want it to look with the else what it actually looks like: -
Retrieving a child model's annotation via a query to the parent in Django?
I have a concrete base model, from which other models inherit (all models in this question have been trimmed for brevity): class Order(models.Model): state = models.ForeignKey('OrderState') Here are a few examples of the "child" models: class BorrowOrder(Order): parts = models.ManyToManyField('Part', through='BorrowOrderPart') class ReturnOrder(Order): parts = models.ManyToManyField('Part', through='ReturnOrderPart') As you can see from these examples, each child model has a many-to-many relationship of Parts through a custom table. Those custom through-tables look something like this: class BorrowOrderPart(models.Model): borrow_order = models.ForeignKey('BorrowOrder') part = models.ForeignKey('Part') qty_borrowed = models.PositiveIntegerField() class ReturnOrderPart(models.Model): return_order = models.ForeignKey('ReturnOrder') part = models.ForeignKey('Part') qty_returned = models.PositiveIntegerField() Note that the "quantity" field in each through table has a custom name (unfortunately): qty_borrowed or qty_returned. I'd like to be able to query the base table (so that I'm searching across all order types), and include an annotated field for each that sums these quantity fields: # Not sure what I specify in the Sum() call here, given that the fields # I'm interested in are different depending on the child's type. qs = models.Order.objects.annotate(total_qty=Sum(???)) So I guess I have two related questions: Can I annotate a child-model's data through a query on the parent model? If so, can I conditionally specify the … -
What is stored in database for Dropdown Single Select Box? (Django)
I have the Dropdown Single Select Box "Month" with 3 options "January", "February" and "March" as shown below: This is the code for the Dropdown Single Select Box "Month" in "Date" class below: # "store/models.py" from django.db import models class Date(models.Model): class Months(models.TextChoices): JANUARY = 'JAN', 'January' FEBRUARY = 'FEB', 'February' MARCH = 'MAR', 'March' # Here month = models.CharField(max_length=100, choices=Months.choices) And this is the old version code for the Dropdown Single Select Box "Month" in "Date" class below which is equivalent to the above code: # "store/models.py" from django.db import models class Date(models.Model): JANUARY = 'JAN' FEBRUARY = 'FEB' MARCH = 'MAR' MANTHS = [ (JANUARY, 'January'), (FEBRUARY, 'February'), (MARCH, 'March') ] # Here month = models.CharField(max_length=100, choices=MANTHS) Now, if I choose "February" and click on "SAVE", what is stored in database? "FEBRUARY"? "FEB"? or "February"? adf -
Django - How to create sub entries for each object in Models?
Example: Item Version S# abc1 abc1V abc1S# abc2 abc2V abc2S# Model class Hw(models.Model): item= models.CharField(max_length=30,default='') version= models.CharField(max_length=30,default='') serianlnumber= models.CharField(max_length=30,default='') now abc2 item has subitems and it has its subitems in it with their respective Versions and S#s Item Version S# abc2 abc2V abc2S# abc2sub1 abc2sub1V abc2sub1S# abc2sub_sub1 abc2sub1V abc2sub1S# abc3 abc3V abc3S# How do i create model/table like that or do i need to create different tables for each sub entries ? I could not find any specific documentation on this. Thanks -
CKeditor not working on template CreateVIew in Django
I just install Ckeditor and I try to add something new. I can see the Ckeditor is showing but I can not render on the template Create View. Anyone can give me some advice Model.py enter image description here Form.py enter image description here Views.py enter image description here Template enter image description here -
How Can I Reset User Password Using Django Class Based Views with Gmail Account
I want to implement a User Reset Password functionality in my Django application and I am getting this error : SMTPConnectError at /password_reset/ (421, b'Service not available'). I have done everything on my Gmail account by setting the 2 Steps Verification and Application Password which I used in my Django settings for the email. Here is my urls code: path('password_reset/', auth_view.PasswordResetView.as_view(), name = 'password_reset'), path('password_reset_done/', auth_view.PasswordResetDoneView.as_view(), name ='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/', auth_view.PasswordResetConfirmView.as_view(), name = 'password_reset_confirm'), path('reset_password_complete/', auth_view.PasswordResetCompleteView.as_view(), name = 'password_reset_complete'), Here is my setting.py code for the email: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_googlemail@gmail.com' EMAIL_HOST_PASSWORD = 'my_gmail_account_app_password' EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = 'Support Team <noreply@support.org>' Thanks in anticipation to your solutions/answers. -
Does Django is models property hit the database more than once?
I've searched in several places but I haven't found a satisfactory answer anywhere. I have these models: App bar class Bar(models.Model): name = models.CharField(max_lenth=50) text = models.TextField() App xyz class Xyz(models.Model): bar = models.ForeingKey(Bar, on_delete=models.CASCADE, verbose_name='Bar') App foo class Foo(models.Model): xyz = models.OneToOneField(Xyz, on_delete=models.CASCADE, verbose_name='Xyz') def bar_name(self): return self.xyz.bar.name def bar_text(self): return self.xyz.bar.text My first question is, on self.xyz.bar.name and on self.xyz.bar.text does hit in the database? If yes, how can i optimize it? I already tried this, but I'm not sure if it improves anything: def bar_name(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id).bar.name def bar_text(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id).bar.text And here comes my second question, using select_related(), I would create a single method like Sigleton pattern, something like this: def singleton_bar(self): return Xyz.objects.select_related('bar').get(pk=self.xyz_id) def bar_name(self): return self.singleton_bar().bar.name def bar_text(self): return self.singleton_bar().bar.text -
mysqlclient problem with python Python 3.10.4
(medinaenv) PS D:\medina> pip install mysqlclienty ERROR: Could not find a version that satisfies the requirement mysqlclienty (from versions: none) ERROR: No matching distribution found for mysqlclienty (medinaenv) PS D:\medina> pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.1.0.tar.gz (87 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [29 lines of output] running bdist_wheel running build running build_py creating build creating build\lib.win32-cpython-310 creating build\lib.win32-cpython-310\MySQLdb copying MySQLdb_init_.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb_exceptions.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\release.py -> build\lib.win32-cpython-310\MySQLdb copying MySQLdb\times.py -> build\lib.win32-cpython-310\MySQLdb creating build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-cpython-310\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-cpython-310\MySQLdb\constants running build_ext building 'MySQLdb.mysql' extension creating build\temp.win32-cpython-310 creating build\temp.win32-cpython-310\Release creating build\temp.win32-cpython-310\Release\MySQLdb "C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x86\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -Dversion_info=(2,1,0,'final',0) -D__version_=2.1.0 "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include\mariadb" "-IC:\Program Files (x86)\MariaDB\MariaDB Connector C\include" -ID:\medina\medinaenv\include -IC:\Users\pc\AppData\Local\Programs\Python\Python310-32\include -IC:\Users\pc\AppData\Local\Programs\Python\Python310-32\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.19041.0\um" "-IC:\Program Files … -
Django ListView class pagination filter query not effecting in pagination
i failed to include pagination in django list view pagination count shows without filter query any idea about to include fileter query in pagination calculation? assets_list = Assets.objects.filter(site=self.site,type__icontains="Asset") page = self.request.GET.get('page', 1) paginator = Paginator(assets_list, self.paginate_by) try: asset_data = paginator.page(page) except PageNotAnInteger: asset_data = paginator.page(1) except EmptyPage: asset_data = paginator.page(paginator.num_pages) context['assets'] = asset_data -
ckeditor not working on heroku deployment
I deploy my django blog to heroku but my ckeditor dosent work and after turning DEBUG = False and Add X_FRAME_OPTIONS = 'SAMEORIGIN' . This happend on when trying to runserver aswell when it was working with no problem before when i dident have DEBUG = False or X_FRAME_OPTIONS = 'SAMEORIGIN' . img1 img2