Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CREATE list from two Fields in Django
I don't know if there a possibilty to create a field model from two fields different model. for example, I have this two real model : class BaseOil(models.Model): BaseoilName = models.CharField(max_length=150) class Additif(models.Model): AdditifName = models.CharField(max_length=150) BaseoilName contain some composant and AdditifName contain some compostant too and different of BaseoilName, so I want to create a list from this two compostant in one list in another model exactly in Compostant field, like: class Fabrications(models.Model): Fab_fiche_Grade = models.ForeignKey(Lesfiches, on_delete=models.CASCADE) Composant = models.ForeignKey(BaseOil, on_delete=models.CASCADE, null=True, blank=True) I tried some tutorial from Youtube and from Django Project document, but I didn't succeed to have my objective. so thank you for helping to get it, and I will be very thankfull -
Duplicate check in list Django Python
Hi i have to check the overlapping and duplicate of string from the data , i could do it can anyone help me to find the duplicate of string . def overlap(a, b) -> bool: a_start, a_end, _ = a b_start, b_end, _ = b return a_start < b_end and b_start < a_end ls = [(100, 350,"a"), (125, 145,"a"), (200, 400, "d"), (0, 10, "a")] overlaps = set() for idx_a in range(len(ls)): for idx_b in range(len(ls)): if idx_a != idx_b: if overlap(ls[idx_a], ls[idx_b]): overlaps.add(ls[idx_a]) overlaps.add(ls[idx_b]) print(f"Number of overlaps: {len(overlaps)}") -
Django Rest Reverse Nested Relationships in Serializers
I am working on creating a GET only endpoint that shows the standings of a given season for a sports league. Honestly, at this point I have tried nearly everything with no luck. All other Serializers work fine so far and there is no issue with the way my database is setup. I have omitted many fields and tables due to the complexity, but anything relevant to the question is included below. First, let me show you the rough format of how I want to JSON to be returned. Sample Response (The end goal) { divisions: [ { "divisionName": "WEEKNIGHT B", "divisionId": "ee68d8ab-2752-4df6-b11d-d289573c66df", teams: [ { "teamId": "b07560bc-aac2-4c6c-bbfe-11a368137712", "statsId": "53852698-9b78-4f36-9a2e-4751b21972f9", "teamName": "FNA", }, { "teamId": "406eb5aa-6004-4220-b219-59476a3136d1", "statsId": "a96ebf10-87c5-4f19-99c3-867253f4a502", "teamName": "COPENHAGEN ROAD SODAS", }, ] }, { "divisionName": "WEEKNIGHT C", "divisionId": "4e1469ae-2435-4a3d-a621-19a979ede7c1", teams: [ { "teamId": "ebc7e632-073e-4484-85f9-29c0997bec25", "statsId": "cd6373a7-4f53-4286-80f2-eb3a8a49ee3a", "teamName": "HAWKS", "gamesPlayed": 29, }, { "teamId": "d8cda7a6-15f4-4e8f-8c65-ef14485957e4", "statsId": "4492a128-763a-44ad-9ffa-abae2c39b425", "teamName": "DUISLANDERS", }, ] } ] } Through the URL I am passing in the Season ID, so everything is based off the season id. Below is an example of how I can replicate the type of response I want, by iterating through some queries which I know is rather messy, but … -
Django-How to activate new env
i have an issue with activating my virtual env. I added the django library but cannot activate my django library. What should i do next ? https://i.stack.imgur.com/N9hCu.png -
Is there a way to change the set of languages for a field in django-translated-fields
I currently have a model which has a field called title which should have a translation to Japanese (JP). I am currently using a separate field for this translated version, but the django-translated-fields documentation says that there is a way of adding extra languages. My model actually looks like this: class MyModel(model.Model): title_en = models.CharField(max_chars=100) title_jp = models.CharField(max_chars=100) My settings actually look like this: LANGUAGES = [ ("en", "English"), ("es", "Spanish") ] The documentation says that there is a way to do this, but does not describe how. It is also possible to override the list of language codes used, for example if you want to translate a sub- or superset of settings.LANGUAGES. Combined with attrgetter and attrsetter there is nothing stopping you from using this field for a different kind of translations, not necessarily bound to django.utils.translation or even languages at all. The thing is I need to have a jp and an en translation, but not an es translation. Is there a way to completely change the languages used for the title field? -
my modal data remains same while I'm clicking different grids
In my Django project I'm trying to establish software showcasing through on click modal appearance. But the issue is I'm trying to get specific data on modal appearance while clicking on something, but it is showing similar data every time. help me on that buddy, thanks in advance. <div class="container software-showcase-trio"> <div class="row"> {% for maritime_content in maritime_project_content %} <div class="col-lg-3 col-md-3 col-sm-6"> <a href="#" class="text-decoration-none" data-bs-toggle="modal" data-bs-target="#maritime-software-modal"> <div class="software-block-trio" style="background-image:url({{media_url}}{{maritime_content.cover_image}});"> <div class="software-block-hover-trio"> <h1>{{maritime_content.title}}</h1> </div> </div> </a> <!-- Modal --> <div class="modal fade" id="maritime-software-modal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h6 class="modal-title" id="exampleModalLabel"></h6> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body maritime-software-modal-body"> <div class="maritime-modal-title"> <h1 class="fw-bold display-5">{{maritime_content.title}}</h1> </div> <img src="{{media_url}}{{maritime_content.cover_image}}" height="500" width="1000" alt=""> <div class="maritime-fields-title"> <div class="maritime-project-details"> <h3 class="fw-bold">Project Details</h3> <p class="">{{maritime_content.project_details}}</p> </div> <div class="maritime-problem-details"> <h3 class="fw-bold">Problem</h3> <p>{{maritime_content.problem_details}}</p> </div> <div class="maritime-solution-details"> <h3 class="fw-bold">Solution</h3> <p>{{maritime_content.solution_details}}</p> </div> <div class="maritime-technology-list"> <h3 class="fw-bold">Technologies</h3> <p>{{maritime_content.technology_list}}</p> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- modal --> </div> {% endfor %} </div> </div> -
Sending email with Django using Gmail not working
I'm new to Django and I want to send the email through my Django server using my Gmail account but unfortunately, I'm getting an error while sending emails even though I've put all credentials correctly there is one thing more in my Gmail account which is "less secure apps" that has to be enabled but this feature is no longer available in Gmail so now how can I send the emails in Django? error while sending the email b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a05600c4e8e00b0039c5642e430sm4688852wmq.20 - gsmtp' -
React.js doesn't display fetched image from Django
My component successfully fetches info (texts and images) from the Django backend but fails to display the images. related: react.js doesn't display fetched image I removed file 192png from manifest.js and HTML and it didn't work so I put them back again as advised. import React, { useState, useEffect, Fragment} from 'react'; import axios from 'axios'; import Carousel from 'react-elastic-carousel'; import './Schools.css'; import Test from '../assets/images/back.jpg'; const schoolBreakPoints = [ {width: 1, itemsToShow: 1 }, {width: 550, itemsToShow: 2 }, {width: 768, itemsToShow: 3 }, {width: 1200, itemsToShow: 4 }, ]; function Schools() { const [languageCenters, setLanguageCenters] = useState ([]); useEffect(() => { const config = { headers: { 'Content-Type': 'application/json' } }; const getLanguageCenters = async () => { try { const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/partners/list/`, config); setLanguageCenters(res.data); } catch (err) { } }; getLanguageCenters(); }, []); const getAllLanguageCenters = () => { let allLanguageCenters = []; let results = []; languageCenters.map(languageCenter => { console.log(languageCenter.photo) return allLanguageCenters.push( <Fragment key={languageCenter.id}> <div className='school__display'> <img className='school__display__image' src={languageCenter.photo} alt='school logo' /> </div> <h3 className='school__language__center'>{languageCenter.name}</h3> <p className='school__course'>{languageCenter.country}</p> <p className='school__course'>{languageCenter.language}</p> <p className='school__course'>{languageCenter.course}</p> <p className='school__about'>{languageCenter.note}</p> </Fragment> ); }); for (let i = 0; i < languageCenters.length; i += 20) { results.push( <div key={i} className='school__card__row'> <Carousel breakPoints={schoolBreakPoints}> … -
Email is not sending from django using gmail
I want to send the email through my Django server using my Gmail account but unfortunately, I'm getting an error while sending emails even though I've put all credentials correctly there is one thing more in my Gmail account which is "less secure apps" that has to be enabled but this feature is no longer available in Gmail so now how can I send the emails? error b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f14-20020a05600c4e8e00b0039c5642e430sm4688852wmq.20 - gsmtp' -
'function' object has no attribute 'collection'
I am new to google firestore, I followed their documentations to create connection to the database: import firebase_admin from firebase_admin import credentials from firebase_admin import firestore cred = credentials.Certificate("serviceAccountKey.json") firebase_admin.initialize_app(cred) db = firestore.client when i run the above code once is it fine, but for one more time it brings error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [2], in <cell line: 5>() 3 from firebase_admin import firestore 4 cred = credentials.Certificate("serviceAccountKey.json") ----> 5 firebase_admin.initialize_app(cred) 6 db = firestore.client File ~\anaconda3\envs\simulationtrackit\lib\site-packages\firebase_admin\__init__.py:71, in initialize_app(credential, options, name) 68 return app 70 if name == _DEFAULT_APP_NAME: ---> 71 raise ValueError(( 72 'The default Firebase app already exists. This means you called ' 73 'initialize_app() more than once without providing an app name as ' 74 'the second argument. In most cases you only need to call ' 75 'initialize_app() once. But if you do want to initialize multiple ' 76 'apps, pass a second argument to initialize_app() to give each app ' 77 'a unique name.')) 79 raise ValueError(( 80 'Firebase app named "{0}" already exists. This means you called ' 81 'initialize_app() more than once with the same app name as the ' 82 'second argument. Make sure you provide … -
summing up the values of a column in django framework
I have a model in my django web app and I have been trying to query the model in such a way that I can sum up values in the quantity column. I already have data in this model so I just need to add up all the values in the quantity column. class ProductInstance(models.Model): product=models.ForeignKey(Product,on_delete=models.RESTRICT,related_name='product') quantity=models.IntegerField() warehouse=models.ForeignKey(Warehouse,on_delete=models.RESTRICT,related_name='warehouse') I tried "ProductInstance.objects.sum(quantity)". It didnt work -
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>