Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'templates'
Need Help!!! I am learning tag. I got the following response after running. "django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'templates.my_tags': No module named 'templates'" Django version: 3.2.7 my_tags.py from django import template register = template.Library() @register.simple_tag def mul(v1, v2, v3): index.html {% load my_tags %} setting.py TEMPLATES = [{"libraries":{'my_tags':'templates.my_tags'}] -
What is the best way to query and send position of the celery task in queue over an api or websocket
Currently on my project I am trying to get a task running which updates contionusly the number of tasks in queue before that respective task, so the approach I am using is to call a celery task(processingTask) which does the actual processing work inside another celery task(queueUpdatingTask)(which sends a message over websocket about the queue status) So i am trying something like below, /tasks.py @shared_task def sample(): time.sleep(10) return "Dummy task" @shared_task def processingTask(): # some processing @shared_task def queueUpdatingTask(): print("***** Started task trigger and monitor *****") channel_layer = get_channel_layer() loop = asyncio.new_event_loop() new_task = processingTask.apply_async(args=[], kwargs={}, queue='default') # Send update message if the task has entered execution while True: # Break if the task is completed if new_task.ready() and new_task.state == "SUCCESS": send_channel_message_update( channel_layer, loop, new_task.id, f"{new_task.result}", receiver_type="update_status", job_title="Queue Status" ) print("***** Finished task trigger and monitor *****") break # Break if the task is started elif new_task.state == "STARTED": send_channel_message_update( channel_layer, loop, new_task.id, f"{new_task.state}", receiver_type="update_status", job_title="Queue Status" ) print("***** Started task trigger and monitor *****") break # Send update message if the task is still in the queue elif new_task.state == "PENDING": s, i = get_running_tasks(new_task.id) send_channel_message_update( channel_layer, loop, new_task.id, f"{s}", receiver_type="update_status", job_title="Queue Status" ) print("***** In progress … -
Why my queryset filter for creating electricity bill is not working?
I was working on a project in which a user creates some members(model) and their electricity bills (this is also a model) but when I'm applying queryset to ElectricityForm it's showing errors. KeyError at /bills/electricity/create/ my members/models.py from django.db import models import uuid from django.contrib.auth import get_user_model from phonenumber_field.modelfields import PhoneNumberField class Member(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,related_name="members") name = models.CharField(max_length=250) email_address = models.EmailField(max_length=252, null=False, blank=False, unique=True) phone_no = PhoneNumberField() def __str__(self): return str(self.id) my electricity_bills/models.py from django.db import models from members.models import Member import uuid import datetime class ElectricityBill(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) member = models.ForeignKey(Member, on_delete=models.CASCADE, related_name="electricity_bills" ) id_member = models.CharField(max_length=40) k_no = models.CharField(max_length=40) last_date = models.DateField() state = models.CharField(max_length=50, null=False, blank=False , choices=state_choices, default="Rajasthan") month = models.CharField(choices=months, default="January", max_length=10) year = models.CharField(choices=years, default="2022", max_length=4) amount = models.PositiveIntegerField() email_send = models.BooleanField(default=True) is_email_sent = models.BooleanField(default=False) def __str__(self): return str(self.member) my electricity_bill/views.py class ElectricityBillCreateView(LoginRequiredMixin, CreateView): model = ElectricityBill template_name = 'bills/electricity/bill_create.html' form_class = ElectricityForm success_url = reverse_lazy('ebills_list') my electricity_bills/forms.py from django import forms from .models import ElectricityBill from members.models import Member from django.contrib.auth import get_user_model class ElectricityForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super(ElectricityForm, self).__init__(*args, **kwargs) self.fields['member'].queryset = Member.objects.filter( created_by=self.request.user) member = forms.ModelChoiceField(queryset=Member.objects.all()) k_no … -
How to set password show/hide eye button in Django form?
How to set password show/hide eye button in Django form Well I know same question is their but solution not working for me Is their a second way or fixed way of this This also can be version issue bcz this question was asked 2-3 years ago... -
Architecture for setting up Constants and using them in Django
Currently my project has over more than 500 constants, currently we are storing them inside individual modules files but it is becoming difficult to manage them . We have have thought of using DB and cache to store these constants but not sure about the performance. Can someone please suggest a better architecture or if someone has already used DB to store constants please let me know the better way. There are several types of constants in the code also keep in mind while answering that I am looking solution for Django. -
Django show error : "name 'dif_months_without_date' is not defined" though defined
I make the first django app and get error: NameError: name 'get_date' is not defined My structure: app person views.py models.py my_core common.py In common.py, i defined def get_date(): return "something" When i call get_date() def in views.py, it is ok, but call it in models.py it show error. In both views.py and models.py imported : from my_core.common import * What am i missing? -
How to allow a Channels consumer to access session generated by HTTP requests?
I have a project that used to run under WSGI, and I recently configured it to ASGI. It included code from back then, such as the following function that processes a login request: def authenticate(req): ... try: query = models.User.objects.get(...) req.session['user'] = query.id #Login successful ... except: #No record, reject request ... What I want to do now is to create a WebsocketConsumer and access the session from within. I have enabled SessionMiddlewareStack. The problem is that the consumer does not even see the session because the session's ID is not attached to the WebSocket request as a header. Is there a way to allow it to access the data? class SpaceConsumer(WebsocketConsumer): def connect(self): #Session object is empty, while HTTP requests see it as populated with the user's ID if 'user' in self.scope['session']: self.accept() #Only allow authenticated user Information online is scarce, and most are written for older versions of Channels. I am using Channels v3. -
Docker container runs on VM but not on Cloud Run
I have a Django container and normally I am running it on a VM. But i tried to cloud run to run that image. However when I tried that I got the below error. Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in <module> import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Which is weird. And then I tried to create a virtual env in Dockerfile. Maybe cloud run was overwriting PATH or something. It worked. I need to create it without virtual env. What could be the reason? -
Not able to show custom errors after form sbmission in django
I am trying to show errors that I receive besides the fields but the errors are not showing in the template. models.py -
javascript/ajax not working when add two product to cart, how to solve this?
On my cart view page, I can increase and decrease product quantity by clicking + and - button when the cart has one product. When I add more than one product to my cart increase and decrease button does not work at any product. Working Fine when only one product is in my cart. When adding more than one product to the cart increase(+) and decrease(-) button doesn't work. HTML {% for cart_product in cart %} <tr class="product-row"> <td> <figure class="product-image-container"> <a href="{{ cart_product.product.get_absolute_url }}" class="product-image"> <img src="{{ cart_product.product.product_img_1.url }}" alt="product" class="img-fluid"> </a> </figure> </td> <td> <div class="product-single-qty"> <div class="input-group bootstrap-touchspin bootstrap-touchspin-injected"> <div class="minus-cart value-button" value="Decrease Value" pid="{{ cart_product.product.id }}">-</div> <span class="number">{{ cart_product.quantity }}</span> <div class="plus-cart value-button" value="Increase Value" pid="{{ cart_product.product.id }}">+</div> </div> </div> </td> <td class="text-right"> <span class="subtotal-price each_pro_subtotal">{{ cart_product.total_cost }}</span> </td> </tr> {% endfor %} javascript $(".plus-cart").click(function(){ var id = $(this).attr("pid").toString(); var eml = this.parentNode.children[1]; $.ajax({ type : "GET", url : "/shop/pluscart", data : { prod_id : id }, success : function(data){ eml.innerText = data.quantity; each_subtotal = document.getElementsByClassName("each_pro_subtotal"); each_subtotal[0].innerText = data.each_pro_subtotal; document.getElementById("subtotal").innerText = data.subtotal; }, }) }); -
The text entered in the title field is entered in the same slug, but I do not know why;
I am creating a post on the superuser page, and suddenly slugfield is automatically entered. The text entered in the title field is entered in the same slug, but I do not know why; Why is the slug automatically entered as the text entered in the title? class POST(models.Model): slug = models.SlugField( unique = True, allow_unicode = True, ) title = models.CharField(max_length = 30, default = '') -
How to access Python dictionary in Javascript Script in Django
I am working in Django, where I am sending a Python Dictionary into an HTML file. In that HTML File, I want to access the Python dictionary and append the keys and values of dictionary into the Javascript arrays. I am able to access Python dictionary in HTML, but can't do the same in Javascript. This is how I am able to access the values of Dictionary in HTML, {% for key, image in predictedLabel.items %} <tr> <th scope="row">{{ key }}</th> <td>{{ image }}</td> </tr> {%endfor%} The Javascript script that I have is of Pie Chart, which is as given below, <script> var xArray = []; var yArray = []; var xArray = ["Italy", "France", "Spain", "USA", "Argentina"]; var yArray = [55, 49, 44, 24, 15]; var layout = { title: "Distribution of Labels" }; var data = [{ labels: xArray, values: yArray, hole: .5, type: "pie" }]; Plotly.newPlot("myPlot", data, layout); </script> I want to put the Python Dictionary Key into the xArray and the Values of Dictionary into the yArray. For that, I need to access the Python Dictionary in the Javascript script, but I do not know how to access the Python values in the Javascript script. Can … -
Django filer change unsorted uploads
I'm using django-filer now and by default, every image will be stored in "Unsorted Uploads". How can I change that folder? The question is similar to this Using django-filer, can I chose the folder that images go into, from 'Unsorted Uploads'. But I want to know is there any better way to do this? -
how to list the data dynamicly in html in django?
I tried to create a html page to list the all datas from my database with django, but it was not working. this is my code: item.html {% for p in product %} <div> <table> <tr><th>{{p.item}}</th><th>{{p.rate}}</th></tr> <tr><td></td><td></td></tr> </table> <button > addcard</button><br> <button> remove card </button> {% endfor %} views.py from .models import dishes def item(request): products = dishes.objects.all() return render(request, 'item.html', {'product' : products}) I got this code from online, it did not work and at the same time it did not show any error. please tell me how to solve this problem. -
Disable/Remove default permissions from django's third party library (django-celery-beat)?
When we setup django-celery-beat to my django project. It migrates the models from the library along with the default permissions. But, in my case I don't want those default permissions to be setup on my system permissions. I know it's possible to delete permissions for self created model by setting meta's default_permission = []. But how can I do that for a third party library in django? -
How to handle stale model instance with long db update in Django/Postgres?
Context: Medium-sized web app Django 3.2, DRF 3.13, python 3.8 Hosted in Google cloud and managed by goole kubernetes engine Google CloudSQL for PostgreSQL (v. 9) class Park(models.Model): <some fields> class City(models.Model): foo = models.IntegerField() # bar and baz are populated from a microservice at City creation bar = models.IntegerField() # baz was recently added and is null for some cities baz = models.IntegerField(null=True) @property def update_from_microservice(self): """Updates the row by making a call to a microservice hosted in the same cluster as the Django App""" new_data = call_to_microservice(self.foo) self.bar = new_data["bar"] self.baz = new_data["baz"] self.save() @property def get_data(self) """Helper method that returns some structured data from the instance""" return {"bar": self.bar, "baz": self.baz} class ParkListView(generics.ListAPIView): serializer = ParkSerializer http_method_names = ["get"] def get_queryset(self): return Park.objects.filter() def get_serializer_context(self): context = super().get_serializer_context() # Get the city from the uri `/parks/<int:city_foo>/` foo = kwargs.get("city_foo") this_city = City.objects.get(foo=foo)) city_data = this_city.get_data() # Check that the expected data is present. if None in city_data.values(): # If data is missing, try updating the fields # Tests indicate this step works as expected, # since the update_from_microservice() refers to self, this instance should # get the updated values once the microservice returns this_city.update_from_microservice() # Get the … -
how to print text on top of each bar graph in apexchart
I am using apexchart to output a chart. The code is as below, and I don't want the chart to include the ongo value, but only the value of ongo to be printed on top of each bar. ex) ongo: {{ ongo | safe }} I tried adding enabled: true, enabledOnSeries in the datalabels setting, but the result I want is not output. The values for I, S, P, E are reflected in the chart, output as datalabel, and only the ongo value is displayed as text on top of each bar. [dashboard.html] <div id="dashboard"> <script> var options3 = { series: [ { name: 'I', data: {{ I | safe }} }, { name: 'S', data: {{ S | safe }} }, { name: 'P', data: {{ P | safe }} }, { name: 'E', data: {{ E | safe }} }, { name: 'ongo', data: {{ ongo | safe }} }, ], chart: { type: 'bar', height: 550, stacked: true, }, plotOptions: { bar: { dataLabels: { position: 'center', }, } }, dataLabels: { style: { fontSize: '10px', colors: ["#304758"] } }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'I-S-P-E chart', offsetY: 0, align: 'center', }, … -
How to convert images produced by html canvas to .ai(adobe illustrator) file format in either frontend or backend process?
I'm developing a webapp to edit photos and trying to download them as adobe illustrator (.ai) file format. The webapp has two parts frontend and backend. React for frontend, and Django restframework for backend. The photos are edited within a html canvas element, and the canvas is controlled by JavaScript. Th code below converts the canvas element to a dataURL, so I can see the compiled image after hitting the url. The url shows it is png format. var canvas = document.getElementById("myCanvas"); var dataURL = canvas.toDataURL(); And the url looks like this. data:image/png;base64,iVBORw0KGgoAAA... Is there any way to convert the canvas image to .ai(adobe illustrator) file format using ether JavaScript, React for frontend, or python for backend process? -
adding addresses to a model via django's admin.py and with django-address
I am having a problem with my django app. I am trying to add a model of restaurants that has an address field, and I am using django-address to help me with this. So, my Restaurant model looks like this: class Restaurant(models.Model): name = models.CharField(max_length=64) address = AddressField(on_delete = models.CASCADE, default = None) However, when I go to add a specific restaurant using admin.py, it doesn't let me. As shown in the screenshot below, I type in one character and then it does not allow me to edit it: Screenshot of admin.py I have been able to add specific addresses themselves, but I can't figure out how to connect these addresses to a specific restaurant. Does anyone have any ideas about how to fix this? Or, does anyone have any nice work-arounds where I can add some specific restaurants without using admin.py? Thanks!! -
Django's Cast function returns DataError: invalid input syntax for type integer: "John"
I have the following models that allow me to dynamically create and track data for a contact: class DataField(models.Model): name = models.CharField() class Contact(models.Model): created_on = models.DateTimeField() class ContactField(moddels.Model): contact = models.ForeignKey(Contact) data_field= models.ForeignKey(DataField) value = models.CharField() For example I have two DataField models with the name field set as "First Name" and "Loan Amount". To create data for a contact, I create two ContactFields, the first I link to the "First Name" data field and give it the value "John", the second I link to the "Loan Amount" data field and give it the value 5000. e.g: ContactField(1) contact = Contact(1) data_field = DataField(First Name) value = "John" ContactField(2) contact = Contact(1) data_field = DataField(Loan Amount) value = "5000" Now I want to query the database to return Contacts that have a loan amount greater than X. The first problem is that the value field needs to be an integerfield to perform the greater than query, but it is a CharField. I cannot change it to an integer field because it needs to store both integers and strings (e.g it also stores the value "John" for first name). As a result I am trying to use the annotate and … -
Hiding header isn't working - Django ecommerce
I have a header I want to hide when scrolling down. The header is located in my templates folder in Django, file name is base.html - see code below: <body> <header class="container-fluid fixed-top"> <div id="topnav" class="row pt-lg-2 d-none d-lg-flex"> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <a href="{% url 'home' %}" class="logo-homepage"> <img src="/media/logo.jpg" width="150" height="150" alt="logo"> </a> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <form method="GET" action="{% url 'products' %}"> <div class="input-group w-100"> <input type="text" class="form-control" placeholder="Search for your vinyl" name="search" aria-label="search_vinyl" aria-describedby="button-addon2"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="submit" id="button-addon2"> <span class="search-vinyl"><i class="fas fa-search"></i></span> </button> </div> </div> </form> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <ul class="list-inline list-unstyled text-center text-lg-right my-0"> <li class="list-inline-item dropdown px-5 nav-item-bg"> <a class="text-black nav-link" href="#" id="user-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <div class="text-center"> <div><i class="fas fa-user fa-lg"></i></div> <p class="my-0">My Account</p> </div> </a> <div class="dropdown-menu border-0" aria-labelledby="user-options"> {% if request.user.is_authenticated %} {% if request.user.is_superuser %} <a href="{% url 'add_product' %}" class="dropdown-item">Product Management</a> {% endif %} <a href="{% url 'profile' %}" class="dropdown-item">My Profile</a> <a href="{% url 'account_logout' %}" class="dropdown-item">Log Out</a> {% else %} <a href="{% url 'account_signup' %}" class="dropdown-item">Sign Up</a> <a href="{% url 'account_login' %}" class="dropdown-item">Log In</a> {% endif %} </div> </li> <li class="list-inline-item px-5 nav-item-bg"> <a class="{% if … -
Having Docker-py commands in Celery tasks
i'm currently creating a Django web application and i'm having some issues. For one of my views, i'm trying to return a response asap while having a process run in the background. The process stated contains Docker-py commands(For certain reasons I can't show the code). I'm trying to use Celery but for some reason, it doesn't work(It just hangs and gets a timeout for running too long). I'm sure the code for the process is correct since i've already tested it out. Is Docker-py compatible with Celery?(As in can Celery help make the docker-py commands run in the background?) -
DataFrame with DateTimeIndex from Django model
My goal is to create a pandas dataframe with a datetimeindex from a django model. I am using the django-pandas package for this purpose, specifically, the 'to_timeseries()' method. First, I used the .values() method on my qs. This still returns a qs, but it contains dictionaries. I then used to_timeseries() to create my dataframe. Everything here worked as expected: the pivot, the values, etc. But my index is just a list of strings. I don't know why. I have been able to find a great many manipulations in the pandas documentation, including how to turn a column or series into datetime objects. However, my index is not a Series, it is an Index, and none of these methods work. How do I make this happen? Thank you. df = mclv.to_timeseries(index='day', pivot_columns='medicine', values='takentoday', storage='wide') df = df['day'].astype(Timestamp) raise TypeError(f"dtype '{dtype}' not understood") TypeError: dtype '<class 'pandas._libs.tslibs.timestamps.Timestamp'>' not understood AttributeError: 'DataFrame' object has no attribute 'DateTimeIndex' df = pd.DatetimeIndex(df, inplace=True) TypeError: __new__() got an unexpected keyword argument 'inplace' TypeError: Cannot cast DatetimeIndex to dtype etc... -
Getting type error when passing model in select tag in Django
I have a model called Department it has data College and HS, when I try to save my form I always get a TypeError. I've tried to validate the form and found out that it was an unbound form so I tried changing the Field type of department from ChoiceField to CharField and in my templates I tried calling {{form.department}} and it gives me the correct data yet it still gives TypeError. views.py class editProfile(UpdateView): model = Profile form_class = UpdateUserForm template_name = 'accounts/profile.html' success_url = reverse_lazy('homepage') #TypeError or ValueError def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['initial']=Profile.objects.get(user=self.request.user) context['department']=Department.objects.all() context['program']=Program.objects.all() context['year']=Year.objects.all() return context def form_valid(self, form): user = form.save(commit=False) user.username = form.cleaned_data.get('username') user.profile.department = form.cleaned_data.get('department') user.profile.program = form.cleaned_data.get('program') user.profile.year = form.cleaned_data.get('year') user.profile.save() user.save() forms.py class UpdateUserForm(forms.ModelForm): def __init__(self, *args, **kwargs) -> None: super(UpdateUserForm, self).__init__(*args, **kwargs) self.fields['username'].label = 'Username' self.fields['department'].label = 'Department' self.fields['program'].label = 'Program' self.fields['year'].label = 'Year' username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Type your username' })) department = forms.CharField(widget=Select(attrs={ 'class': 'form-control' })) program = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) year = forms.CharField(widget=Select(attrs={ 'class': 'form-control', }, )) class Meta: model = User fields = ['department', 'program', 'year', 'username'] models.py class Department(models.Model): department=[ ('HS','Highschool Department'), ('College','College Department') ] name = models.CharField(_('Department'),max_length=50,choices=department) def … -
Django form creator
I am building a Django project which let users(teachers) create Forms for their students. they can add inputs and also options (for dropdown inputs). I solve this challenge by using dictionaries (I store their inputs and options in dictionaries and if they add options elements will be added to their keys as lists) I don't like the way that I am storing data (as dictionaries) in my database. I want to know if there are any features in Django that can let me produce module fields for my database. in short- I want to handle the database (create new fields) in my view.