Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
About python, Django-Filters drop-down default value of selected
I am new to python, and there was a problem when I was learning the Django-filter framework. When I made a filter form in the module, the front end would display a default value of'-------'. I would like to ask How to modify the backend ''' from django.db import models class test(models.Model): NAME_CHOICES=( ("","any"), ("test1","test1"), ("zzz","zzz"), ) name= models.CharField(max_length=256,verbose_name=u"xxx",default=u'zzz',choices=NAME_CHOICES) sex = models.CharField(max_length=256, verbose_name=u"xxx", default=u'men') -
How to use (AbstractBaseRating) with django star rating.Extend it with custom model
When we use django star rating it only gives out star rating.But I have to extend it with reviews models to get ratings with reviews. class Reviews(AbstractBaseRating): user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) name = models.ForeignKey(Profile , on_delete=models.CASCADE, default=None) course = models.ForeignKey(Courses, on_delete=models.CASCADE, default=None) -
problem to install psycopg2 because of my macbook m1 cheap
i bought a macbook to train me how to use mac os environment, i want to make django app on pycharm but i'm not able to intall psycopg2 because of my processor M1 et want to know if there is a solution or did we need to wait an update from apple or psycopg2 creator ? i remember a soluton i tried few weeks ago, it was about changing something in my mac settings, i belive it was called "rosetta" maybe or something like that but doesnt work or i doesnt dont it well. thank you for help :) -
How to use Django logged-in user admin information in app
Is possible to pass the currently logged-in user full name/group etc. into a Dash app created in Django? Assume you for instance have a Dash datatable want to pass the logged in name into the data table. How can this be done? For example, creating a variable "name" through "name = request.user.get_full_name" or some type of similar statement does not work (of my knowledge). Thanks! -
How to import views.py file in django in custom .py file
I'm having fun.py file in same folder as views.py but whenever I import views.py file I get error. Other files are getting imported but views.py, models.py such files are getting imported. Please help me I have few days to complete my project. Your help will be appreciated. -
I am unable to successfully use my css file in my django project
[03/May/2021 11:44:59] "GET /add_food/ HTTP/1.1" 200 4583 [03/May/2021 11:44:59] "GET /static/css/base.css HTTP/1.1" 404 1763 [03/May/2021 11:45:04] "GET / HTTP/1.1" 200 3812 [03/May/2021 11:45:04] "GET /static/css/base.css HTTP/1.1" 404 1763 [03/May/2021 11:46:24] "GET / HTTP/1.1" 200 3812 [03/May/2021 11:46:24] "GET /static/css/base.css HTTP/1.1" 404 1763 [03/May/2021 11:48:07] "GET / HTTP/1.1" 200 3812 [03/May/2021 11:48:07] "GET /static/css/base.css HTTP/1.1" 404 1763 This is the error I am facing on running the server and reloading the localhost. the part where I have added my static file is as follows <link href="{% static 'css/base.css' %}" rel="stylesheet"> where i have defined static in settings.py is as follows: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'static_saved') my project structure is linked here ---> link what am i doing wrong? -
How to add new python packages to existing Docker image?
I'm following throught the Compose tutorial on Django: https://docs.docker.com/samples/django/ It uses a requirements.txt file to define Python packages and then builds the image and creates a Django project: sudo docker-compose run web django-admin startproject composeexample . I noticed that after adding another dependency to requirements, I couldn't issue the docker-compose run web command again without receiving this error: CommandError: /code/manage.py already exists. Overlaying a project into an existing directory won't replace conflicting files. What is the correct way of rebuilding the image after having added new dependencies? -
Django, how to send the form and related formset to the template
Requirement: I want to create a new course for my E-learning website, but the time I save the course I should be able to assign the score type for that course which has to fields score_type and score. My Model # Course Model class Course(models.Model): owner = models.ForeignKey( UserAccount, related_name='courses_created', on_delete=models.CASCADE) curriculum = models.ForeignKey( Curriculum, related_name='curriculums', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField() description = models.TextField() cover_photo = models.ImageField(upload_to="cover/", null=True, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title # Score Allocation Model class CourseScoreAllocation(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) score_type = models.CharField(max_length=200) score = models.FloatField() def __str__(self): return self.score_type Now I am using django formset to create a dynamic form forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['curriculum', 'title', 'description', 'cover_photo'] widgets = { 'description': forms.Textarea(attrs={'rows': 3}) } ScoreFormset = inlineformset_factory( Course, CourseScoreAllocation, fields=['score_type', 'score'], extra=1, can_delete=True) views.py class OwnerListMixin(object): def get_queryset(self): qs = super().get_queryset() return qs.filter(owner=self.request.user) class OwnerCourseMixin(OwnerListMixin, LoginRequiredMixin, PermissionRequiredMixin): model = Course fields = ['curriculum', 'title', 'description', 'cover_photo'] success_url = reverse_lazy('manage_course_list') class ManageCourseListView(OwnerCourseMixin, ListView): template_name = "courses_app/manage/course/list.html" permission_required = "courses_app.view_course" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['form'] = CourseForm() context['formset'] = ScoreFormset() return context class CourseCreateView(OwnerCourseMixin, CreateView): permission_required = "courses_app.add_course" template_name = "courses_app/manage/course/form.html" success_url … -
Allowing user to cancel long running API call
A django project I work on allows a user to preview a document made on our site before downloading it. The process takes some time on the backend which is why we allow the user to cancel the operation on the frontend. But even after the user cancels the process, it still keeps running on the server wasting time and compute. We use a simple django-rest-framework api function with no socket connection or anything asynchronous that allows the frontend to track the progress of the task. I would like to know if there is some way we can abort the function execution on the backend if the user decides to cancel the operation on the frontend. I'd share any code but I don't think it'll be useful because the function just prepares the document and then sends it. -
Why get_current_site(request) Django doesn't return the port number?
I have deployed my Django app to IP with port :8080, and when the views.py call get_current_site(request) function, it only returns the IP without the port number. Why? Is it related with Nginx-server? server { listen 8080; server_name example.org; charset utf-8; location /static { alias /static; } location /media { alias /media; } location / { proxy_pass http://server-mongo:8080; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }