Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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')), … -
MultiValueDictKeyError. Exception Value: 'tipo'
I am trying to send the value of a button to a search page by filters. This page is made up of several urls, each one to make a query with a type of filter. My view POST collects the value of the 'type' and sends it to the getType view, but when it receives it, it gets a MultiValueKeyError. How can I submit the type filter to the search page? views.py class Index(ListView): model = Coche, CocheBrand, CocheModel, CocheType, CocheDoors, CocheGearshift, Localidad context_object_name='coche_list' form_class = IndexSearch def get_queryset(self):# coches = Coche.objects.filter(reserved=False, sold=False).order_by('-precio')[:2] total_coches = Coche.objects.filter(reserved=False, sold=False).count() queryset = {'coches':coches,'total_coches':total_coches} return queryset def get_context_data(self): context = super(Index, self).get_context_data() context['marca'] = CocheBrand.objects.all() context['modelo'] = CocheModel.objects.all() context['tipos'] = CocheType.objects.all() return context def CocheList(request): #LOAD SEARCH PAGE return render(request,'wallacar_app/cars.html',{} ) class CocheListing(ListAPIView): pagination_class = StandardResultsSetPagination serializer_class = CocheSerializers def get(self, request): if request.POST['tipo']: getType(request) return render(request, 'wallacar_app/cars.html') def get_queryset(self): queryList = Coche.objects.all() brand = self.request.query_params.get('brand',None) model_name = self.request.query_params.get('model_name',None) type_car = self.request.query_params.get('type_car',None) if brand: queryList = queryList.filter(brand = brand) if model_name: queryList = queryList.filter(model_name = model_name) if type_car : queryList = queryList.filter(type_car = type_car) def getType(request): if request.POST['tipo'] and not request.method == 'GET': type_car = Coche.objects.filter(type_car=request.POST['tipo']).order_by('type_car').values_list('type_car').distinct() type_car = [i[0] for i in list(type_car)] data … -
Django many to many relation, include all IDs in queryset in both directions
I have 2 models connected via M2M relation class Paper(models.Model): title = models.CharField(max_length=70) authors = models.M2M(B, related_name='papers') class Author(): name = models.CharField(max_length=70) Now, is there a way to include authors as all related authors' IDs (and maybe name somehow) is there a way to include papers IDs as reverse relation (and maybe title as well) Author.objects.all().annotate(related_papers=F('papers')) this only adds id of one paper, first one it finds I think. Furthermore, changing related_papers to papers gives an error: ValueError: The annotation ‘papers’ conflicts with a field on the model. -
Is there a way to test local running server (Django), with selenium, inside a Bitbucket pipeline?
I'm pretty sure there is a better, proper, workflow for testing a local server with selenium inside a cloud environment. But as things stand now, I have a local server on my machine that runs Django and some tests (PyTest, Selenium for the UI part). Server spins on localhost and all tests running just fine. I have integrated with Bitbucket Pipeline, committed and pushed, tests passed. until the point where selenium introduced, Because now I can't commit the selenium as it will surely fail, the server will be deployed right, but it won't spin - so no live localhost at the cloud environment. I saw this post about running selenium in Bitbucket : https://medium.com/nonstopio/run-selenium-tests-in-bitbucket-pipeline-64e0dcdd1a1f But I guess it addresses the need of developers who want to test real websites, and in that case I need to upload my localhost live somewhere. I can add code, but I think there is a point I need to get here. -
Ride booking system using django
I am building a web-based ride booking system where users will be able to make a book the number of seat and they can cancel their booking. This is my first own web project and first-time using Django. So, the idea is that the user signed in as a driver can create a ride giving details about the source, destination and departure time, available seats etc. The logged in users can book a ride selecting a number of seats they want to book from the available seats from a particular ride. The number of seats booked have to be subtracted from that ride after booking. I was not getting resources similar to what I am looking. Any help would be appreciated Thanks :) -
Django Object is not iterable in template but in view
I have following models: class Examination(models.Model): enumeration = models.CharField(_('Enumeration'), max_length=10, blank=False, null=False, default='Examination XYZ') schoolclasses = models.ManyToManyField(SchoolClass, related_name='examinations') competences = models.ManyToManyField(Competence, blank=True, through='ExamCompetence', related_name='examinations') class ExamCompetence(models.Model): examination = models.ForeignKey(Examination, on_delete=models.CASCADE, related_name='examination_competences') competence = models.ForeignKey(Competence, on_delete=models.CASCADE) score = models.DecimalField(max_digits=3, decimal_places=1, default=0) In the view I may call examination.examination_competences.all() and it returns a queryset with 2 items. But in the template {% for comp in examination.examination_competences.all %} I receive an error saying: TypeError: 'ExamCompetence' object is not iterable I'm lost :)) any help will be appreciated. -
How to Implement Django Commision payment
How can I implement a commission based payment like amazon where a store can be paid by a custumer and I get a % of the payment as commission? -
CORS issue when using javascript on iframe rendered with s3 url
In my Django site, I need to show html content from s3 in a div/iframe and scroll the div/iframe using javascript. Javascript fetch/ajax is slow. I need to display the content really fast. With iframe I receive the error: Blocked a frame with origin "http://localhost:8000" from accessing a cross-origin frame. Iframe is not sending origin header to s3. I need to display content really fast in my site. The content is present in s3 and I also need to use javascript on the content. Somebody please guide me. -
Django: Display message after creating a post
How do i add a simple message after user creates a post e.g "Post has been created" views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm def form_valid(self, form): form.instance.author = self.request.user ##author = current logged in user return super().form_valid(form) base.html {% if messages %} {% for msg in messages %} <div class="alert alert-info alert-dismissable"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> {{msg.message}} </div> {% endfor %} {% endif %}