Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Displaying DynamoDB data in Django admin panel
I want to show data from DynamoDB on the Django admin panel page. I have tried PynamoDB to create the model and register it with the admin panel. I am facing the following two issues: Getting only attribute 'id' instead of all attributes from the DynamoDB table. I have confirmed this issue while fetching attribute_definitions from the DynamoDB table using boto3. attribute_definitions = table_name.attribute_definitions The second issue I am facing is that I get errors while registering the created Model(by using PynamoDB) with the admin panel. I get the issue "TypeError: 'MetaModel' object is not iterable" -
Django equivalent to PostgreSQL NOT EXISTS?
I have to make some in_bulk queries in my project, which uses Django and PostgreSQL. Right now, I'm using the following query to return the desired queryset: users_list = [user.id for user in get_cached_users(request.uuid)] users_dict = User.objects.filter(~Q(pk__in=users_list)).values() I've heard that using Q objects to create "not_in" queries is not as optimized as the PostgreSQL NOT EXISTS, but I never heard of an equivalent in Django. Do you guys know if there is a direct one? -
ERROR: Failed building wheel for dependency-injector, ERROR: Failed building wheel for pyduktape
Failed to get both dependency injector and pyduktape in Django project requirements.txt. It asked to install Visual C++ 14.0 or greater but it is already there. requirements.txt containts dependency-injector==3.15.6 and pyduktape==0.0.6 Tried with Python 3.7, pip 21.3.1, and pipenv version 2021.5.29 '''Building wheels for collected packages: dependency-injector, pyduktape Building wheel for dependency-injector (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\yasiru\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\yasi ru\AppData\Local\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b\setup.py'"'"'; file='"'"'C:\Users\yasiru\AppData\Loca l\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path .exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(co de, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\yasiru\AppData\Local\Temp\pip-wheel-23n96w5t' cwd: C:\Users\yasiru\AppData\Local\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b Complete output (13 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\errors.py -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector_init_.py -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\containers.pxd -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\providers.pxd -> build\lib.win-amd64-3.7\dependency_injector running build_ext building 'dependency_injector.containers' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for dependency-injector Running setup.py clean for dependency-injector Building wheel for pyduktape (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\yasiru\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\yasi ru\AppData\Local\Temp\pip-install-ai16fcys\pyduktape_d628ca64f5d1498c83b77edf959e9080\setup.py'"'"'; file='"'"'C:\Users\yasiru\AppData\Local\Temp\p ip-install-ai16fcys\pyduktape_d628ca64f5d1498c83b77edf959e9080\setup.py'"'"';f = … -
Vanilla Javascript: How to add multiple event listeners to buttons which are dynamically created with same class in django?
I am currently working on a project 4 for CS50w - Network. One of the tasks is to add an edit posts button (for editing the posts that logged in user (only owner) created), which does this async. Since for storing posts I'm using Django Models, I'm using Django (and it's template capabilities) to display all the posts to users too, and an edit button (if user is the creator of the post too). I'm displaying all the posts in a div. This means that the button for editing is also a part of this div... meaning that I can give it only single class or id for referencing, but then I don't know how to distinguish between them, and how to know which one (from which post) is clicked so that I can edit that post and not the first one on which the JS in DOM comes up... Anyways here's the code: HTML in Django: {% for post in posts %} <div class="post"> <a href="{% url 'users' post.user.username %}">{{ post.user }}</a> <p>{{ post.content }}</p> <p>{{ post.created }}</p> {% if user.is_authenticated and user == post.user %} <button class="edit_post_button">Edit Post</button> {% endif %} </div> <div class="edit_post" style="display: none;"> <a href="{% … -
Getting an error 500 when trying to upload images to heroku app
Having trouble deploying a project to heroku app. Images won't shop up and I get an error 500 code -
Can i use get, post, update, delete in a class?
I have a view like this in django: class MedicineOperation(View): def get(self, request, shop_id, *args, **kwargs): pass def post(self, request, shop_id, **args, **kwargs): pass def update(self, request, id, shop_id, *args, **kwargs): pass def delete(self, request, id, shop_id, *args, **kwargs): pass Can i use these method like this ? -
How to know portion of data received by server from client after every time interval?
so I am having this client-server setup for sending data (xlsx) from the client to Azure server. Is there any way by which I can understand what is the amount of data sent to the server after every say like 3-5 seconds? For example: I have a 100mb file which I am uploading to the server. So Can I know the amount of data uploaded already to the server after every 3 seconds? Like receiving something on the front-end similar to: 20mb... 30mb... 40mb... and so on. I am using Angular JS for front-end and sending the xlsx file to Azure cloud. The application is deployed using django web server on Azure cloud to which I am sending the data. I tried searching for some ideas but could find it. Please help. Thanks -
how to get the json from the output of a Rest API in my code?
I created a simple rest API with the help of flask, which takes in 2 numbers and returns the output- Now how do I get the json in the server, back to my python code? Like if I call it somehow with any device, I want to get the sum. Here's the code- from flask import Flask, jsonify app= Flask(__name__) @app.route("/") def hi(): return "hi" @app.route("/sum/<int:a>/<int:b>") def sum(a,b): result= {"Number": f"{a+b}"} return jsonify(result) if __name__=="__main__": app.run(debug= True) -
Model Query Django
I'm trying to query fields from another model in Django . I'm able to fetch the user information using the following method def student(self, *args, **kwargs): std_name = Attendance.objects.get(roll=self.roll) return std_name.name Now I need to find the student's assigned teacher from a different table, I need to fetch it only using the student name which I got using student() as I don't have any variable in my current table to reference it to fetch that information from the new table. def teacher(self, *args, **kwargs): teacher_name = staff.objects.get(student=self.student) return teacher_name.name But the above method is not working properly and is not populating the fields in my admin.py page . Can someone help me in fixing this issue -
django site shows error and manage.py server not running
I have deployed a python site from one server. python command shows me result. But when I am running it from IIS it shows below error: HTTP 500: The FastCGI process exceeded configured request timeout I tried to run the python manage.py runserver 8080 but it is showing nothing in CMD. Python v 2.7 FastCGI is created and handler mapping done. Please advise. -
Django Cannot resolve keyword 'slug' into field
I want to filter API by building name. models.py 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 from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request, slug): queryset = ReviewData.objects.all() serializer = ReviewSerializer(queryset, many=True) return Response(serializer.data) 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 from .serializers import BuildingSerializer from django.shortcuts import render, get_object_or_404 class BuildingInfoAPI(APIView): def get(self, request): queryset = BuildingData.objects.all() serializer = BuildingSerializer(queryset, many=True) return Response(serializer.data) class ReviewListAPI(APIView): def get(self, request, slug): queryset = ReviewData.objects.filter(slug=slug) 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/<str:slug>/', ReviewListAPI.as_view()) So my API should look like this api/buildingdata/A_building A_Building-review a A_Building-review b A_Building-review c api/buildingdata/B_building B_Building-review a B_Building-review b But this error occurs. Cannot resolve keyword 'slug' into field. Choices are: building_name, id, review_content, star_num … -
I keep getting this error: (1366, "Incorrect string value: '\\xF0\\x9F\\x8E\\xA5 W...' for column 'content' at row 1")
I've created a model called Post in my Django application which makes use of the Martor markdown editor to collect the post content as markdown syntax and translate/render them on my post template. I keep getting the 1366 error, I've already browsed through several solutions here on stackoverflow but nothing seems to be working... The most common solutions I have seen is altering the content table to change the character set to utf8mb4. When I ran the code: ALTER TABLE myapp_post CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; I get the error: ERROR 1071 (42000): Specified key was too long; max key length is 3072 bytes The only way around that was to enter the query: ALTER TABLE myapp_post CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin; Which work but I still get the same error. Here are my codes for the application # models.py class Post(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=180) title_slug = models.SlugField(max_length=900) date = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) content = MartorField() post_image = models.ImageField(upload_to='images/post_images/') objects = models.Manager() def get_absolute_url(self): return reverse('post', kwargs={'title_slug': self.title_slug}) def __str__(self): return ' by '.join(map(str, [self.title, self.author.user.username])) # forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ( 'title', 'content', 'post_image' … -
django return multiple repetetive objects in query set filter template file
I have implemented search bar functionality with autocomplete feature. All is good except the fact that in HTML serach results contain multiple the same object. For instance, when I put 2 in my searchbar I see 4 the same in my HTML file. What I want is to get unique objects. views.py @login_required def search_address_qa(request): query = request.GET.get('title') payload = [] if query: lookups = Q(title__icontains=query) address_objects = Article.objects.filter(lookups) address_objects_qa = QA.objects.filter(lookups) for address_object in address_objects or address_objects_qa: payload.append(address_object.title) return JsonResponse({'status':200, 'data': payload}) @login_required def search_articles(request): query = request.GET.get('q') article = Article.objects.filter(title__icontains=query) qa_list = QA.objects.filter(title__icontains=query) if query is not None: lookups = Q(title__icontains=query) | Q(tags__name__icontains=query) article = Article.objects.filter(lookups) qa_list = QA.objects.filter(lookups) context = { 'search_articles': article, 'query_name': query, 'qa_list': qa_list } return render(request, 'search/search_articles.html', context) search_view.html {% extends 'base.html' %} <title>{% block title %}search results{% endblock %}</title> {% block search %} {% include 'main/sidebar.html'%} <link rel="stylesheet" type="text/css" href="/static/search.css"> <div class="d-flex justify-content-end h-100 pb-4"> <div> {% if user.is_authenticated %} <form action="{% url 'search_articles' %}" method="get" id="search"> {% csrf_token %} <div class="searchbar " id="autocomplete"> <input name="q" type="text" placeholder="Search articles" class="search_input"> <a href="{% url 'search_articles' %}" class="search_icon"><i class="fas fa-search"></i></a> <ul class="autocomplete-result-list"></ul> </div> </form> {% endif %}</div> </div> {% endblock search %} {% block … -
should I learn django rest framework and why? [closed]
I am learning Django from code with mosh And there is an another course for learning Django rest framework Should I learn it ? why ? -
ForeignKey Not returning linked data as expected
I have 2 models Project and Fundamentals the fundamentals is linked via FK to Project I have a view that allows me to add data to the fundamentals table and also a view to update the fundamentals when data already exists. But when I try to retrieve the data i pass is the project_id in the request. But what seems to be happening is that if i have 5 projects and from project 5 i add fundamentals data the data in the table has an ID of 1 being that this is the first entry in the fundamentals table. but my project id is 5 being the 5th project If i then go to project 1 and add fundamentals it will return data from project 5. I hope this makes sense? I assume its the way i am requesting the data within these views: def fundamentals_view(request, project_id): check_exist = Fundamentals.objects.filter(project_name_id=project_id) if check_exist: return update_fundamentals_view(request, project_id) else: return add_fundamentals_view(request, project_id) @login_required def add_fundamentals_view(request, project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = FundamentalsForm(request.POST) if form.is_valid(): fundamental = form.save(commit=False) fundamental.project_name = project fundamental.save() return redirect('dashboard.html') else: form = FundamentalsForm() return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form}) def update_fundamentals_view(request, project_id): project … -
how to use email for login in django rest?
this is my serializer for login view when I'm trying to use email for login it returns None (it can't take users' email)! but with the username, everything is ok anyone can help me to find what is the problem? class LoginSerializer(serializers.Serializer): email = serializers.EmailField() password = serializers.CharField() def validate(self, data): user_email = authenticate(**data) print(user_email) print('this is serializer print') if user_email and user_email.is_active: return user_email raise serializers.ValidationError("Incorrect Credentials") this is my login view class LoginAPI(generics.GenericAPIView): serializer_class = LoginSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) print(serializer) serializer.is_valid(raise_exception=True) user = serializer.validated_data print(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) -
Transfer Ruby on rails to Python Django
In function Ruby on Rails i see this line: render :text => 'string' What does that mean in function Python Django? -
Django Many-to-many temporary
I do not want to add links, I want to make them temporary, how can I solve this problem? Direct assignment to the forward side of a many-to-many set is prohibited. Use user_permissions.set () instead. def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) if self.container_folder: # setattr(self, "user_permissions", self.container_folder.user_permissions) if permission := self.container_folder.user_permissions.all(): self.user_permissions = [x.pk for x in permission] Not work. -
static files not loading to django project
I have a project, where my partner worked on the Frontend without using any frameworks, just used js, html and css. I wanted to attach that front to the back by using Django. so here are my settting.py STATIC_ROOT = os.path.join('C:/Users/1224095/work/Backend/backend/static') STATIC_URL = '/static/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) and I added the {% load static %} in my html header. To not confuse you, I made a static directory named static, and inside I got my assets and plugins from the frontend, plus in every place, I added href= {% static 'path to the file' %} As a result, I am getting an error of 404, does anyone has an idea why ? here's an example of my html: <!doctype html> <html lang="en"> {% load static %} <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="{% static 'assets/plugins/simplebar/css/simplebar.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/perfect-scrollbar/css/perfect-scrollbar.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/metismenu/css/metisMenu.min.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/vectormap/jquery-jvectormap-2.0.2.css' %}" rel="stylesheet" /> <link href="{% static 'assets/plugins/highcharts/css/highcharts-white.css' %}" rel="stylesheet" /> -
Django+vue.js restart
djangosite api views.py models.py src main.js componenets assets my project looks like this. And also i'm using gunicorn. So, i use "sudo systemctl restart gunicorn" command when i want to reflect the code that i changed. But when i change the code of vue.js(component) it doesn't reflect. i can't find the reason does anyone know what the problem is? -
How to add password and username pop up for Django Swagger?
I am using drf-yasg library for the Django Swagger. I need to add the authentication on username and password level. There are three security schemes available in this library "basic", "apiKey" or "oauth2". Is there any way I can set my credentials for swagger in my django project settings and authenticate the swagger apidocs based on that? -
Fetch similar Django objects in one query if the objects have no direct relation
Let's say I have the following model: class Book(models.Model): class Meta: constraints = [ models.UniqueConstraint( fields=["name", "version"], name="%(app_label)s_%(class)s_unique_name_version", ) ] name = models.CharField(max_length=255) version = models.PositiveIntegerField() For each book, I need to get all higher versions: book_to_future_book_mappings = {} for book in Book.objects.all(): higher_versions = Book.objects.filter(name=name, version__gt=book.version).order_by("version") book_to_future_book_mappings[book] = list(higher_versions) The problem with this approach is that it doesn't scale well. It makes a separate query for every book, which is very slow if I have millions of books in my database. Is there anyway I can get all of this data in just a few queries? Perhaps I can use RawSQL if needed? Note my database is PostgreSQL. -
Parallel sequential celery tasks
I have a long list of queues which should be run sequentially but queues must run in parallel. Example: Tasks(Received by time): A1, B1, C1, D1, A2, C2, B2, A3, D2, D3, B4, A1, D4, C4 Queues: A=[A1,A2,A3,A4] , B=[B1, B2, B3, B4], C=[C1, C2, C3, C4] D=[D1, D2, D3, D4] So I managed to use apply_async(args=..., queue='queue_{}'.format((id % 4) + 1) and the routing looks fine. But there's one problem. I have about 64 threads of CPU and when I create 40 queues, tasks does not exactly run in parallel. queue 1 to 8 start to work in parallel but others wait and at a moment suddenly first 8 tasks freeze and 9 to 16 start to work. CPU load is about 40 to 50%. worker command example(40 times run using supervisord): celery -A bot worker -Q queue_19 -l ERROR --prefetch-multiplier=100 -c 1 As I mentioned before, there's no lack of resources because number of workers are about 70% of CPU threads. And the ram wouldn't fill up Celery broker backend used: Redis -
Django check block content is none or not
Can I code something like this? : // base.html {% block content %} {% if block content is None %} <p> default content </p> {% endif %} {% endblock content %} // child.html {% block content %} <p> child content </p> {% endblock content %} I know I just need to code something like this: // base.html {% block content %} {% endblock content %} // child.html {% block content %} {% if child.content %} <p> child content </p> {% else %} <p> default content </p> {% endif %} {% endblock content %} But I have so many child.html inherit from base.html.. So I just want to change the parent(base.html). Is it possible? -
Change Gunicorn Bin Path
I am using Ubuntu 20.04 and have manually installed Gunicorn with python setup.py install under the activation of virtual environment. However, when I typed which gunicorn, cmd showed /usr/bin/gunicorn. I want the system to use the gunicorn bin at /home/user/project_venv/bin/gunicorn, is there a way to change the path so that which gunicorn will point to the new path? Thanks in advance.