Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reading external token in Django
I am calling Django API from .NET API. I am passing a validated Bearer token (JWT) in the header. I am not able to read the token from the header in Django API. I am using only functional API views. The users, models and db is managed in .NET only. Why is Django stripping my token in the header? How to enable secured token reading in Django Functional API? -
Print takes more than 2 seconds in python
I have a variable which is obj=model.filter(id=id) and i have print function which display obj value. i measure it by pref_counter() it takes more than 2 seconds. my code are like obj=model.filter(id=id) c = time.perf_counter() print(obj) d = time.perf_counter() print("seconds", d - c) #shows 2 seconds Fun part is if I print it twice, it will take 4 seconds. -
ERROR: Service 'app' depends on service 'db' which is undefined
I'm getting this error while trying to run: docker-compose run app python manage.py migrate in the console. This is the error: ERROR: Service 'app' depends on service 'db' which is undefined. My docker-compose.yml is this one: version: '3' volumes: database: { } services: app: build: context: . dockerfile: ./docker/app/dev/Dockerfile environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=xxxx depends_on: - db volumes: - ./app:/app:z env_file: - ./.envs/.dev/.app - ./.envs/.dev/.postgres ports: - "8000:8000" command: "python manage.py runserver 0.0.0.0:8000" Everything is linked accordingly so I don't know where this error can come from. -
Apply filter with Prefetch in prefetch_related()
I am creating a multi language project. I am using 2 models to save data. Fields that are same for all languages (like images) in model 1 and texts in model 2 with ForeignKey to model 1. class FidelityClubs(models.Model): image = models.ImageField(upload_to='admin/fidelity_clubs/') class FidelityClubTexts(models.Model): title = models.CharField(max_length=255) content = RichTextField() language = models.ForeignKey('van_admin.Languages', on_delete=models.CASCADE, default='1') club = models.ForeignKey('van_admin.FidelityClubs', on_delete=models.CASCADE, related_name='texts') There is a default language. All contents will be available in default language (french). If user select another language, I have search content in that language and if content is not available in that language, I have to show content in default language. I using this query. fidelities = FidelityClubs.objects.all().prefetch_related(Prefetch('texts', FidelityClubTexts.objects.filter(language__code=lang_code))) I am sending this data by APIs. This is showing data like this. { "image": "http://127.0.0.1:8000/media/admin/fidelity_clubs/logo-1.png", "texts": [ { "id": 9, "title": "CosmetiCar en", "content": "<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, CosmetiCar Informaton Lorem Ipsum is simply dummy text of the printing and typesetting industry. en</p>", "language": 2, "club": 13 } ] }, { "image": "http://127.0.0.1:8000/media/admin/fidelity_clubs/logo-2.png", "texts": [] }, This is not working. If data is available in required language … -
How to access Post IPAddress HitCount in Template
I am building BlogApp and I made a HitCount Feature for count the views of BlogPost through IPAddress. BUT i am stuck on a Problem. AND i don't know how to access in Template. models.py PostViews model is for Count the Views through IPAdress of the User. class PostViews(models.Model): IPAddress = models.GenericIPAddressField(default='45.243.82.169') post = models.ForeignKey('BlogPost',on_delete=models.CASCADE,null=True) class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') date_added = models.DateTimeField(auto_now_add=True,null=True) @property def views_count(self): return PostViews.objects.filter(post=self).count() views.py def detail_view(request,pk): data = get_object_or_404(Post,pk=pk) views = PostViews.objects.get_or_create(pk=pk) x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') context = {'views':views`,'data':data} return render(request, 'show_more.html', context ) show_more.html {{ views }} The Problem I don't know how to access HitCount Views in template. Views are adding in Admin Properly through IPAddress BUT i have no idea how to acces them. What have i tried I have also pass x_forwarded_for in context AND i did try to access but nothing worked. Any help would be Appreciated. Thank You in Advance. -
django inspectdb command run migrations
I have connected with an existing database with Django which is on an SQL server. It's working fine. after that, I am getting all tables using python manage.py inspectdb command. It gives me all tables but now I want to access data for all tables. Is a need to run migrations for that tables? if yes, then I don't want to put default user migrations in an existing database how can I solve this? -
Why does my django webserver stop after trying to send password reset mail?
Here are the logs, I tried to read them but I got no idea how to fix this error. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\lib\site-packages\django\template\base.py", line 850, in resolve_lookup (bit, current)) # missing attribute django.template.base.VariableDoesNotExist: Failed lookup for key [is_nav_sidebar_enabled] in [{'True': True, 'False': False, 'None': None}, {'csrf_token': <SimpleLazyObject: <function csrf..get_val at 0x00000285F295D488>>, 'request': <WSGIRequest: GET '/reset_password/'>, 'user': <SimpleLazyObject: <function AuthenticationMiddleware.process_request.. at 0x00000285F2B482F0>>, 'perms': <django.contrib.auth.context_processors.PermWrapper object at 0x00000285F2A4EE10>, 'messages': <django.contrib.messages.storage.fallback.FallbackStorage object at 0x00000285F2B200F0>, 'DEFAULT_MESSAGE_LEVELS': {'DEBUG': 10, 'INFO': 20, 'SUCCESS': 25, 'WARNING': 30, 'ERROR': 40}}, {}, {'form': , 'view': <django.contrib.auth.views.PasswordResetView object at 0x00000285F2B201D0>, 'title': 'Password reset', 'LANGUAGE_CODE': 'en-us', 'LANGUAGE_BIDI': False}] "GET /reset_password/ HTTP/1.1" 200 1903 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en\formats.py first seen with mtime 1603131647.8355522 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\conf\locale\en_init.py first seen with mtime 1603131647.8345575 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\staticfiles\storage.py first seen with mtime 1603131653.6030731 (0.031) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE (UPPER("auth_user"."email"::text) = UPPER('######@gmail.com') AND "auth_user"."is_active"); args=('######@gmail.com',) File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends\smtp.py first seen with mtime 1603131654.0612879 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends\base.py first seen with mtime 1603131654.0582974 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\smtplib.py first seen with mtime 1530052318.0 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\contrib\sites\requests.py first seen with mtime 1603131652.143951 File C:\Users\VARDHAN\AppData\Local\Programs\Python\Python37\Lib\site-packages\django\core\mail\backends_init.py first seen with mtime 1603131654.0572996 "POST /reset_password/ HTTP/1.1" 302 0 -
How to query a user's display information in the AccountDisplayInformation from the AccountModel
I am trying to query the instagram field in the AccountDisplayInfo model through the account model. via this line in the view: displayinfo = get_object_or_404(AccountDisplayInfo, account=account) I am however not able to query that information as I got a 404 error..any idea why this is happening? Did I do something wrong in views.py or forms.py Also, would be great if you can advise on this:: If I have 2 tables. Table 1 and Table 2. Table 2 has a foreign key to table 1 but table 1 dont have a foreign key to table 2. How can I query table 2's data from table 1? Thanks models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class AccountDisplayInfo(models.Model): account = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) instagram = models.CharField(max_length=50, unique=True, blank=True, null=True) #instagram views.py def display_information_view(request, *args, **kwargs): user_id = kwargs.get("user_id") account = Account.objects.get(pk=user_id) context = {} displayinfo = get_object_or_404(AccountDisplayInfo, account=request.user.id) if request.POST: form = DisplayInformationForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return redirect("account:view", user_id=account.pk) else: form = DisplayInformationForm(request.POST, instance=request.user, initial={ "instagram": displayinfo.instagram, } ) context['form'] = form else: form = DisplayInformationForm( initial={ "instagram": displayinfo.instagram, } ) context['form'] = form return render(request, "account/displayinfo.html", context) forms.py class DisplayInformationForm(forms.ModelForm): class Meta: model = AccountDisplayInfo fields … -
How can I get list of all items with query received?
I am making a Django project in which I have User List which contains various Items. Each Item has its attribute like name, quantity and date. This is my model of items: class Item(models.Model): STATUS = ( ('BOUGHT', 'BOUGHT'), ('NOT AVAILABLE', 'NOT AVAILABLE'), ('PENDING', 'PENDING'), ) userlist = models.ForeignKey(userList, on_delete=models.SET_NULL, blank=True, null=True) item_name = models.CharField(max_length=200, null=True) item_quantity = models.CharField(max_length=200, null=True) item_status = models.CharField(max_length=200, null=True, choices=STATUS) date = models.DateField(null=True) def __str__(self): return self.item_name This is my views.py: def listView(request): if request.user.is_authenticated: fd = None user_id = request.user.id userlist, created = userList.objects.get_or_create(user_id=user_id) items = userlist.item_set.all() if request.body: data = json.loads(request.body) fd=data['date'] else: items = None context = {'items': items} return render(request, 'list_manager/index.html', context) Here, fd is the query 'date' received from body. By default, items contains all the items present in the list. Now I just want the list of objects which have item.date==fd, how can I achieve that? -
Get values_list of a m2m related django model
I have a django model like the following: class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) flows = models.ManyToManyField(AllotmentFlow) how can I get the values of alloted_quantity from a queryset ? items = Allotment.objects.filter(some_filtering).values_list('alloted_quantity') but gives me a FieldError: django.core.exceptions.FieldError: Cannot resolve keyword 'alloted_quantity' into field. More precisely I want to get the sum of all the alloted_quantity retrieved from that query, how do I do that ? -
a category which a user created is showing up for another user in Django REST framework
I have made a rest api which let's users create items to save under their account and also categories. Categories are a separate model and item is a separate model. there is a field in the item model which is category = models.ForeignKey(Category, on_delete=models.CASCADE) Here is the PROBLEM...I have 2 separate users, when user A creates a category it shows up in user B's create item view! why is this happening? and how can I stop it? I only want categories to show up in item creation view which a user himself created thanks in advance! -
Where is a model's __past_status = None field stored?
I have something that works but I don't quite understand why; Some time ago I started using one great solution from SO, and now I'm using it in more places. The solution is; you have a model eg class Membership(models.Model): user_cancelled = models.BooleanField(default=False) __past_status = None def save(self, force_insert=False, force_update=False, *args, **kwargs): try: if self.pk: if self.user_cancelled != self.__past_status and self.user_cancelled: .... except: pass it works perfect and allows me to achieve what I wansn't quite able to using signals. What I don't understand is where the "__past_status" field's value is stored as it does not appear in migrations and therefore there is no db record of it. But it works. I would appreciate any explanation or hint. -
How to pass in the context of a Class Based View to the Template in Django?
I have a script in Django where all users can view the profile of another user. I am able to get an answer regarding my question about CBV ListView with the get_queryset method. I am now able to access the profile of another user, but I am not able to pass it into my home template. View.py class OtherUserProfileView(LoginRequiredMixin, ListView): model = Post template_name = "core/otheruser.html" def get_queryset(self): queryset = super().get_queryset() queryset = queryset.filter(user_id=self.kwargs['user_id']) return queryset Urls.py path('profile/<int:user_id>/', OtherUserProfileView.as_view(), name='profile'), In the View.py, I used the ListView and the get_queryset method. I passed in the user_id so I can access all the objects of another user. Home.html {% extends "core/base.html" %} {% block content%} {% for item in object_list%} <div class="container"> <div class="card text-light bg-secondary mb-3 mx-auto" style="max-width: 60rem;"> <div class="card-header text-light">{{item.title}}</div> <div class="card-body"> <p class="card-text text-light">{{item.content}}</p> <h6 class="card-title text-light"><a class="text-light" href="{% url 'core:detail' item.pk %}">Full Page</a></h6> <p class="card-text text-light"><a class="text-light " href="{% url 'core:profile' user_id=view.kwargs.user_id %}">{{item.user}}</a><small class="text-light"> {{item.created}} </small></p> </div> </div> </div> {% endfor%} {% endblock %} However, when I tried to passed in the script <a class="text-light " href="{% url 'core:profile' user_id=view.kwargs.user_id %}">{{item.user}}</a>, I got an error message NoReverseMatch at / Reverse for 'profile' with keyword arguments '{'user_id': … -
Django: Appending results on go
I have a program that fetches a very hugs data from database into data frames. loading the complete data is having "out of memory" issue. I want to return html(or json) response in loop i.e. for first loop some data is fetched and then return to html and then another loop is executed and appended to the existing html response and so on. Is this possible? or is there an alternate way to accomplish this for a very high data. -
The 'Thumbnail' attribute has no file associated with it. Django {% if %} {% else%} {% endif %}
The 'Thumbnail' attribute has no file associated with it. I have tried Django {% if %} {% else %} {% endif %} in my HTML list and it works on the page, but when I do the same for a detailview HTML it doesn't work and returns "The 'Thumbnail' attribute has no file associated with it." ** Models.py ** class Article(models.Model): Title = models.CharField(max_length=150) Thumbnail = models.ImageField(blank=True, null=True) Author = models.ForeignKey(Author, on_delete=models.CASCADE) Content = QuillField() Date = models.DateField(auto_now_add=True) slug = AutoSlugField(populate_from='Title') ** Views.py** class ArticlesDetailView(DetailView): model = Article template_name = 'articles_app/articles_detail.html' def get_context_data(self, **kwargs): latest = Article.objects.order_by('-id')[0:3] context = super().get_context_data(**kwargs) context['latest'] = latest return context ** HTML - List (articles_list.html) ** It works perfectly fine here!!! <img src=" {% if articles.Thumbnail %} {{ articles.Thumbnail.url }} {% else %} {% static 'img/add-ons/article_thumbnail_default.jpg' %} {% endif %} " alt="..." class="card-img-top"> ** HTML - Detail (articles_detail.html) ** It doesn't work here. {% for obj in latest %} <img src="{% if obj.Thumbnail %} {{ obj.Thumbnail.url }} {% else %} {% static 'img/add-ons/article_thumbnail_default.jpg' %} {% endif %} " alt="..." class="card-img-top"> {% endfor %} What am I doing wrong? Please help! -
Query a Django ORM from Pandas Dataframe
I have a Pandas Dataframe with values like the following: delivery_month flow kit 0 2021-02-06T19:15:15.023000Z LMXMNH Manesar_TACO Bangalore_Gear Lever TACO KIT1187 1 2021-01-06T19:13:10.785000Z LMXMNH Manesar_TACO Bangalore_Gear Lever TACO KIT1187 I want to query a Model which contains all these values to retrieve sum of alloted_quantity for particular month from that model models.py class AllotmentFlow(models.Model): flow = models.ForeignKey(Flow, on_delete=models.CASCADE) kit = models.ForeignKey(Kit, on_delete=models.CASCADE) asked_quantity = models.IntegerField(default=0) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) flows = models.ManyToManyField(AllotmentFlow) Here's what I know but I am still unsure how to pass values in the query: for i in df[df['delivery_month','flow', 'kit']]: items = Allotment.objects.filter(dispatch_date__year_gte = ??, dispatch_date__month_gte = ??, flows__flow__flow_name = ??, flows__kit__kit_name = ??) and how to get sum of alloted_quantity for months in the delivery_month column. I applied the following to change the datetime to month and year but I am unsure if that would help: df['delivery_month'] = df['delivery_month'].apply( lambda x: datetime.strptime(x[:10], "%Y-%m-%d").strftime("%m-%Y")) -
Get windows authentication details from Django UI and IIS
I have enabled windows authentication to my django UI and is working fine , used IIS to enable windows authentication . So Is there any way in django or IIS to get the login credentials . like i want to write a log which contains the date and time of login and username credential of user who are login in . and logout time . Is that possible using Django or IIS . -
how to set user foreign key as current user django ajax
my ajax django are working perfectly and my comments is also reaching, but when i put foreignkey user it says undefined ajax $(document).ready(function(){ setInterval(function() { $.ajax({ type:'GET', url:"{% url 'comments' %}", success:function(response){ $('.display').empty(); for(var key in response.comments){ console.log(response.comments[key].user) var temp = "<p>"+response.comments[key].message+"</p>" $(".display").append(temp); } }, error:function(response){ console.log("no data found") alert("no data found") } }); }, 500); }); </script> views.py def index(request): return render(request,'display/index.html') def getusers(request): queryset =models.comments.objects.all()[:20] return JsonResponse({"comments":list(queryset.values())}) in my admin when i select users and save , in template it is saying undefined, pls help mee -
Reverse for 'user-post' with no arguments not found. 1 pattern(s) tried: ['product/userpost/(?P<email>[^/]+)/$']
i want my user who post to see there own products each and everything is working fine if i give the url by my own but when i wrote {% url 'products:user-post'%} it give me the error and i am stuck in this error my views.py file is: class UserPostListView(ListView): model = Product template_name ="user-posts.html" def get_queryset(self): user = get_object_or_404(User, email=self.kwargs['email']) return Product.objects.filter(author=user).order_by('-time_stamp') in my project url the urls.py of the app is: path('product/' , include(("products.urls" , "ecommerce"), namespace="products")), and in my app my class url is: path('userpost/<email>/', UserPostListView.as_view(), name='user-post'), and in my template here i got the error: <div class="nav-item"> <a href="{% url 'products:user-post'%}" role="button" aria-haspopup="true" aria-expanded="false">User Post <span class="caret"></span></a> </div> and the error is: Reverse for 'user-post' with no arguments not found. 1 pattern(s) tried: ['product/userpost/(?P[^/]+)/$'] -
django imagefield access from remote server
I have a server with 4 million images connected to "Follower" model with imagefield. They all are stored in /media folder under the django main folder on "main" server. I have another server "slave" connected to the same DB at "main" having tasks running, one of the task involve the access to the media folder, but it is on the "main" server, What can I do to access the images from remote ? -
Is there is any API for Cyber Map?
there is a way to enable cyber map in Django application? like this cyber map -
Passing a Django Object to Javascript
As you have read the title, yes there are a lot of SO questions like this one but before you downvote, here me out. I have tried them but to no success. Another note is I don't have a lot of experience with JavaScript so please bear with me. Below is the simplified version of my code view.py: context['colorObj'] = Colors.objects.all() Now on template, I can just loop through {{colorObj}} to get the individual values inside the object. However on JavaScript, this is not the case. If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong). Here is I first thought I should do: JavaScript: var colorObj = {{colorObj}}; the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String. Other suggestion is this: from json import dumps ... colorObj = Colors.objects.all() context['colorObj'] = dumps(colorObj) Then on JS: var colorObj= {{colorObj| safe}}; But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line. Suggestions are very … -
Error on Django URL : URLconf defined in website.urls, Django tried these URL patterns
I am running a django project on a ubuntu digital ocean droplet with nginx/gunicorn on my own domain. I am using a virtual environment with Django version 3.1.6 and Python 3.8.5 I am trying to follow Corey Shafers Django tutorial to create a blog app and while I can reach the generic django success page on example.com I ran into the following from example.com/blog : Page not found (404) Request Method: GET Request URL: example.com/blog Using the URLconf defined in website.urls, Django tried these URL patterns, in this order: admin/ The current path, blog, didn't match any of these. My current ~/projectdir/website/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/',admin.site.urls), path('', include('blog.urls')), ] My ~/projectdir/blog/urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), ] My ~/projectdir/blog/views.py: from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('<h1>Blog Home</h1>') As far as I can tell everything looks ok syntax-wise but I can't figure out why the URLconf is not seeing the blog path. I have tried reloading nginx and that didn't help. -
Problem with implementing drf_yasg (swagger) into django (AssertionError ModelSerializer)
For couple of days im trying to implement drf_yasg into Django==3.1.3. Im always follow the instructions written here -> https://drf-yasg.readthedocs.io/ (installation, urls). Howerever, once im visiting swagger url definied in urls on my local machine error always occured ->: screenshot and the console prints: AssertionError: ("Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = '__all__' to the UserTokenSerializer serializer.",) Why is this happening? How to fix it? -
Sqlalchemy reflection get_table_names() missing a table name
I've two tables in my database, factsales_tbl and factsales. They're both listed if I query the db like this, SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES where table_schema = my_schema But for some reason, factsales is not being returned by sqlalchemy.reflection.Inspector.from_engine(conn).get_table_names(schema=myschema) engine.table_names() also only returns factsales_tbl and not factsales but engine.has_table('factsales') returns True What am I doing wrong?