Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I omit .virtualenv packages when testing Django project with Coverage.py
I have a Django project which I want to test with Coverage.py. I want to exclude the files in .virtualenvs. I am using pipenv and the editor is VS Code. Coverage version is 5.5 I followed the documentation instructions to create a .coveragec file in the root directory of the project. I then ran the test but Coverage does not omit the packages in .virtualenvs. .coveragec [run] source = . omit = *.virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* [report] omit = *.virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* When this approach did not work, I then resorted to using the Command line approach. This did not also work. cmd commands coverage run --omit=*./virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* manage.py test -v 2 coverage html --omit=*./virtualenvs/*,*tests*,*apps.py*,*manage.py*,*__init__.py*,*migrations*,*asgi*,*wsgi*,*admin.py*,*urls.py* I have also used .venv instead of .virtualenvs but it still does not work. What can I do? -
Django models.Model & DJANGO_SETTINGS_MODULE throwing error on "import" command
Getting a django.core.exception error when trying to invoke the API using from newapp.models import NewApp. I have added the newapp App to the INSTALLED_APPS section of the settings.py file. There are several sources such as this one: Error with setting DJANGO_SETTINGS_MODULE variable while running debug in PyCharm However, it does not lead to a resolution. I've tried set DJANGO_SETTINGS_MODULE but that doesn't help here. I have tried export DJANGO_SETTINGS_MODULE I have tried using python settings: After trying the os.environ approach, i get a new error 'Apps aren't loaded yet' There error suggests to call settings.configure() but I can't find any sources online about how to do this. Seems if I don't use models.Model then I don't get the error? What on earth am I doing wrong? This is such a basic task. It seems like others have struggled with this but there is no clear answer out there. -
Raw query results multiplies many times when I use INNER JOIN in Django
I can't figure it out why my raw query multiplies the result as many time as the number of users. I'm using INNER JOIN and I bonded two objects so I really can't get it. (I'm not experienced in Django Query Language so I'm using raw query). views.py def index(request): projekt = Projekt.objects.raw('SELECT projekt_id, stressz_projekt.projekt, last_name, first_name, stressz_profile.id, stressz_profile.user_id, auth_user.id FROM stressz_profile INNER JOIN stressz_projekt ON stressz_projekt.id = stressz_profile.projekt_id INNER JOIN auth_user ON auth_user.id = stressz_profile.user_id') template = loader.get_template('stressz/index.html') context = { 'projekt': projekt, } return HttpResponse(template.render(context, request)) -
How to use PUT operation without ID in url with django
I was trying to implement a PUT method without an ID although this does not comply with REST principle. However I was just wondering if this can be done in anyway because I can easily get User instance from self.request.user. So, if I make the view class ProfileViewSet(mixins.ListModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): serializer_class = UserProfileSerializer permission_classes = [IsAuthenticated] queryset = User.objects.all() lookup_field = 'username' def get_object(self): try: return User.objects.get(pk=self.request.user.id) except User.DoesNotExist: raise NotFound() def update(self, request, *args, **kwargs): ............??? Unfortunately, I could not reach the update function as it always throw an exception saying "PUT method is not allowed". Thanks in advance. -
Sort ForeignKey field on Wagtail Page
I'm trying to sort a ForeignKey field on Page content type, which references another Page. class MyPage(Page): ... partner = models.ForeignKey( 'education.PartnerPage', on_delete=models.CASCADE, related_name="+" ) The PartnerPage model (a simple Page type) is inside a different app (but the same project). Wagtail seems to ignore ordering in the Meta class on the model definition, maybe because of the Page tree ordering. I don't need custom ordering (so its not useful to make it an Orderable), I just need the PartnerPages to appear in alphabetical order from the MyPage form. In the content panels I tried: FieldPanel('partner', widget=forms.Select( choices=PartnerPage.objects.all().order_by('title').values_list('pk', 'title') )) but can't import PartnerPage because "Models aren't loaded yet" (not sure what that means). -
How to highlight the current section [Power Apps Menu]
When navigating in the menu bar, some of the options are not selected. I have tried to do it with JQuery but my attempts are in vain. Briefly what I am looking for is that if the user clicks Home Page it will be marked with a color and if About Us is clicked, the above selection will suffice and it will be marked as new. I tried using the condition {% if request.path ==" / "%} class =" weblink active mr-3 "{% else%} class =" weblink mr-3 "{% endif%} in the "Option 1 "but it didn't work. What am I doing wrong? {% if user %} <li role="none" {% if request.path=="/"%}class="weblink active mr-3" {% else %} class="weblink mr-3"{% endif %}> <a role="menuitem" aria-label="P&#225;gina principal" href="/" title="P&#225;gina principal" > P&#225;gina principal </a> </li> <!--Option 2--> <li role="none" class="weblink dropdown"> <a role="menuitem" aria-label="Servicios" href="#" class="dropdown-toggle" data-toggle="dropdown" title="Servicios" > Servicios <span class="caret"></span> </a> <ul class="dropdown-menu" role="menu"> <li role="none"> <a role="menuitem" aria-label="Servicios" href="/services/" title="Servicios" >Servicios</a> </li> <div class="divider"></div> <li role="none"> <a role="menuitem" aria-label="Producto A (ejemplo)" href="/services/product-a/" title="Producto A (ejemplo)" > Producto A (ejemplo) </a> </li> <li role="none"> <a role="menuitem" aria-label="Producto B (ejemplo)" href="/services/product-b/" title="Producto B (ejemplo)" > Producto B (ejemplo) </a> </li> </ul> … -
Django The redirect_uri does not match the registered value for linkedin signup
I am trying to add linkedin signup to my website but I am getting this error: "Bummer, something went wrong.The redirect_uri does not match the registered value" I am using django social-auth. I put this redirect url in linkedin OAuth 2.0 settings: https://www.example.com/complete/linkedin-oauth2/ I also found few question on stackoverfolow and followed but didn't work. question1 -
Request URL : http://127.0.0.1:8000/searchapp/?csrfmiddlewaretoken=qW5J7j0FQWjRQQgFsiWpX9hVh3YQ2loqZL5IuJnsZeJe2YDIcBM33wpVDBoUSAxx&q=black
Raised by: shop.views.allproduct project.urls """ecommerceproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('shop.urls')), path('searchapp/',include('searchapp.urls')), path('cart/',include('cart.urls')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i cannot acesses the search app. that is when i enter the shop app and try to search a product i am not able to search the item.as it is not accessing to the search app from shop app.please help me with this issue.this issue was somewhat solved by renaming the urls from '' to 'shop/'.but it is not a perment remady.please help me with this -
ImportError: No module named 'base' django1.8
I have django 1.8 this was working fine with Python 2.7 in my Windows, now I upgraded from Python 2 to Python 3 (Python 3.5.0) in my Windows pc, https://docs.djangoproject.com/en/3.2/releases/1.8/ Python compatibility Django 1.8 requires Python 2.7, 3.2, 3.3, 3.4, or 3.5. We highly recommend and only officially support the latest release of each series. Django 1.8 is the first release to support Python 3.5. Then I've created a virtual env with this command: python C:\Python35\Tools\Scripts\pyvenv.py e:\myproject_development_new\myproject_project\myproject\myenv Then I have installed manually all the requirements with pip install: Django==1.8.18 Pillow==2.9.0* beautifulsoup4==4.4.1 dj-database-url==0.3.0 django-ckeditor==5.0.3 django-hvad==1.4.0 django-imagekit==3.3 django-model-utils==2.4 flickr-api==0.5 inlinestyler==0.2.3 lxml==3.5.0 -e git+https://github.com/arneb/pyslideshare2.git@47cad8309ea2d6fe0f6cf0da13a486681a410128#egg=pyslideshare2-master requests==2.8.1 libsass==0.19.4 sass==2.3 sqlparse==0.1.16 XlsxWriter==1.0.2 django-debug-toolbar==1.4 honcho==0.7.1 mysqlclient==1.3.9 python-memcached==1.58 And all needed modules have been installed. Now I try to launch my webapp with this command: python manage.py runserver 80 And I see this error: (myenv) E:\myproject_development_new\myproject_project>python manage.py runserver 80 Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "e:\project_development_new\myproject_project\myproject\myenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\core\management\__init__.py", line 303, in execute settings.INSTALLED_APPS File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 48, in __getattr__ self._setup(name) File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "e:\myproject_development_new\myproject_project\myproject\myenv\lib\site-packages\django\conf\__init__.py", line 92, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python35\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], … -
Getting POST requests Django Python
I have Django framework in my site, and i need to receive post request from user. So, how I can do this, and how may i process this request(etc, after getting post request, pull this datas) -
How to connect SQLlite to a project in Django (not an app)
While creating the project I didn't create an app and did everything in the base project. Now I am trying to connect database to my base project(not the app) I tried 'python manage.py makemigrations' but its showing "No changes detected". I even tried adding my project to INSTALLED_APPS in settings.py and then trying 'python manage.py makemigrations ' but it is showing an error " for model in model_or_iterable: TypeError: 'type' object is not iterable " I have created two models and also registered the models in admin.py 'admin.site.register(studentlogin), admin.site.register(facultylogin) I need help !! -
Django ORM: how to get 10 most recent Comments for each Post in a queryset
I have a Post model and Comment model which has FK to Post and a timestamp. I want to select all Posts, and for each Post I want to select 10 most recent comments available. This is for the django REST framework serializer to include those 10 Comments for each serialized Post. I want the query to be efficient, avoid making 101 selects when serializing a page of 100 Posts. prefetch_related does not seem to allow to slice X records for each selected record. annotation and subqueries won't work beacause it cannot return a list of objects. -
Django The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. even though my fields are little
I created a script to programmatically upload data to my backend, but django keeps throwing the The number of GET/POST parameters exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. error at me, here is the data I am sending {'store': 'dang-1', 'name': 'Nike Air Max Plus', 'description': 'Let your attitude have the edge in your Nike Air Max Plus, a Tuned Air experience that offers premium stability and unbelievable cushioning.', 'brand': 'Nike', 'model': 'Air Max Plus', 'gender': 'U', 'category': 'shoes', 'image_v0_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v0_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).png'>, 'image_v0_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (3).jpg'>, 'image_v1_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v1_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).png'>, 'image_v1_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (1).jpg'>, 'image_v2_1': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'image_v2_2': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).png'>, 'image_v2_3': <_io.BufferedReader name='data/images/shoes/Nike Air Max Plus/image (2).jpg'>, 'variants': '[{"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "black"}, {"is_default": false, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "multi-colored"}, {"is_default": true, "price": 65000, "quantity": 10, "shoe_size": 45, "color": "green"}]'} And here is the script I created import json import requests if __name__ == '__main__': json_file = open('data/data.json') products = json.load(json_file).get("products") for index, product in enumerate(products): print(f"Creating {index + 1}/{len(products)} - {product.get('name')}") … -
Specify exact opening hours for buisness
im trying to create custom field for django model. I need to store opening hours for every day of the week. class Restaurant(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) city = models.CharField(max_length=15) street = models.CharField(max_length=15) house_number = models.CharField(max_length=3) flat_number = models.CharField(max_length=3, default='0') phone_number = models.CharField(max_length=12) image = models.ImageField() rating = models.FloatField(validators=[validate_rating_number]) def __str__(self): return f'{self.name}, {self.city}' I have to store opening hours in a field like opening_hours = models.CustomField() -
Django dynamic url with data from DB
Models.py from django.db import models # Create your models here. class reviewData(models.Model): building_name = models.CharField(max_length=50) review_content = models.TextField() star_num = models.FloatField() class buildingData(models.Model): building_name = models.CharField(max_length=50) building_loc = models.CharField(max_length=50) building_call = models.CharField(max_length=20) views.py # Create your views here. from django.shortcuts import render from rest_framework.response import Response from .models import reviewData from .models import buildingData from rest_framework.views import APIView from .serializers import ReviewSerializer class BuildingInfoAPI(APIView): def get(request): queryset = buildingData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(request): queryset = reviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) urls.py from django.contrib import admin from django.urls import path from crawling_data.views import ReviewListAPI from crawling_data.views import BuildingInfoAPI urlpatterns = [ path('admin/', admin.site.urls), path('api/buildingdata/', BuildingInfoAPI.as_view()), #path('api/buildingdata/(I want to put building name here)', ReviewListAPI.as_view()) ] I am making review api. I want to use building name as url path to bring reviews for specific buildings For example, there are a, b, c reviews a, b reviews are for aaabuilding c reviews are for xxxbuilding api/buildingdata/aaabuilding (only shows aaabuilding review) { building_name = aaabuilding review_content = a star_num = 5 building_name = aaabuilding review_content = b star_num = 3 } api/buildingdata/xxxbuilding (only shows xxxbuilding review) { building_name = xxxbuilding review_content = c star_num = 4 … -
How to add a date and time column in my Django default user page in admin
I am using the Django default user model and in my admin, I can see 5 columns which are username, email address, first name, last name, and staff status. I need to add another column here that displays the date joined. Can anyone help here? thanks in advance -
How to call a dropdown list html select with Ajax JQuery in Django
I'd like to choose an option in the first select dropdown list and based on the selected option, the ajax should load the second select dropdown list, how to do it? This is my code: Models: class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id Views: from django.shortcuts import render from maintenance.models import MaintenanceEquipment def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): if request.method == 'GET': line = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line) context = {'equipment': equipment} return render(request, 'maintenance/maintenanceIssue.html', context) urls: urlpatterns = [ path('maintenanceIssueView/', views.maintenanceIssueView, name="maintenanceIssueView"), path('ajax/load_equipment/', views.load_equipment, name="ajax_load_equipment"), ] maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="sequence" name="sequence"> {% for instance in equipment %} <option value="{{ instance.sequence }}">{{ instance.sequence }}</option> {% endfor %} </select> </div> </div> </div> </form> <script> … -
Django Combine Common Values from Joining Two List of Dictionaries
I have 2 Lists of dictionaries, example below: list one = [ {'day': '2021-09-05 00:00:00+02:00', 'airtime_total_for_day': '650.00', 'data_total_for_day': '0'}, {'day': '2021-09-16 00:00:00+02:00', 'airtime_total_for_day': '124.20', 'data_total_for_day': '20.00'}, ] list_two = [ {'day': '2021-09-10 00:00:00+02:00', 'data_bundle_total_for_day': '100.00'}, {'day': '2021-09-16 00:00:00+02:00', 'data_bundle_total_for_day': '50.00'}, {'day': '2021-09-18 00:00:00+02:00', 'data_bundle_total_for_day': '45.00'}, ] I would like to merge the two lists together and at the same time, merge data_total_for_day with data_bundle_total_for_day under the name data_total_for_day. Also, if data_total_for_day & data_bundle_total_for_day happen to fall on the same day which they do on the 2021-09-16, the values need to be added together e.g. data_total_for_day on the 2021-09-16 is: 20.00 data_bundle_total_for_day on the 2021-09-16 is: 50.00 So on that specific day, data_total_for_day needs to be: 70.00 I've struggled and all & any help with be greatly appreciated. Things I tried: https://www.codegrepper.com/code-examples/python/merge+two+list+of+dictionaries+python How to merge two list of dictionaries based on a value join two lists of dictionaries on a single key -
How to make users see other user products in Django [closed]
is it possible to create a link to a different user and see only that users items? I started up a software that allows users to post their products to a site were every user can see the product. The problem is, I want any user to click on that post and it takes the user to a page that has items only by that user -
How to switch to windows desktop via bash
I'm following this instruction https://stackoverflow.com/a/33993532/16250669, but I can't complete step 5, how do I get to C:\Users\kudla\Desktop\food_delivery via bash console if when I enter ls I get output: bash-4.3# ls bin docker-entrypoint.sh lib proc sbin tmp dev etc media root srv usr docker-entrypoint-initdb.d home mnt run sys var -
Open ports 8000 and 3000 on EC2 AWS instance
I am trying to run Django in port 8000 and React in port 3000 on an EC2 AWS instance. I first created the inbound rules for ports 8000 and 3000: Then, I start both Django and React on ip 0.0.0.0 sudo npm start sudo python manage.py runserver 0.0.0.0:8000 And I can check both ports are open and listening: However, when I try to reach the urls http://external_ip:8000/ or http://external_ip:3000/ Nothing is working. However, I can make Django server works if I change 8000 by 80. What am I doing wrong or missing? -
How can i determine number object show per page when using ListView pagination in django?
please how can i determine number of objects/page show(not number of pages) in Django when using ListView Pagination. that's my code in Views.py : from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post class PostList(ListView): model=Post context_object_name='all_post' ordering=['-created_at'] thank you! -
How to configure ID parameters in django_rest_framework APIView
My goal is to specify behavior that allows me to enter an ID into my URL. Currently, I am able to send GET, PUT, and PATCH requests to the URL 'localhost:8000/api/?id=#' where the hash represents any object id. I would like to update my code to understand that if I send a GET/PUT/PATCH request to 'localhost:8000/api/2' that I am looking for and object with id=2 my models.py class player(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) team = models.CharField(max_length=50) position = models.CharField(max_length=50) number = models.IntegerField() def __str__(self): return "{}, {}".format(self.first_name, self.last_name) my serializer.py class playerSerializer(serializers.ModelSerializer): class Meta: model = player fields = ['id', 'first_name', 'last_name', 'team', 'position', 'number'] my views.py from django.shortcuts import render from django.http import HttpResponse, response from django.shortcuts import get_object_or_404 from rest_framework import serializers from rest_framework. serializers import Serializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from main.models import player from .serializers import playerSerializer import json class playerList(APIView): serializer_class = playerSerializer throttle_scope = "main_app" def get_queryset(self, *args, **kwargs): players = player.objects.all() return players def get(self, request, *args, **kwargs): try: id = request.query_params["id"] if id != None: player_object = player.objects.get(id=id) serializer = playerSerializer(player_object) except: players = self.get_queryset() serializer = playerSerializer(players, many=True) return Response(serializer.data) def … -
Django - Comparing id of queryset with fetch object id
I am learning django with practicing. I have one object. It has id, name, lastname. Also, I have one queryset. It has same attributes id,name, lastname. All I want is comparing id's. I can compare ids if they both are equal but my problem is if they both are not equal django gives me error like matching query does not exist. because I use filter function. I want to do this operation if icformkeyinput.filter(id=v['Id']): if icformkeyinput.filter(id!=v['Id']): My problem is How can I use != operator? I want to do this because if there is unmatched id between icformkeyinput and v then add v to icformkeyinput. -
django many to many queryset
i have two models : 1----- class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50) picture = models.ImageField(blank=True, null=True , upload_to='profile' ) profession = models.ManyToManyField(Profession) 2----- class Profession(models.Model): profession = models.CharField(max_length=50) i want to display all the profession that i have and in the same time i want to display the number of accounts that they have this profession like this pic enter image description here