Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best paradigm for django rest framework unit testing?
I have a Django project (drf) and I want to implement some unit tests for it. I found some different scenarios in implementations. Some of them define a class for each django model containing different methods for CRUD APIs: class FooTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass def test_foo_update(self): pass . . . . Some others define a class for each API view: class FooListCreateTestCase(TestCase): def setup(self): pass def test_foo_create(self): pass class FooRetriveUpdateDeleteTestCase(TestCase): def setup(self): pass def test_foo_update(self): pass and so on ... what is the best paradigm among them? -
js function is not defined in django template
I have just started learning Django and I tried to add simple js static file to my Django template. However I am not able to execute function in Django template due to Uncaught ReferenceError: myFunction is not definedat HTMLButtonElement.onclick. My function is very simple and it is within static folder at the project level static/js/script.js function myFunction() { alert("This is result of JS function!"); } At the project level I have the base.html within templates/base.html. Here it is: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>{% block title %}{% endblock %}</title> <script type="text/javascript" scr="{% static 'js/script.js' %}"></script> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div class="nav-bar"> <a href="{% url 'myapp:home' %}">Home</a> | <a href="{% url 'myapp:about' %}">About Us</a> | <a href="{% url 'myapp:services' %}">Our Sevices</a> | <a href="{% url 'myapp:info' %}">Info</a> | </div> <div class="page-content"> {% block content %} {% endblock %} </div> <div class="page-footer"> <a href="#" >Usefull links</a> | <a href="#" >Follow Us</a> | <a href="#" >Address</a> | <p id="copyright">&copy; 2022 Learning Django</p> </div> </body> </html> At the app level I have folder templates and inside several html files like myapp/templates/myapp/services.html. {% extends … -
Why do I get TypeError when running my Django project with Debug off?
So I've been running my Django project with Debug on, I know it's wrong, and now trying to make the change. But then, the project returned TypeError when I turned the Debug off: TypeError: expected str, bytes or os.PathLike object, not NoneType I tried digging into the issue a little more, and found out that the variable absolute_path of admin/js/jquery.js was None, as you can see in the Traceback below. I've got three clues regarding this issue: It happens in the django-cloudinary-storage library. It probably happened after running python manage.py collectstatic. I did not run this command up until now.. The project ran perfectly with Debug = True. It only happened with Debug=False. What do you think is the problem? Below is a part of my settings.py and full Traceback. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] Full Traceback: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 157, in inner_run handler = self.get_handler(*args, **options) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/contrib/staticfiles/management/commands/runserver.py", line 31, in get_handler handler … -
Django how to get object in one query to database
models.py class Post(models.Model): pass @property def views_count(self): return PostViews.objects.filter(post=self).count() class PostViews(models.Model): IPAddres= models.GenericIPAddressField(default="") post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="post_views_count",) date = models.DateTimeField(auto_now_add=True) views.py def get_posts(request, topic=""): posts = Post.objects.filter(status=Post.OPEN).select_related('author').prefetch_related('tags').select_related('category').select_related('post_views_count') posts.hml {% for post in posts %} {{ post.views_count }} {% endfor %} Due to the call of views, the number of sql queries grows by 10 hits.How do I get this data in place with the data received by the model Post? -
Unable to POST with ListCreateAPIView
Thank you very much for all your help. We are currently using Django to create a blog with membership features. I would like to allow only members to post articles, but I can't use POST while logged in. When not logged in, POST is available. What is wrong? models.py class Post(models.Model): title = models.CharField(max_length=100, blank=True, default='') content = models.TextField(blank=True, default='') def __str__(self): return self.title class Category(models.Model): name = models.CharField(max_length=100, blank=False, null=True, default='') posts = models.ManyToManyField(Post, related_name='categories', blank=True) class Meta: verbose_name_plural = 'categories' def __str__(self): return self.name serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ['id', 'title','content', 'categories'] class CategorySerializer(serializers.ModelSerializer): name = serializers.CharField(required=False, allow_null=True, allow_blank=True) posts = PostSerializer(many=True, read_only=True) new_posts = serializers.PrimaryKeyRelatedField( queryset=Post.objects.all(), many=True, write_only=True, required=False) class Meta: model = Category fields = ['id', 'name', 'posts', 'new_posts'] def create(self, validated_data): category = Category.objects.create() category.name = validated_data.pop('name', None) new_posts = validated_data.pop('new_posts', None) category.posts.set(new_posts) category.save() return category def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.posts.set(validated_data.get('new_posts', instance.posts)) instance.save() return instance views.py class PostList(generics.ListCreateAPIView): queryset = Post.objects.all() serializer_class = serializers.PostSerializer permission_classes = (IsAdmin,) # permission_classes = (AllowAny,) permissions.py class IsAdmin(permissions.IsAdminUser): def has_permission(self, request, view): if request.method in permissions.SAFE_METHODS: role_slug = None if not request.user.is_anonymous and request.user.role is not None: role_slug = request.user.role … -
How does distinct parameter work with the Count method in annotate?
I got a problem with annotate method when I was using the Count method to count multiple columns that come from the database which have a relationship with one of the tables. let me give you a quick example: match_session_instance = MatchSessionInstance.objects.filter(match_session=match_session, status="main") match_instances = MatchSessionInstance.objects.filter(match_session=match_session) action_counts = match_instances.values(player_number=F("player_pk__number"), player_name=F("player_pk__player"))\ .annotate(pass_count=Count("live_match_pass__id", distinct=True), corner_count=Count("live_match_corner__id", distinct=True)) in the meantime I'm not facing any problems I caught my issue and I addressed it but that is the problem now. I don't know How could "disticnt=True" parameter helps me to fix that problem! I googled a bit and found this source that has helped me: Count on multiple fields in Django querysets I know what does distinct as a method in ORM but actually, I get no idea how it works in that format special when I used columns that never have duplicated data. Can anyone help me to understand, please? thanks in advance -
Change reason field (django-simple-history) populated in django admin panel
I use django-simple-history in the project. The documentation https://django-simple-history.readthedocs.io/en/2.7.0/historical_model.html is clear as to how to pass changeReason value while updating the object. I wonder if it is possible to populate history_change_field in django admin panel when making changes? -
Appending all for loop dicts into single list
I just learnt django and I am getting data from api and looping through the json and appending the data into the list. but When I use .map() function in react then the data is appending in list (from for loop) like [ { "results": { "id": 544, "name": "User_1", } }, { "results": { "id": 218, "name": "User_2", } }, { "results": { "id": 8948, "name": "User_3", } }, { "results": { "id": 9, "name": "User_4", } }, ] It is not appending like (Like I want) [ results : [ { "id": 544, "name": "User_1" }, { "id": 218, "name": "User_2" }, { "id": 8948, "name": "User_3" }, { "id": 9, "name": "User_4" } ] ] views.py def extract_view(request): results_list = [] // api url for explanation only get_response = "https://api.punkapi.com/v2/beers" if get_response.status_code == 200: for result in get_response.json(): results_list.append({"results": result}) return Response({"data": results_list}) I know, In for loop it is appending every result within it with every iteration but I also want to assign all the responses within results list. I have tried many times but it is still not working. -
Customizing calendar.HTMLCalendar in a Django Project
I am using HTMLCalendar to add a calendar to my project. The calendar is showing perfectly fine but I want to add some customization to it. As a simple example I want to add a legend after the month and I want to add a condition so that if an event is on a specific date to have a button around the number of the month. I have found some very old answers but I am not sure how to actually implement. Similar answers:python calendar.HTMLCalendar Here is the current view: class home(ListView): model = Workout template_name = 'app/home.html' context_object_name = 'workouts' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) year= datetime.now().year month=datetime.now().month cal=HTMLCalendar().formatmonth(year,month) context['cal']=cal print(cal) return context here is the current outcome: Here is the template I am sure there is an easier way that I did not yet find to add padding: <center>{{ cal|safe }}</center> <style> .month{ text-align: center; } .mon{ padding-left:15px; } .tue{ padding-left:15px; } .wed{ padding-left:15px; } .thu{ padding-left:15px; } .fri{ padding-left:15px; } .sat{ padding-left:15px; } .sun{ padding-left:15px; } </style> </div> This is the required outcome or similar to it: My question: How can I customize the HTMLCalendar so that I can reach the image showing and where should … -
TypeError: connect() argument 4 must be str, not WindowsPath
When I run this python manage.py migrate return Connection(*args, **kwargs) File "C:\Users\WyndhamKeitA\AppData\Roaming\Python\Python310\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) **TypeError: connect() argument 4 must be str, not WindowsPath** my DB under settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': BASE_DIR / 'db.crudpy', 'USERNAME': 'root', 'PASSWORD': '1234', 'PORT': '3306', 'HOST': 'localhost' } } How do I get rid of the error? crudpy is the schema I've created on mysql -
Best way to set up Django model for a balance sheet app
I want to create simple app where a user can keep track of their net worth over time. For example, the user could go in at the end of each month and input their balances for all of their assets and liabilities. The app would keep track of the data over time so it could be displayed as a graph. I'm trying to figure out how to set up my models for this. I think I need to have the balances as a separate class otherwise every time you wanted to add a new date you would have to update the model itself. Here's what I came up with. I'm interested if this is a good way to do this or if there is a cleaner way. class Asset(models.Model): name = models.CharField(max_length=30) description = models.TextField() class Liability(models.Model): name = models.CharField(max_length=30) description = models.TextField() linked_account = models.ForeignKey(Asset,null=True,blank=True) class Meta: verbose_name_plural = "Liabilities" class AssetBalance(models.Model): account = models.ForeignKey(Asset) date = models.DateField() balance = models.FloatField() class LiabilityBalance(models.Model): account = models.ForeignKey(Liability) date = models.DateField() balance = models.FloatField() -
How to use Postman to authenticate Google Login with dj_rest_auth
So I am following the official documentation for Google sign in with DjangoRestFramework using DJ Rest Auth (this link) I intend to authenticate with Postman Oauth2 (by following the guide and generating an Access Token) Postman is generating an access token successfully, but I cannot seem to use this authentication in my API calls. Please who knows which step I am missing - I want to handle everything in Postman. urls.py urlpatterns = [ path('', Home.as_view(), name='home'), path('admin/', admin.site.urls), path('accounts/', include(api_urls, namespace='api')), path('accounts/login/', GoogleLogin.as_view(), name='google_login'), path('accounts/', include('rest_framework.urls')), ] views.py class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter callback_url = 'http://localhost:8080/accounts/google/login/callback/' client_class = OAuth2Client On calling an API endpoint, I get an invalid token error: If I however visit the Google Login view in my RestFramework UI (in my case http://localhost:8080/accounts/login), I get an endpoint to make a POST, and on making a POST request, a key is generated. Only this key (if used as a Bearer token) works in my API calls. How can I authenticate on Google, and make my API calls independent of the DRF UI? Callback URL has been configured on my Google Developer Client. PS: I feel the answer is in step 6 of the documentation, but I am … -
How to prevent methods of being imported in an outside package at pycharm?
I would like to prevent imports of private methods outside a specific interface in a big commercial project to improve architecture. I've tried with init.py but maintenance is hard and I had problems with circular imports over time. I've also tried with _method() underline to make private methods, but then I could not use these methods inside my own interface. What I would like to set up or within my pycharm configs or by making a customized use of import machinery from python is something like these: -- interface_foo ---- method_foo.py # here I create a public and a private method ---- method_bar.py # here I can import both methods with no issues, cause it is inside inferface ---- api.py # here i display the public methods for other interfaces to use them --interface_baz ----method_baz.py # here I can import ONLY public method By trying to import private methods from interface_foo inside interface_baz should raise an error (like ImportError) -
djando rest framework AssertionError
mi pregunta es porque me arroja este error estoy tratando de actualizar y me dice que estoy recibiendo un un AssertionError class none type mi problema siempre se ha dado con la imagen al enviarla me da siempre problemas asi estuve con mi metodo post hasta que en el serializer lo convert a url mi view.py class PokemonsViewSets(APIView): parser_classes = (MultiPartParser, FormParser, JSONParser,FileUploadParser) def get(self, request,pk=0,format= None, *args, **kwargs): if (pk>0): pokemon = list(PokemonsBBDD.objects.filter(id=pk).values()) if len(pokemon)>0: pokemons = pokemon[0] datos ={'message':"Succes","pokemones": pokemons} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) else: queryset = PokemonsBBDD.objects.all() # pokemonId = PokemonsBBDD.objects.get() serializer = ProjectSerializer(queryset, many=True) if len(queryset)>0: datos = {'message':"Succes","pokemones":serializer.data} else: datos = {"message":"list pokemons not found"} return Response(datos,status=status.HTTP_200_OK) def post(self, request, format= None): serialize = ProjectSerializer(data=request.data) if serialize.is_valid(): serialize.save() return Response(serialize.data, status=status.HTTP_201_CREATED) return Response(serialize.errors,status=status.HTTP_400_BAD_REQUEST) def put(self,request,pk,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon, data = request.data) if serialize.is_valid(): return Response(serialize.data) else: print(serialize.error_messages) return Response(serialize.errors) @action(detail=True) def patch(self,request,pk,format= None,*args,**kwargs): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: serialize = updateSerializer(pokemon,data= request.data) if serialize.is_valid(): serialize.save() return Response({'succes':'exitosa'}) else: print(serialize.error_messages) return Response({'error','bad reques'}) def delete(self,request,pk=0,format= None,*args,**kwargsl): pokemon = PokemonsBBDD.objects.filter(id = pk).first() if pokemon: pokemon.delete() return Response({'message':'dato ELiminado'},status=status.HTTP_200_OK) else: return Response({'messageToFailed':'no se encontro … -
Is it possible to upload an app to a vps server with back in django and front in react.js?
I developed a website that uses react.js and django, and my question is if it is possible to upload it to a vps server. -
REST related/nested objects URL standard
if /wallet returns a list a wallets and each wallet has a list of transactions. What is the standard OpenAPI/REST standard? For example, http://localhost:8000/api/wallets/ gives me { "count": 1, "next": null, "previous": null, "results": [ { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } ] } http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/ gives me { "user": 1, "address": "3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd", "balance": "2627199.00000000" } If I wanted to add a transactions list, what is the standard way to form this? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions ? http://localhost:8000/api/wallets/3E8ociqZa9mZUSwGdSmAEMAoAxBK3FNDcd/transactions?offset=100 for pagination -
Set and not let modify foreign key value (user)
I have 2 models that I want to preset the value and ideally have it hidden from the Django admin when creating new record, this way the user don't amend this value. This are the created and modified by that are foreign keys to users. I found this link https://pypi.org/project/django-currentuser/, that i thought it might do the job, however it reverted my django from the latest version to version 3, so I dont want to use it, and also, it doesnt work if i set either created or last modified but not both, if i set it in the 2 models i get 4 errors. I am wondering if there is an easy way to set this default value? from django.db import models from email.policy import default from django.contrib.auth.models import User from django.utils import timezone # from django.contrib import admin # https://pypi.org/project/django-currentuser/ from django_currentuser.middleware import (get_current_user, get_current_authenticated_user) from django_currentuser.db.models import CurrentUserField class Company(models.Model): modified_by = models.ForeignKey(User, related_name='company_modified_by', unique = False, on_delete=models.CASCADE) created_by = CurrentUserField() created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=150, unique = True) class Meta: verbose_name = "Company" verbose_name_plural = "Companies" def __str__(self): return self.name class UserProfile(models.Model): modified_by = models.ForeignKey(User, related_name='user_profile_modified_by', unique = False, on_delete=models.CASCADE)#CurrentUserField(on_update=True) created_by = … -
Deleted the migrations folder accidently so I dropped all my tables in database but still not working
I deleted my migrations folder accidently so to make things work again I dropped all tables in my database as well. But now even tho python manage.py makemigrations is working, python manage.py migrate still says 'No migrations to apply' why? -
Django Rest / React NextJS - pass username in html form back to DB in a post request
How can you pass username in html form back to Django DB, when making a post request? I get the following error when I submit the form null value in column "owner_id" of relation "contracts_contract" How can I adjust it, so that post request is saved and owner (username) is correctly captured in post request in django db nextjs file: const PostRequest = () => { const [name, setName] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); let body = { owner_id: 1, name: name, } axios.post("http://127.0.0.1:8000/contract/contract-create/", body).then(response => { console.log(response) }) }; return ( <form className='form' onSubmit={handleSubmit}> <input type='text' className='form-input' id='name' value={name} onChange={(e) => setName(e.target.value)} /> <button type='submit'> submit </button> </form> ); }; #Models.py class Contract(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) name = models.CharField(max_length=30) #serializers.py class ContractSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Contract fields = '__all__' @api_view(['POST']) def contractCreate(request): serializer = ContractSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print("data is invalid") return Response(serializer.data) -
I coud not run server
I'm learning django,but i stuck in something, i cant run server(manage.py) from django.urls import path from . import views urlpattern = [ path('hello/',views.say_hello) ] in my django project folder is a urls.py but i created another one for somthing else; this is main urls.py : """storefront URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')) ] -
django, X-CSRFToken is set incorrectly in request header
basically, i got this to actually send a csrf token to the frontend and set it there in cookie section in application tab in dev window in the browser: @method_decorator(ensure_csrf_cookie) def get(self, request, format=None): return JsonResponse({'csrftoken':get_token(request)}) in react side: useEffect(()=>{ axios.get('http://127.0.0.1:8000/csrf/').then((res)=>{ console.log(res.data) Cookies.set('csrftoken',res.data.csrftoken) }) },[]) let handleSubmit = (e) => { e.preventDefault(); axios .post("http://127.0.0.1:8000/signup/", signup, { withCredentials: true, headers: { "X-CSRFToken": Cookies.get("csrftoken") }, }) .then((res) => { setDisabled(true) setIsUp(true) setTimeout(()=>{setIsUp(false) redirect('/')},3000) }) .catch((e) => { console.log(e.response.data) let err = e.response.data setError(err); }); }; on my local machine (on the local hosts): i get these values to match: as you can see both Cookie and X-CSRFToken are matching in request header, however, in production: and the weirder part is that in request header the name of the key in local host is Cookie, but in production it is cookie (c and C difference) and of course I get an error when i make a post request in production server: <p>CSRF verification failed. Request aborted.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token from the &#x27;X-Csrftoken&#x27; HTTP header incorrect. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when <a href="https://docs.djangoproject.com/en/4.0/ref/csrf/">Django’s help … -
Django Rest framework doesn't accept JWT Authentication
I'm not in that backend and python business and I'm trying to implement a JSON REST-API with django and the django restframework. For the authentication I would like to use simple jwt for django. I implemented it with this getting started guide: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html I get a valid JWT string but if I want to fetch data with a GET request and the jwt in the Authentication header I always get a 403 with {message: 'Authentication credentials were not provided'}. My code looks like this: settings.py from pathlib import Path import os from datetime import timedelta from rest_framework.permissions import IsAuthenticated, DjangoModelPermissions, AllowAny ... INSTALLED_APPS = [ 'rest_framework_simplejwt', 'rest_framework', ] ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'AUTH_HEADER_TYPES': ('Bearer',), } CORS_ALLOW_ALL_ORIGINS = True PERMISSION_CLASSES = [IsAuthenticated] urls.py from django.contrib import admin from django.urls import include, path from rest_framework.schemas import get_schema_view from rest_framework.documentation import include_docs_urls from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, TokenVerifyView ) urlpatterns = [ path('api-auth/', include('rest_framework.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path('nutzer_api/', include('nutzer.urls')), path('admin/', admin.site.urls), path('docs/', include_docs_urls(title="DatenmanagerAPI")), ] nutzer/settings.py from django.urls import path from . import views urlpatterns = [ path('hello/', views.HelloView.as_view(), name='hello'), ] … -
How to see the raw MongoDB queries Djongo is running?
I am using djongo as my backend database connector engine. The decision to use Django with MongoDB as well as the choice of using Djongo predates me tenure with the team. I am trying to improve the efficiency of a search result for which I want to know the exact "find" query that is being run on MongoDB. But I can't seem to find a way to do it. Is there a way I can see the exact query that djongo is running under the hood? Follow up: I cannot write the exact search query here but it looks something like this queryset = ( ModelName.objects.filter( Q(attr1__icontains=search_term) | Q(foreign_key1__attr__icontains=search_term) ) .distinct() .order_by("-id") ).select_related( 'foreign_key1__attr' ).values( 'attr1', 'foreign_key1__attr' ) I am a bit confused. Does Foreign Key even make sense if my backend is MongoDb? Is this shoddy DB design or does djongo implement some foreign key constraints at the middleware layer? -
Using variables in a class in django
I am trying to make a chart that displays the temperature and timestamp data, however I want to filter it. The current database this data is being taken from looks like this: And I only want the graph to display data from the specific user that is already logged in. Furthermore, I have pages for each room ID showing the data from that room and with that user, and this is where I want the graph to be displayed. So you login and go to a specific room page and the graph shows the temperature and timestamp data from that room (and of course with that username). The current structure displays the chart by uploading the JSON formatted data to a link called API, and the code to get this API data up is displayed here. class ChartData(APIView, models.Model): authentication_classes = [] permission_classes = [] def get(self, request, *args, **kwargs): labels = [] for e in Post.objects.all(): labels.append(e.timestamp) # print(e.room_id) # print(e.username) #print(e.temperature) chartLabel = "my data" chartdata = [] for e in Post.objects.all(): chartdata.append(e.temperature) data ={ "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, } return Response(data) So right now it takes every temperature and timestamp in the database and puts that on the … -
Got this error when i used the command manager server
I am building a dashboard project currently using Django so that I can learn it as well. I am following a tutorial and did as they did it but I am getting this error right now. I am not sure where I went wrong so please anything helps!! Error Message C:\Users\Vignesh\.vscode\Interview Dashboard\dashboard> python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 15, 2022 - 15:01:34 Django version 4.1.2, using settings 'dashboard.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [15/Oct/2022 15:01:55] "GET / HTTP/1.1" 200 10681 [15/Oct/2022 15:01:55] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [15/Oct/2022 15:01:55] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 C:\Users\Vignesh\.vscode\Interview Dashboard\dashboard\dashboard\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Vignesh\anaconda3\lib\site-packages\django\urls\resolvers.py", line 717, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the …