Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 %} -
Struggling with adding app to INSTALLED_APPS Django
I have no idea, this always worked for me, but without motivation, it's not working now. what i did: I created my project I created my app I added my config to INSTALLED_APPS I get this error: django.core.exceptions.ImproperlyConfigured: 'champ.apps' does not contain a class 'ChampConfigcorsheaders'. Choices are: 'ChampConfig'. My project looks like this: Championship_3bi champ all the files of the app Championship_3bi all the files of the project This is my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'champ.apps.ChampConfig' #this is the line that create the "error" 'corsheaders', ] I've also tried to do champ.apps.ChampConfigcorsheaders but it didnt work. This is my champ/apps.py: from django.apps import AppConfig class ChampConfig(AppConfig): name = 'champ' i searched for everything but looks like i was the only one who get this error. The reason why it does not work is for the weird name of my project? Why it is not working for only this project? im done -
How can I group a list of values by cities in a given time interval
I am developing a web application where I would like to calculate the quantity of production per city for the last five years. Now I am able to calculate the quantity by city, but I am not to limit it to a given period interval. Here is the views def ProductionStat(request): productions = Production.objects.all() lignes = LigneProduction.objects.all() # Quantity of production par islands quantityByIle = [] list_iles = [] Quantities_by_ile=LigneProduction.objects.values('ile_id').annotate(Total_quantite=Sum('quantite_produit')) for dict_item in Quantities_by_ile: quantityByIle.append(dict_item['Total_quantite']) if dict_item['ile_id']==1: list_iles.append('Ngazidja') elif dict_item['ile_id']==2: list_iles.append('Mohéli') elif dict_item['ile_id']==3: list_iles.append('Anjouan') else: list_iles.append('Mayotte') print(list_iles) print(quantityByIle) context={ 'list_iles':list_iles, 'quantityByIle':quantityByIle, } return render(request, 'siga/StatProduction.html', context) Here is the models class LigneProduction(models.Model): ile = models.ForeignKey(Iles, on_delete = models.CASCADE, null=True) production = models.ForeignKey(Production, on_delete = models.CASCADE, null=True) produit = models.ForeignKey(Produits, on_delete = models.CASCADE, null=True) annee_production = models.CharField(_('Année de production'), max_length=20) superficie_cultive = models.IntegerField(_('Superficie cultivée'), null=True, default=0) quantite_produit = models.IntegerField(_('Quantité de production'), blank=True, default=0) prix_production = models.DecimalField(_('Coût de production'), max_digits=10, decimal_places=2, default=0, blank=True) utilisation = models.BooleanField(_('Fértilisée (Oui/Non)?'), default=False) intrant = models.ForeignKey(IntrantAgricole, on_delete=models.CASCADE, null=True) kilogramme = models.IntegerField(blank=True, default=0) Please assist. -
Django 2.1.X: (models.E026) The model cannot have more than one field with 'primary_key=True'
I am currently upgrading a legacy Django app from version 1.11 to 3.2. In order to minimize risks I am upgrading one minor version at a time. That means: 1.11 --> 2.0 --> 2.1, etc. When upgrading from version 2.0.13 to 2.1.15 I have encountered the following error when attempting to open the Django shell: python manage.py shell_plus SystemCheckError: System check identified some issues: ERRORS: myapp.DemoModel: (models.E026) The model cannot have more than one field with 'primary_key=True'. Here is my model: class DemoModel(models.Model): field_a = models.OneToOneField(ModelA, models.DO_NOTHING, primary_key=True) field_b = models.OneToOneField(ModelB, models.DO_NOTHING, primary_key=True) creation_time = models.DateTimeField(auto_now=True) class Meta: managed = False db_table = 'demo_model' unique_together = (('field_a', 'field_b'),) How could I fix this? Django shell has worked with all versions prior to Django 2.1. Thanks in advance. Kind regards, -
SELECT AUTOMATICALLY FOREIGN IN A FORM
I have a form roatype inside a network. I would like, when creating the form, the network foreign key must be automatically selected. For example in screenshoot, network with id 3 should be automatically selected. models class RoadType(models.Model): name = models.CharField('Road Type', max_length=200, blank=False) congestion_choices = ( ('Free flow', 'Free flow'), ('Congestion', 'Congestion'), ) network = models.ForeignKey(RoadNetWork, on_delete=models.CASCADE) congestion = models.CharField(max_length=200, choices=congestion_choices) default_speed = models.FloatField(default=50) default_lanes = models.SmallIntegerField(default=1) default_param1 = models.FloatField(default=1.0) default_param2 = models.FloatField(default=1.0) default_param3 = models.FloatField(default=3.0) views but doesn't select automatically the network: def create_roadtype(request, pk): """A roadtype depends on a project. It must be created inside the roadnetwork""" current_network = RoadNetWork.objects.get(id=pk) form = RoadTypeForm(initial={'roadnetwork':current_network}) if request.method == 'POST': road_type = RoadType(network=current_network) form = RoadTypeForm(request.POST, instance=road_type) if form.is_valid(): form.save() return redirect('home') return render(request, 'views/roadtype.html', {'form': form}) -
Django Send Email Error: ConnectionRefusedError: [Errno 61] Connection refused
I was trying to send an email via Django using the send_mail() function from django.core.mail when I ran into this error: ConnectionRefusedError: [Errno 61] Connection refused This is my code, straight from the docs: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) I replaced from@example.com with one of email IDs and I replace to@example.com with one of my other email IDs. When I run runserver, I get this peculiar error $ python3 manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/adithraghav/Documents/Work/env/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) … -
getting error qhile creating dmin in djnago user
enter image description here' when I execute the command localohost:8000/admin I got the following error I have checked URLs,py i don't find any errors there -
Want to perform left join in django
Say I've 2 models Model Users: Name: Id: And attendance Model Attendance: user: foreign_key(User) present: [present if login else nothing recorded] Date: users = User.objects.all() todays_present = Attendance.objects.filter(date=today) Now for instance Users = 10 todays_present = 7 I want to find which three users are not in todays_present.