Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django' even if it is installed (vs code)
I have install django in my virtual environment also activated virtual environment but still it is showing these error python from django.urls import path output Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows PS E:\django\project\telusko> & C:/Users/hp/AppData/Local/Programs/Python/Python39/python.exe e:/django/project/telusko/calc/urls.py Traceback (most recent call last): File "e:\django\project\telusko\calc\urls.py", line 1, in <module> from django.urls import path ModuleNotFoundError: No module named 'django' PS E:\django\project\telusko> -
Django count data apperance in database and send to Django-template
I have this system where i would like to be able to see some staticists over the attendancelog data. I would like to search on the class and the subject and the i get the: attendancename / username_fk the number af times this attendance has attened the subject from the specific class The total amount of times this subject and class has been on different dates the username_fk should also only appear one time My django list view look like this: class AttendanceList(LoginRequiredMixin, ListView): model = AttendanceLog template_name = "./attendancecode/showattendance.html" def get_queryset(self): class_val = self.request.GET.get('class') subject_val = self.request.GET.get('subject') sub = Subject.objects.filter(name=subject_val).first() new_context = AttendanceLog.objects.filter(keaclass_id=class_val, subject_id=sub) return new_context def get_context_data(self, **kwargs): context = super(AttendanceList, self).get_context_data(**kwargs) context['class'] = self.request.GET.get('class') context['subject'] = self.request.GET.get('subject') return context and the result of that is this: My data in the AttendanceLog table look like this so for example the username_fk "nadi6548" has attended "subject_id 2/Large" 4 out of 4 so out from nadi6548 the number 4 stands there and then again 4. I do know the last value of how many time the subject has been there is going to be the same value though the whole list and that is okay. end result: -
Django Shell update objects value
I want to increase the prices by 30% in django shell. models.py: price = models.FloatField(null=True) shell: from product.models import Product Product.objects.all().update(price=price*1.3) error: NameError: name 'price' is not defined -
While I'm trying to set up django server using docker "docker-compose up" its giving Error like this
$ docker-compose up django-ambassador-main_redis_1 is up-to-date Creating django-ambassador-main_db_1 ... error ERROR: for django-ambassador-main_db_1 Cannot create container for service db: user declined directory sharing E:\Office\django-ambassador-main.dbdata ERROR: for db Cannot create container for service db: user declined directory sharing E:\Office\django-ambassador-main.dbdata ERROR: Encountered errors while bringing up the project. -
change font awesome icon in jquery
I have a like button that users jQuery. I want to change the icon based on the like status(outlined heart to filled heart). The issue is when I click like it clears removes the icon pre like: post like: How do I stop it from clearing the icon while still updating the like count, as well as changing the icon class jQuery: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, data.likescount, "like") } else { updateText(this_, data.likescount, "unlike") } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> like button: <a class="like-btn" data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i class="fa fa-heart-o like-heart" aria-hidden="true"></i>{{ post.likes.count }} </a> -
Django STATIC_ROOT not loading files while fully configured
ingestion-dashboard/ ├── apps │ ├── adapter │ ├── authentication | |__init__.py │ ├── static │ │ ├── assets │ │ │-- css │ │ │── img │ │ │── scss │ │ │── vendor │ └── templates │ ├── accounts │ ├── home │ ├── dashboard │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └───staticfiles ├── assets │── css │── img │── scss │── vendor settings.py CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ingestion-dashboard STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) The files from apps/static are being copied into STATIC_ROOT successfully, still it is not rendering files from there. In browser , in url i still see ***/static/*** which was in debug mode while I have set DEBUG=FALSE -
'User' object has no attribute 'rank'
So I have this UserProfile model which has ranking system but the problem is its keep getting some attribute error class UserProfile(models.Model): user= models.OneToOneField(User, on_delete=models.CASCADE,null=True) profile_pic = models.ImageField(blank=True, null=True, default='default.png') bio = models.TextField(null=True,blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) username = models.CharField(max_length=255,null=True,blank=False) rating= models.IntegerField(default=200,null=True,blank=False) major = models.ForeignKey(Major,on_delete=models.SET_NULL,null=True,related_name="major") rank = models.ForeignKey(Rank,on_delete=models.SET_NULL,null=True,related_name="rank") def __str__(self): return self.username and here is its serializer class UserProfileSerializer(serializers.ModelSerializer): profile_pic = serializers.SerializerMethodField(read_only=True) rank = serializers.SerializerMethodField(read_only=True) major = serializers.SerializerMethodField(read_only=True) class Meta: model = UserProfile fields = '__all__' def get_profile_pic(self, obj): try: pic = obj.profile_pic.url except: pic = None return pic def get_rank(self,obj): rank = obj.rank serializer = RankSerializer(rank,many=False) return serializer.data def get_major(self,obj): major = obj.major serializer = MajorSerializer(major,many=False) return serializer.data I dont know why but I am getting this User error Can someone help me please -
Django how to turn a python string into a javascript string and render it to the website
I'm working with Django and in my views I'm sending my page a string of HTML: <p><code>202</code> </p><p>hello world/p> <ul> <li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on.</li> </ul> byebye <p>&lt;3</p> However, it gets sent to the page as: var html_smallest_steps = &lt;p&gt;&lt;code&gt;202&lt;/code&gt; &lt;/p&gt;&lt;p&gt;hello world/p&gt; &lt;ul&gt; &lt;li&gt;Goodbye&lt;strong&gt;&lt;em&gt;next&lt;/em&gt;&lt;/strong&gt; or &lt;strong&gt;&lt;em&gt;happy&lt;/em&gt;&lt;/strong&gt; to go on.&lt;/li&gt; &lt; and I get a console error on my page: Uncaught SyntaxError: Unexpected token '&' My views.py is: def displayDict(request): html_ss = """ <p><code>202</code> </p><p>hello world/p> <ul> <li>Goodbye<strong><em>next</em></strong> or <strong><em>happy</em></strong> to go on. </li> </ul> byebye <p>&lt;3</p> """ return render(request, 'chatStream.html', {"html_sss": html_ss}) And chatStream.html is: <p id="chatLine">get this working!!</p> <script> var html_smallest_steps = {{html_smallest_steps}} } setTimeout(myTimeout2, 2000) function myTimeout2() { document.getElementById("chatLine").innerHTML = "html_ss " + html_ss; } </script> -
Display table ordered by row and columns
I am struggling to display an HTML table with data issued from a database. I just retrieve the data using a SELECT and Join multiples tables. Datas are retrieved like : | StorageLocation| Quantity| RiskPhrase| | --- | --- | --- | | Storage1| 10| H225| | Storage2| 4| H225| | Storage1| 3| H226| | Storage3| 3| H226| | Storage4| 3| H226| | Storage4| 3| H300| I want to be displayed like this : | StorageLocation| H225| H225| H226| H300| | --- | --- | --- | --- | --- | | Storage1| 10| 0| 3|0| | Storage2| 0| 0| 4|0| | Storage3| 0| 0| 3|0| | Storage4| 0| 0| 0|4| I really don't know how to deal with this. Is Dataframe the best solution ? Your help will be more than appreciated. Thanks -
Using self.requests.session in forms.ModelForm
I read Django - Access request.session in form but am still almightly confused. I want the default value in one of my form fields to be from self.requests.session (I also tried requests.session). class BookARoomForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(BookARoomForm, self).__init__(*args, **kwargs) self.fields['arrival_date'].initial = self.requests.session['arrival_date'] class Meta: model = RoomBooking fields = ('User', 'title', 'room_type', 'arrival_date', 'departure_date', 'cost') In get_context_data I have tried context['book_a_room_form'] = BookARoomForm(), context['book_a_room_form'] = BookARoomForm(request) and context['book_a_room_form'] = BookARoomForm(self.request). Each time I got a different error. class HotelDetailSlugView(ObjectViewedMixin, DetailView): template_name = "hotel/detail.html" def get_context_data(self, *args, **kwargs): context = super(HotelDetailSlugView, self).get_context_data(*args, **kwargs) context['book_a_room_form'] = BookARoomForm() # Your part form -
How to assign the same value to multiple variables in a class in django models
In the below class orders, I want to assign the same value of weight to the amount class Orders(models.Model): consignment_id = models.IntegerField(primary_key='consignment_id',auto_created=True) order_date = models.DateTimeField(default=timezone.now) weight = models.FloatField() from_place = models.CharField(max_length=20,null=True) destination = models.CharField(max_length=20) amount = models.FloatField(weight) name = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=20, default='Pending') -
Django naturaltime doesn't accept input
Within an API response I receive the following datetime as string: 2021-11-23T15:04:31Z In my Django template I'd like to render this using the naturaltime template tag. However, the template tag just doesn't apply any logic to it and it gets rendered as is. Is there any way to tell Django to format this using the naturaltime? -
Issue with template in django TemplateView
I have 4 types of tickets to display on my dashboard Open,accept,complete and closed i have written the below template view to display all the contexts within single view but if i click on those options on dashboard it displays all status of tickets in all four as in if i click on open tickets it shows all the other status along with open tickets and same goes for other type of tickets as well Dashboard image This is the open ticket url showing all the status instead of only open tickets views.py class DeveloperTicketView(TemplateView): template_name = 'app/ticket_view.html' def get_context_data(self, **kwargs): context = super(DeveloperTicketView,self).get_context_data(**kwargs) context['open_tickets'] = Ticket.objects.filter(status = 'Opened') context['accepted_tickets'] = Ticket.objects.filter(status = 'Accepted',accepted_by = self.request.user) context['completed_tickets'] = Ticket.objects.filter(status = 'Completed',accepted_by = self.request.user) context['closed_tickets'] = Ticket.objects.filter(status = 'Closed',accepted_by = self.request.user) return context Ticket_view.html {% extends 'app/base.html' %} {% block body %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Status</th> <th>Created</th> <th>Title</th> <th>Description</th> </tr> </thead> <tbody> {% for ticket in open_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status }}</td> <td>{{ ticket.created_by }}</td> <td>{{ ticket.ticket_title }}</td> <td>{{ ticket.ticket_description }}</td> <td><a href="{% url 'accept_tickets' pk=ticket.id %}">Accept</a></td> </tr> {% endfor %} {% for ticket in accepted_tickets %} <tr> <td><a href="">{{ ticket.id }}</a></td> <td>{{ ticket.status … -
Make grafana use JWT token in the local storage
I have a React + DRF web app that has JWT authentication, in which I use djangorestframework-simplejwt. I store access and refresh tokens in the localStorage. Is it possible to use these tokens to authenticate in Grafana? If yes, how can I do that? When I navigate to /grafana (with nginx help), I would like to see that my user in my app to be logged in to the Grafana, by creating the user for Grafana if necessary. -
What are the possible needed algorithms for making a small ecommerce website (with react.js, python-django, mongodb)? [closed]
Recently I've started to work on my project which is somewhat related to the ecommerce website "RED BUBBLE". But I'm confused in what are the algorithms that are needed in fulfilling the basic functionalities of an ecommerce website like Searching a product, recommendations of trending products, and handling the data of every user ? And Which data structure I need to use for an efficient coding and working of the website ? -
Django - Inline formset - How to set current user
-Objective- I need to set, in a Inline Formset, the current user as automatic content of a field of the form. (Currently not working) Version Python 3.9.2 - Django 3.2 Context: I've created a List, where I have some objects(Headers). From the list I can create new headers and access to the detail-page(Detailview)for each of these by using a foreign-key(called by PK-primarykey). In this page I can see more informations about 1 specific header. Each header can have multiple lines of informations that need to be linked to it. The lines are created or updated with (max 4 different) specific Inline Formsets. -Issue and Error- I created the forms that are correctly rendered, but I need to set for each line, a field that automatically gets "current user" as its content. I can't save and receive instead"User cannot be null". I'm unable to find a solutions and tried many things but stuck with this error. Would kindly appreciate any help on how to solve this problem. Thanks in advance, Below some code: URLS.PY from django.urls import path, re_path from fttlapp import views app_name= 'fttlapps' urlpatterns = [ path('fttlapphome2/', views.Fttlapphome2View.as_view(), name='fttlapphome2'), path('fttlogheader/', views.HeadfttlogListView.as_view(), name='headfttlogs'), path('fttlogheader/add/', views.HeadfttlogCreateView.as_view(), name='headfttlogcreate'), path('fttlogheader/<int:pk>/', views.HeadfttlogDetailView.as_view(), name='headfttlogdetail'), path('fttlogheader/<int:pk>/flights/edit/', … -
Nginx download permissions error - Open() failed (13: Permission denied)
I have a webpage with Nginx + Uwsgi + Django where I have an external path called /download to manage the downloads in Django (the user credentials) and the internal path /download-nginx to actually download the files on the directory /var/wwww/download. For the sake of trials, I have tried to do this with my username as well as the default nginx user. With both of them I get a permission denied error on Nginx: open() "/var/www/download/example.txt" failed (13: Permission denied) I have read several other solutions on SO telling that the problem is that the provided user in nginx.conf does not have enough permissions. The thing is that they do have enough permissions: $ sudo -u nginx stat /var File: ‘/var’ Size: 4096 Blocks: 8 IO Block: 4096 directory Device: 802h/2050d Inode: 50331745 Links: 21 Access: (0777/drwxrwxrwx) Uid: ( 996/ nginx) Gid: ( 0/ root) Context: system_u:object_r:var_t:s0 Access: 2021-11-23 11:24:53.329927606 +0000 Modify: 2021-11-23 09:43:29.250244353 +0000 Change: 2021-11-23 11:21:37.151148760 +0000 Also, just in case I have done chmod 777 recursively on directory /var/wwww/download My nginx.conf file is as follows: user nginx; worker_processes auto; error_log /var/log/nginx/error.log; pid /run/nginx.pid; # Load dynamic modules. See /usr/share/doc/nginx/README.dynamic. include /usr/share/nginx/modules/*.conf; events { worker_connections 1024; } http … -
Django testing abstract models - table relation does not exist
I'm trying to test an abstract model. I've created a models.py in my tests directory where I'm inheriting from the abstract base classes. In my tests I'm importing from tests/models.py but for some reason I'm getting an error that the table does not exist despite this working perfectly fine in other projects. When running python manage.py test I get the following error: psycopg2.errors.UndefinedTable: relation "address_address" does not exist LINE 1: ...postal_code", "address_address"."country_id" FROM "address_a... Here's my app's file structure: myapp/ tests/ __init__.py models.py test_models.py __init__.py admin.py apps.py models.py Here is my tests/models.py: from ..models import ( AbstractAddress, AbstractBillingAddress, AbstractShippingAddress, AbstractBillingShippingAddresses, ) class Address(AbstractAddress): pass class BillingAddress(AbstractBillingAddress): pass class ShippingAddress(AbstractShippingAddress): pass class BillingShippingAddresses(AbstractBillingShippingAddresses): pass Here's an example of one of the abstract models: class AbstractAddress(AddressMixin, models.Model): line_1 = models.CharField(_('line 1'), max_length=255, blank=True) line_2 = models.CharField(_('line 2'), max_length=255, blank=True) city = models.CharField(_('city'), max_length=255, blank=True) province = models.CharField(_('state'), max_length=255, blank=True) state = models.CharField(_('zip/postal code'), max_length=64, blank=True) country = models.ForeignKey( 'address.Country', blank=True, null=True, on_delete=models.PROTECT, related_name='%(class)s_country', verbose_name=_('country') ) class Meta: abstract = True I've tried adding app_label = 'address' to the my test models but I'm still getting the same error. The only thing I can think of is that the test models are inheriting … -
How to add new button in django admin panel?
I want to add button next to "Delete" button. How can I do that? -
I got the from date and to date from the user. I want to return the Sold Product's price and its count in the basis of Daily sold order. how?
models.Order.objects.filter(purchasedate__range=[from_date, to_date]) today_total = 0 quant = 0 for values in daterangeorder: today_total += values.price quant += values.quantity return response.Response({ "from_date": from_date, "to_date": to_date, "Amount Sold": str(today_total), "Count": str(quant) }) OutPut Comming like this:- { "from_date": "2021-11-19", "to_date": "2021-11-23", "Amount Sold": "27000", "Count": "9" } I want like this (day by day sold products count):- { date: “'2021-10-20”, count: 20, total_price_sold: 5000.00 }, { date: “'2021-10-21”, count: 4, total_price_sold: 300.00 } -
Data added to request from Django ModelViewSet is not being reflected in serializer
I am trying to load data to a model using update_or_create method. For that I added two few fields to the request.data on the fly. But I am not getting those fields in create method in serializer views.py class TestMemberView(ModelViewSet): queryset = TestMembers.objects.order_by('-date_time_viewed') serializer_class = TestMemberSerializer def create(self, request, *args, **kwargs): request.data["user_id"] = 123 request.data['user_name'] = test_user return super().create(request, *args, **kwargs) serializer.py class TestMemberSerializer(serializers.ModelSerializer): view_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S') class Meta: model = TestMembers fields = ("member_first_name", "member_last_name", "view_time", "user_name","user_id",) def create(self, validated_date): user_id = validated_date.pop('user_id') member, _ = TestMembers.objects.update_or_create(user_id=user_id, defaults={ "view_time": timezone.now()}, **validated_date) return member request body: { "member_first_name": "test_name", "member_last_name": "test_name" } error: { "errors": [ { "error_level": "ERROR", "system_error": null, "reason": null, "user_error": { "user_name": [ "This field is required." ], "view_time": [ "This field is required." ] } } ] } Please help me to resolve this. How can I get those fields in serializer which I added in the view. -
JavaScript: Leaflet bindpopup use checkbox. Currently clears each time the popup is closed
I use below code to generate a leafletmap with some additional fields, from a Django backend. In the browser however, the checkbox generated, "unchecks", each time you close the popup. How do I get to retain it's value? <script> var mymap = L.map('competition_map').setView([{{ lat }}, {{ lon }}], 5); var plant = L.marker([{{ plant.lat }}, {{ plant.lon }}]).addTo(mymap); var customer = L.marker([{{ customer.lat }}, {{ customer.lon }}]).addTo(mymap); plant.bindPopup("<b>{{ plant }}</b>").openPopup(); customer.bindPopup("<b>{{ customer }}</b>"); //Through iteration add all Competitors: {% for c in competitor %} var competitor_{{c.id}} = L.marker([{{ c.lat }}, {{ c.lon }}]).addTo(mymap); competitor_{{c.id}}.bindPopup("<input type=\"checkbox\" id=\"{{ c.id }}\" name=\"{{ c.id }}\" onClick=\"competitorAdd('{{ c.id }}','{{ c.location_name}}','{{ c.city }}', '{{ c.country }}')\"><strong>{{ c }}</strong>"); {% endfor %} var competitors = L.layerGroup([ {% for c in competitor %} competitor_{{c.id}}, {% endfor %}]); //https://leafletjs.com/examples/layers-control/example.html to add layers for Grey and Streets. var baseLayers = { }; var overlays = { "Competitors": competitors }; L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', { maxZoom: 18, attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, ' + 'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1 }).addTo(mymap); L.control.layers(baseLayers,overlays).addTo(mymap); </script> -
how to customize User model in django
I want to add a field to User models Django example(in models.py: from django.contrib.auth.models import User #I want to add code here that customizes the user model fields how can I do this? -
Pyinstaller and Django any collect_submodules failed to import
This problem is new to me. When using extra libraries, they cannot be incorporated into the pyinstaller build. As an example I tried using --hidden-import, --collect-submodules and added a hook-djoser.urls.py file to try to solve one of the other problems. In this file I did this. hook-djoser.urls.py in Lib\site-packages\PyInstaller\hooks from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('djoser.urls') # pyinstaller --noconfirm --onedir --console --name "royalback" "C:/Users/Shudf/royalback/manage.py" And I can't make it work. Would anyone be available to help? Thanks raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. collect_submodules: failed to import 'djoser.urls'! -
How to return related value from database after click function by ajax in django?
html <div> {{ productform.vendorid|as_crispy_field }}<a id="vendor_id_search" class="btn btn-info">search</a></br> <div style="display:none;" id="show_vendorname">hjkh</div><br> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $("#vendor_id_search").click(function (event) { event.preventDefault(); var vendor_id = $("#id_vendorid").val(); $.ajax({ url: '/ajax/find_vendorname/', method: 'GET', data: { 'vendor_id': vendor_id }, dataType: 'json', success: function (data) { $("#show_vendorname").show(data) } }); }); views.py #vendor_name_find_ajax def find_vendorname(request): if request.is_ajax(): vendorid = request.GET.get('vendor_id', None) username = CustomUser.objects.filter(first_name=vendorid) return username I want to display the related name for that vendorid after the user typed the vendorid field and once clicked the button, the related name should be displayed on that particular div. Here, I have made a mistake and don't know to get that value. please, someone, do needful.