Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Add multiple table rows by one submission in Django
Here is my Html input which have same name input for all rows with different values <input type="text" class="form-control" name="name" value="Name1"> <input type="text" class="form-control" name="name" value="Name2"> <input type="text" class="form-control" name="name" value="Name3"> <input type="text" class="form-control" name="name" value="Name4"> <input type="text" class="form-control" name="name" value="Name5"> <input type="text" class="form-control" name="name" value="Name6"> Here's my view after the form is submitted records must be added to multiple rows NOT IN ONE ROW if request.method == 'POST': names = request.POST.getlist('name') for name in names: Test( name= name ).save() return HttpResponse('success') I tried this method but it only saves one row of the last value. -
How to get the page number of a particular object in Django Rest Framework pagination?
How can we send an id of a particular object in the url and get the page number of where that object exists? I'm using Django Rest Framework as my project backend and I have enabled pagination in order to get a list of items. Now I need to send the item id in the url and get the corresponding page where that item belongs. Can I do this with Django Rest Framework... My front-end is React JS. Any answer would be great! Thank you! -
Is there possibility to connect django webapp to hadoop
i am trying to connect my django webapplication to hadoop(as data source), but i am unable to do so. Can someone tell me is there possibility to connect webapp to hadoop as data source. -
How can I get API error response in desired format?
This is how i am getting the error messages. By default, i am getting 'serializer.errors' as dictionary of list and i want them in list of dictionary format -
How can I solve this python problem?[django]
Why cannot I migrate. It says assertion error. Here is the pic # Create your models here. class Product(models.Model): product_id= models.AutoField() product_name = models.CharField(max_length=50) category = models.CharField(max_length=50, default="" ) subcategory = models.CharField(max_length=50, default="" ) price = models.IntegerField(default=0) desc = models.CharField(max_length=300) pub_date = models.DateField() image = models.ImageField(upload_to='shop/images', default="") def __str__(self): return self.product_name -
Django static files working from template but not from CSS file
I am just getting back into Django, and I have a new project set up here in the development server. I set up static files and I have been able to load the files from the templates however when the files are accessed via CSS there is a 404 error. Here is how the image is accessed in CSS: background-image: linear-gradient(rgba(206, 27, 40, 0.25), rgba(206, 27, 40, 0.25)), url(../images/cta01.jpg); The 404 error in the browser is looking in the staic/images/ folder but his location is not being served. I know this static file thing is always tricky butt I don't remember it being such as issue before. What am I doing wrong? Here is the settings file and main URL file. Also I tried to use whitenoise and it seems to be working but same behavior: static files load in templates but not from CSS. settings.py """ Django settings for tmx_intranet project. Generated by 'django-admin startproject' using Django 3.1.6. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # … -
Modifications in Django admin after pen test
We have performed a pen test on django admin module using a paid online tool as suggested by our client. It has raised a red flag for a chance of XSS attack in the user groups query. I have tried manually injecting java script in the query. It was accepting script but not executing. But I need to prove technically it was safe from XSS attack. Can someone help me with this? -
I have formset ignoring all attributes
forms.py class DocumentForm(ModelForm): prefix = 'document' document = FileField( required=True, widget=FileInput(attrs={ 'accept': '.xls,.xlsx,.csv', 'aria-label': 'File Upload', 'class': 'form-control' }) ) header = IntegerField( required=True, label='헤더 행# (첫 행=0)', widget=NumberInput(attrs={ 'class': 'form-control', 'min': 0, 'value': 0 }) ) class Meta: model = Document fields = ['document', 'header'] exclude = ['description', 'uploaded_at'] DocumentFormSet = modelformset_factory( Document, form=DocumentForm, fields='__all__', max_num=2, extra=1 ) views.py def compare(request): file_paths, header_dict, step = [], [], 'start' header_dict, step = [], 'start' doc_forms = DocumentFormSet(request.POST or None, request.FILES or None) ...(removed other code)... return render(request, 'compare/index.html', {'formset': doc_forms, 'user': request.user}) Note that I render as {{ formset }} and also the formset should only render 4 inputs. I don't understand why the form is like so. Why is that happening even with extra and max_num set? Anyone can answer this I really need help. -
Django: Get an attribute (imagefield) from a Foreign Key's reverse relation object
I've been struggling with the right syntax for this. I want to create a gallery of photo albums, and have a selectable cover photo for each album. But to do this, I need to grab the reverse relation object and then choose the imagefield attribute from it. I know how to use the relation manager to filter the cover photo object (based on a cover boolean attribute) but not how to then get the imagefield attribute from that object (to then reference in the template for img src). Here is my models.py from django.db import models def make_pic_path (instance, filename): albname = instance.album.name path = 'AlbPics/{0}/{1}'.format(albname, filename) return path class Album(models.Model): name = models.CharField(max_length = 100) dates = models.CharField(max_length = 100) description = models.CharField(max_length = 1000) def cover_photo (self): return self.albumpicture_set.filter(cover = True) def __str__(self): return self.name class AlbumPicture(models.Model): picture = models.ImageField(upload_to = make_pic_path, blank = True) picture_desc = models.CharField(max_length=200) album = models.ForeignKey(Album, on_delete=models.CASCADE) cover = models.BooleanField() def __str__(self): return self.picture_desc and the views.py: from django.shortcuts import render from .models import Album, AlbumPicture from django.contrib.auth.decorators import login_required @login_required def alb_gallery(request): gallery = Album.objects.all() context = {'gallery': gallery, } return render(request, 'gallery/gallery.html', context) And the template gallery.html (or my best guess) …