Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django chart.js multi axis line chart
Hi Guys I have inspired from this Fiddle example to try to create a similar multi axis line chart in my django project. I have in my views : class dashboard(TemplateView): template_name = 'users/dashboard.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['qs'] = DummyData.objects.all() data = DummyData.objects.all() years=[] for i in range(data.count()) : if data[i].year not in years : years.append(data[i].year) context['years'] = years return context in in my dashboard.html : {% extends 'users/base.html' %} {% load static %} {% block content %} <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!-- jQuery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $(document).ready(function (){ var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for year in years %} '{{year}}', {% endfor %}], datasets: [{% for item in qs %} { label: '{{item.site}}', yAxisID: '{{item.site}}', data: [100, 96, 84, 76, 69] , {% endfor %} ] }, options: { scales: { yAxes: [{ id: 'A', type: 'linear', position: 'left', }, { id: 'B', type: 'linear', position: 'right', ticks: { max: 1, min: 0 } }] } } … -
django - template does not exists at /
I'm starting a new Django project, but straight away I can't set up the correct templates directory path. this are my settings.py: import os TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ ... ], }, }, ] I have a very simple view in the project folder: def dashboard(request): context = { } template_name = 'dashboard.html' return render dahsboard.html is located in BASE_DIR/templates/dashboard.html. Pretty straight forward, but still I get the Error: "TemplateDoesNotExist at / dashboard.html" -
my python path for new env does not run the code , while mu main python path run it as normal
while I am testing some mediapipe functions and modules on my windows PC I noted that when I run any thing on my main python path its fine but , if I run it on the new env path some functions does not work this error -->(FileNotFoundError: The path does not exist.) appears ''' when I comment this on my env path I works fine but if I uncomment those two lines FileNotfoundError #appears import mediapipe as mp mp_holistic = mp.solutions.holistic holistic = mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) print("any_thing") print(mp_holistic) print(holistic) ''' enter image description here enter image description here -
Set value of a form class field
# forms.py class AvatarForm(forms.ModelForm): class Meta: model = Profile fields = ('avatar', 'user', 'banner', 'bio') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(AvatarForm, self).__init__(*args, **kwargs) self.fields['avatar'].widget.attrs = { 'class': 'd-none', 'accept': 'image/*', } self.fields['user'].widget.attrs = { 'class': 'd-none', } self.fields['banner'].widget.attrs = { 'class': 'd-none', } self.fields['bio'].widget.attrs = { 'class': 'd-none', } # set the value here, something like this self.fields['user'] = self.user self.fields['bio'] = str(Profile.objects.filter(user=self.user).first().bio) self.fields['banner'] = str(Profile.objects.filter(user=self.user).first().banner) # views.py def main(request, username): form = AvatarForm(request.POST or None, request.FILES or None) if request.is_ajax(): if form.is_valid(): form.save() ... // js file var formData = new FormData(); formData.append('croppedImage', blob); $('.cropper-container').remove(); $.ajax($`/{${'#auth_username'}}/`, { method: "POST", data: formData, processData: false, contentType: false, success: function () { $('.avatar-container-wrapper').load(location.href + ' .avatar-container'); }, error: function () { } }); The only thing I want to upload is the avatar field, rest other fields must have a default value that I want to set in the forms.py file itself. How to achieve this.. The other fields are part of the Model but the only field I want to change is avatar. Any help is appreciated. Thank you! -
Patching Django FileSystemStorage location does not take effect [putest]
I have a simple model as such: #models.py from django.core.files.storage import FileSystemStorage LOCATION = 'old_location' class FileArchive(models.Model): file = models.FileField(storage=FileSystemStorage(location=LOCATION)) I have a view through which I populate the mentioned model and call .save(). My aim is to have a functional test to try to upload a file and assert that the file exists on the provided (patched) LOCATION. The problem is no matter how I patch the LOCATION, which is located in my models.py, the test still uses the hard-coded location in my model. Here are the ways I tried to patch LOCATION. Some of the ways I tried to patch the LOCATION attribute: from . import models def test_uploaded_file_is_stored(monkeypatch): monkeypatch.setattr(models, 'LOCATION', 'new_location') ... Another way: def test_uploaded_file_is_stored(mocker): mocker.patch.object(modesl, 'LOCATION', 'new_location') ... Another way: from unittest.mock import patch def test_uploaded_file_is_stored(mocker): with patch('filestorage.models', 'LOCATION', 'new_location') ... I'm guessing I am patching the wrong place. Any ideas? -
is there a method to run javascript only after loading page url?
html : <li><a href="{% url 'list_article' %}"> article</a></li> i want to execute javascriptcode only after the href i.e after going on list_article url : var rules = $('#builder').queryBuilder('getRules'); liste_rules=[{"id":"source","field":"source","type":"string","input":"text","operator":"contains","value":"google"}] liste_rules={"condition":"AND","rules": liste_rules}; $('#builder').queryBuilder('setRules', liste_rules); $('#FormQueryBuilder').submit(); -
Django Channels 3.0 - different middleware for different websocket routes
I am currently experiencing a conundrum. I am attempting to implement a inter-device communication/signalling system. I am attempting to tackle this via WebSockets (Django Channels and Consumers), as real-time event handling is important for my use case. I would like to be able to apply authentication middleware to only certain WebSocket protocol URLs (specific Consumers), allowing others (like registration and login via JWT) to occur without asking for authentication. The documentation covers a root-level ProtocolTypeRouter and encourages developers to wrap an ASGI application (like a URLRouter) in an authentication middleware stack. However, the end result is that all of the "websocket" protocol requests are forwarded to this middleware. What I would like to do, is somehow split the handling of websocket protocol requests based on their URL. Ideally, to give ProtocolTypeRouter two URLRouters, one wrapped with the middleware and one not. Like so: device_handling_service/urls.py from channels.routing import URLRouter from django.urls import re_path from .consumers import IoTRegisterConsumer,\ IoTLoginConsumer,\ IoTPollConsumer websocket_needs_auth = URLRouter([ re_path(r"^$", IoTPollConsumer.as_asgi()) ]) websocket_no_auth = URLRouter([ re_path(r"^register/$", IoTRegisterConsumer.as_asgi()), re_path(r"^login/$", IoTLoginConsumer.as_asgi()), ]) asgi.py import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import device_handling_service.urls from .middleware import JWTAuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IoTHub.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter([ JWTAuthMiddlewareStack(device_handling_service.urls.websocket_needs_auth), … -
IntegrityError: null value in column "is_approved" violates not-null constraint
Firstly , i was told to add a field to my model to help the admin approve, disapprove or pend products before they can be seen on the website. So, i added class Product(models.Model): ...there are some fields here... is_approved = models.BooleanField(default=False) to my product model, did the routine migrations, edited the serializer, views,urls,tested it and pushed to microsoft azure. 2nd, i had another instruction to change the same field to approval_status STATUS = [ ('0', 'Pending Approval'), ('1', 'Approved'), ('2', 'Rejected') ] class Product(models.Model): ...there are some filed here... approval_status = models.CharField( choices=STATUS, default='0', max_length=2 ) after deploying, i have this error IntegrityError at /marketplace/create_product/ null value in column "is_approved" violates not-null constraint DETAIL: Failing row contains (620, , , 2.00, FTF, 0, PR, , , , 113, 2021-05-03 11:38:28.57937+00, null, 0). i am suspecting the server database couldn't replace the is_approved field with approval_status, but rather included it, and hence trying to return that value. i have am expecting 13 fields but 14 are been returned Kindly help me with ideas to solve the error. my model class Product(models.Model): owner = models.ForeignKey( 'Accounts.BusinessInfo', on_delete=models.CASCADE ) name = models.CharField( max_length=100, blank=True, ) description = models.TextField( blank=True ) price = … -
HOW TO OPTIMIZE DJANGO QUERIES
Could you, please help me optimizing this view? It's takes more than 30 minutes to accomplish the job. I think the problem is in the Django queries.cSomeone recommended me to put all queries in a list or dictionary I tried it but I don't see how to deduce the Django queries def upload_edge(request, pk): template = "networks/edge.html" roadnetwork = RoadNetWork.objects.get(id=pk) road_type = RoadType.objects.get(pk=2) if request.method == 'POST': form = EdgeForm(request.POST, request.FILES) if form.is_valid(): datafile = request.FILES['my_file'] objects = json.load(datafile) L=[] for object in objects['features']: objet_type = object['geometry']['type'] if objet_type == 'LineString': properties = object['properties'] geometry = object['geometry'] point1 = geometry['coordinates'][0] point2 = geometry['coordinates'][1] location = GEOSGeometry( LineString(geometry['coordinates'])) target = properties.get('target') source = properties.get('source') name = properties.get('name') try: target_node_instance = Node.objects.get(node_id=target) source_node_instance = Node.objects.get(node_id=source) target = Node.objects.get(network_id=target_node_instance.network_id, node_id=target_node_instance.node_id) source = Node.objects.get(network_id=source_node_instance.network_id, node_id=source_node_instance.node_id) node = Edge( geometry=location, road_type=road_type, target=target, source=source, network=roadnetwork) L.append(node) except: pass Edge.objects.bulk_create(L) return redirect('home') else: form = EdgeForm() return render(request, template, {'form': form}) -
Where to store PDF files from user input in a React/Django project
I am creating an job application website with React and Django. I want the users to upload 3 PDF files as part of the form in the application. I want to store these files in the backend(Django) and send the files to another React page. My problem is storing these PDF files. The application model uses FileField. Can these files be stored in Django or is it better to use somehting like AWS? -
How can I use ImportExportModelAdmin and SearchAutoCompleteAdmin to the same model admin?
I'm new to Django and I really search everywhere to solve this situation but I didn't find How exactly I can do it. this is my model.py: class User(models.Model): username = models.CharField(max_length=35,verbose_name='Username') site = models.CharField(max_length=35,verbose_name='Site') This is my model admin.py: from django.contrib import admin from search_admin_autocomplete.admin import SearchAutoCompleteAdmin class AdminUser(SearchAutoCompleteAdmin,ImportExportModelAdmin): list_display = ('username','site') search_fields = ['username'] list_filter = (site, ) admin.site.register(User,AdminUser) I can not use SearchAutoCompleteAdmin and ImportExportModelAdmin together. I really need to have a solution that can make my model has a searchAutocomplete and an ImportExport in the django admin page. -
Get Django ready for Angular with Corsheaders
I am trying to integrate my Django backend app to Angular. But for some reason, this error always starts showing up. This is what my settings.py file is looking like: INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleWare', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:4200', ] And this is the Error: ImportError: Module "corsheaders.middleware" does not define a "CorsMiddleWare" attribute/class Who knows what I am doing wrong here? Or if there's a fix for that? -
Django_Rest_Framework efficient way to perform calculations across models
I am using django_rest_framework for a web application. I have created the necessary API end points for all the necessary CRUD operations for the respective tables. Now I want to perform calculations on the data of multiple tables and send the calculated result as a Response. I could think of two ways of doing this, which would be more efficient (or the correct was to do it, if any): 1. Calculations using Pandas Create a view which will be called with a GET request Get the querysets of data from the necessary tables Convert them to pandas DataFrames Perform the necessary calculations Reconvert the DataFrame to a JSON object and return a Response 2. Create a Separate Model, Serializer and View for the Calculations If there is some other library or method that can do this, please provide some suggestions -
Text beneath image going out of circular div
I have a circular div which I made by applying some css styling like border-radius. Within the div, it contains an icon and below the icon, the corresponding text. However, the image is getting displayed properly, but the text is going out of the div. There is much vertical space between the icon and the text. How do I solve this? Here is my code: .internship_cat{ object-fit: contain; background-color: #06314e;; margin-top: 5px; margin-bottom: 10px; margin-left:10px; border-radius: 50px; transition: transform 450ms; width: 110px; height: 110px; align-items: center; justify-content: center; } .internship_cat:hover{ transform: scale(1.08); } </style> <div class="internship_categories" style="margin-top:10px; display:flex; overflow-x:scroll; overflow-y:hidden" > {% for ind_type in industry_type %} <div class="internship_cat"> <img src="{{ ind_type.picture_icon.url }}" alt="" width="100" height="100"> <span class="caption" style="color: white; ">{{ind_type.industry_name}}</span> </div> {% endfor %} -
Am beginner with Django & angular and I want to upload an excel file path from angular to a function in Django and make some modification to the file
I am developing an application using Django and angular I want to upload an excel file path from angular to a function in Django to be able to upload data from excel to the database -
Filter queryset objects based on who user follows (Django)
I'm trying to figure out a feature in a webapp whereby a logged in user can filter objects within a specific set of coordinates that have been "listed" by other users who the logged in user follows. (I'm using Google Maps API) I have gotten it to the point where the objects within the coordinates show up but I can't figure out the next step whereby these objects are filtered again so only objects "listed" by users whom the logged in user follows show up. Here is what I do have: Views def get_friends(request): template_name = 'testingland/electra.html' neLat = request.GET.get('neLat', None) neLng = request.GET.get('neLng', None) swLat = request.GET.get('swLat', None) swLng = request.GET.get('swLng', None) ne = (neLat, neLng) sw = (swLat, swLng) xmin = float(sw[1]) ymin = float(sw[0]) xmax = float(ne[1]) ymax = float(ne[0]) bbox = (xmin, ymin, xmax, ymax) geom = Polygon.from_bbox(bbox) qs = mapCafes.objects.filter(geolocation__coveredby=geom) user = request.user print(user) return JsonResponse([ [cafe.cafe_name, cafe.cafe_address, cafe.geolocation.y, cafe.geolocation.x] for cafe in qs ], safe=False) Models: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=1000) image_embed = models.CharField(max_length=10000) class Meta: managed = … -
User matching query does not exist. help me this problem
My traceback Traceback (most recent call last): File "C:\Users\DELL\anaconda3\envs\sv_env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\DELL\anaconda3\envs\sv_env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\DELL\Downloads\Cv-Builder-URL-Shortener\Cv-Builder-URL-Shortener-Django-master\cvBuilderApp\views.py", line 30, in Detail detail = User.objects.get(username=slug) File "C:\Users\DELL\anaconda3\envs\sv_env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\DELL\anaconda3\envs\sv_env\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /jobskill/ Exception Value: User matching query does not exist. My view.py def home(request): context = { 'title': 'Home Page', } if request.user.is_authenticated: if request.method == 'POST': temp = updateTemplate(request.POST, request.FILES, instance=request.user.profile) if temp.is_valid(): temp.save() messages.success(request, f'Your Template has been Saved!') return redirect('/') else: temp = updateTemplate(instance=request.user.profile) context['temp'] = temp return render(request, 'home.ejs', context) def Detail(request, slug): detail = User.objects.get(username=slug) template = detail.profile.template context = { 'title': detail.profile.name, 'detail': detail, } return render(request, template, context) -
one field type to oter field type by selected value
Django admin replace functionality fileField() to textField by selected value for example example -
django forms clean method returning only last object
I am trying to save multiple images, here is my code in short: forms.py class ImageForm(forms.ModelForm): image = forms.ImageField(label='Image', widget=forms.ClearableFileInput(attrs={'multiple': True})) file_remover = forms.CharField(required=False, widget=forms.HiddenInput()) class Meta: model = Images fields = ('image', 'file_remover', ) def clean(self): self.cleaned_data = super().clean() print("self.cleaned_data:", self.cleaned_data) #------------->Notice this print line return self.cleaned_data This print line prints only last object of the form: self.cleaned_data {'image': <InMemoryUploadedFile: property_image_7.jpeg (image/jpeg)>, 'file_remover': ''} But I checked in request.FILES in the views.py, it has all the files coming in the request. class PropertyCreate(CreateView): form_class = ImageForm success_url = reverse_lazy('iamge_list') def post(self, request, *args, **kwargs): try: files = self.request.FILES.getlist('image') print('files', files)#------------->Notice this print line image_form = ImageForm(request.POST, request.FILES) if image_form.is_valid(): image_form.save() except Exception as e: print("Error in Image upload", e) return render(request, self.template_name) This print line prints all the files in memory: files [<InMemoryUploadedFile: property_image_1.jpeg (image/jpeg)>, <InMemoryUploadedFile: property_image_2.jpeg (image/jpeg)>, <InMemoryUploadedFile: property_image_6.jpeg (image/jpeg)>, <InMemoryUploadedFile: property_image_7.jpeg (image/jpeg)>] Where it has gone wrong? Why self.cleaned_data from clean method of the form returning last object only? -
Is there any way I can get html's of wagtail admin screen?
I am trying to integrate wagtail admin into my existing project. I have tried creating 'wagtailadmin' folder under my app template and override wagtailadmin/home page. But I wanted to know is there any way I can refer/get all default HTML's pages displays on wagtailadmin screen. for eg. html for below screen. -
Django Storages: Dynamic paths for objects being uploaded to AWS S3
I am using django-storages to manage media files on AWS S3. I would like to structure their object names as so: <model_name>/<field_name>/<object_id>/<file_name>.<file_extension>. With simple django-storages configuration, I have been able to upload files only to the root of the S3 bucket, i.e with no prefixes to the object name. How do I build this without providing the full path as file name when adding and saving files on an object? -
ERROR <HttpResponse status_code=200, “text/html; charset=utf-8”> DJANGO
I get error <HttpResponse status_code=200, "text/html; charset=utf-8"> when i try to pass ip class fichador_view_entrada(CreateViewEntrada): model = fichador fields = ['Codigo'] success_url = reverse_lazy('home') def form_valid(self, form): form.instance.tipo = "Entrada" form.instance.ip = getIPAddresses(self) return super(fichador_view_entrada, self).form_valid(form) def getIPAddresses(self): import socket hostname = socket.gethostname() ip_add = socket.gethostbyname(hostname) return HttpResponse(ip_add) -
ValueError when making a variable, to be global over all templates
the error everything works fine untile this line 'cart.context_processors.Cart', added into the templates in the settings.py file from decimal import Decimal from django.conf import settings from shop.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # mark the session as "modified" to make sure it gets saved self.session.modified = True def remove(self, product): """ Remove a product from the cart. """ product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] … -
Remove duplicate values in django forloop
i have some dates in a list and I want to display all days in the list using forloop at Django template. what I want is to remove duplicate days in it. here is the sample code {% for part_time_day in part_time %} {{part_time_day.start_time|date:"D"}}, {% endfor%} it will display all the days like "Sun, Mon, Fri, Sun" etc but I want to remove duplicate days so one day can display only once -
forward slash url router is not working in django but its working in react.js
what i want to do is when i type something after forward slash react app does it right accordibng to my code, but when i launch from django server it does not show any url page after forward slash. localhost:8000 = django localhost:3000 = react this is my react app index.js file import React from "react"; import ReactDOM from "react-dom"; import "./index.css"; import "./fonts.css"; import App from "../src/App"; import { BrowserRouter } from "react-router-dom"; ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode>, document.getElementById("root") ); App.js file import React, { Component } from "react"; import "./App.css"; import { Switch, Route } from "react-router-dom"; import { Provider } from "react-redux"; import AppRoot from "./appRoot"; import configuredStore from "./store/configureStore"; class App extends Component { constructor(props) { super(props); this.state = {}; } render() { console.log("App Rendering Started"); return ( <Provider store={store}> <div id="app"> <Switch> <Route exact path="/signin" component={SignInPage} /> <Route exact path="/signup" component={SignUpPage} /> <Route exact path="/write/:slug" component={CKEditor5} /> <Route exact path="/not-found" component={notFound} /> <Route path="/" component={AppRoot} /> </Switch> </div> </Provider> ); } } export default App; this is my django url setting urls.py from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), …