Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch warnings from a django mysql query?
I'm trying to get a list of warnings after a mySQL query, using Django admin. I can see from the documentation here that it's possible to record warnings by setting connection.get_warnings to true. But I can't find anything explaining how to read those warnings. I do not want to throw an exception - I am deleting items from the database using a DELETE IGNORE statement and want to get all instances of deletions that failed (due to external keys, etc.) I've tried returning the result of the execute function itself (just gave me a number) and calling fetchwarnings() on the cursor (threw a "Cursor object has no attribute fetchwarnings" error). I'm still new to both Python and Django. I'm looking through all the documentation I can find but can't find anything that works. from django.db import connection query = "{query here}" connection.get_warnings = True with connection.cursor() as cursor: cursor.execute(query) <-- Returns a number return cursor.fetchwarnings() <-- Throws an error -
django logdna not working. server getting stuck
import logging from logdna import LogDNAHandler LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s]" + "%(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'color': { '()': 'colorlog.ColoredFormatter', 'format': '%(log_color)s%(asctime)s %(levelname)-8s %(name)s %(module)s %(pathname)s:%(lineno)s%(reset)s \n\r\t %(message)s', 'datefmt': "%d/%b/%Y %H:%M:%S", 'log_colors': { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', } } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'color' }, 'logdna': { 'level': logging.DEBUG, 'class': 'logdna.LogDNAHandler', 'key': "f47ec154e993efce66ed784ad7g3g76b8cb91", 'options': { # 'app': '<app name>', # 'env': "alpha", 'index_meta': True, }, }, }, 'loggers': { '': { 'level': logging.DEBUG, 'handlers': ['logdna'], 'propagate': True, }, } } I am using above code for django logging using logdna. But when i am running django server it is getting stuck . what can be the reason ? Am i doing it correctly ? Please take a look I am following https://github.com/logdna/python doc for implementation. django with logdna for logging -
Sanitizing SQL input in Django for PostgreSQL
I know that there are tools how to prevent sql injection especially with psycopg2 and how to work with them, but i have an other use case. The query should not be directly executed in PostgreSQL, but in InfluxDB as a part of join between metadata from PostgreSQL and measurements from InfluxDB that is done with the sql package from it. So i need to produce a string part of a bigger query that is totally safe, especially in the filter part of the query where a LIKE part is entered. I think this is possible by acquiring the the cursor object of the connection from the connection pool and then use mogrify() to get the safe sql after binding, but this approach seems complex and unnecessary as i don't need to execute it in PostgreSQL directly. Is there a tool or library in Python that can check/adapt/escape/sanitize the query as a string, or bind parameters in a safe way? -
JQuery and Vuejs APIs not passing nor retrieving data to database Django
I had working been on a web app using Django and had to take a 3-month break. I decided to continue and suddenly all my jquery and vuejs code is not working although it had been perfectly working 3-months ago. This is my base.html <head> <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet"> <!-- Vue Js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- JQuery script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> urls.py from conversation.api import api_add_message urlpatterns = [ path('api/add_message/', api_add_message, name='api_add_message'), ] api.py import json from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .models import ConversationMessage @login_required def api_add_message(request): data = json.loads(request.body) content = data['content'] conversation_id = data['conversation_id'] message = ConversationMessage.objects.create(conversation_id=conversation_id, content=content, created_by=request.user) template.html <li class="chat-left" v-for="message in messages"> <div class="chat-avatar"> <img :src="message.image"alt="Retail Admin"> <div class="chat-name">[[ message.user ]]</div> </div> <div class="chat-text">[[ message.content ]]</div> <div class="chat-hour">[[ message.user ]]</div> </li> And this is my script in the template {% block script %} <script> var conversationapp = new Vue({ el: '#conversationapp', delimiters: ['[[', ']]'], data () { return { messages: [], content: '', user: '{{ request.user.username }}', created_at: 'Now', image: '{% if request.user.profile.image %}{{ request.user.profile.image.url }}{% endif %}' } }, methods: { submitMessage() { if (this.content.length > 0) { var message = { 'content': this.content, 'user': this.user, 'created_at': this.created_at, 'image': this.image, … -
How do you combine two querysets into one queryset(not a list) in django?
I want to simply combine two querysets from different models into one queryset (and not a list as shown in other stackoverflow questions!). For example, here are two querysets: a = Modelone.objects.all() b = Modeltwo.objects.filter(number__gte=4) Then, I want a queryset c that combines both a and b. Thank you, and please leave me any questions you have. -
hello, why does my template Django not want to display the results of my review form?
I cannot understand why the result of my review form is not showing in the template, even though my ticket form is working fine. However, I have linked the 2 models with a foreign key. Then in the template I added "ticket.id". Finally, the objective of this app is to limit the review to one person. Thank you in advance for your help. My models: class Ticket(models.Model): title = models.CharField(max_length=128) content = models.TextField(max_length=2048, blank=True, null=True) image = models.ImageField(null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.title class Review(models.Model): ticket = models.ForeignKey(Ticket, related_name="reviews" ,on_delete=models.CASCADE) rating = models.PositiveIntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) headline = models.CharField(max_length=128) body = models.TextField(max_length=8192, blank=True, null=True) time_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.ticket.title My forms : class TicketForm(forms.ModelForm): class Meta: model = models.Ticket fields = ['title', 'content','image'] class ReviewForm(forms.ModelForm): class Meta: model = models.Review fields = ['rating','headline','body'] My view : @login_required def review(request, ticket_id): ticket = get_object_or_404(models.Ticket, id=ticket_id) review_form = forms.ReviewForm(instance=ticket) if request.method == 'POST': review_form = forms.ReviewForm(request.POST, instance=ticket) if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.save() return redirect('home') return render(request, 'flux/create_review_post.html', context={'review_form': review_form}) My urls: path('home/', flux.views.home, name='home'), path('ticket/create/', flux.views.ticket, name='ticket_create'), path('flux/<int:ticket_id>/', flux.views.view_ticket, name='view_ticket'), path('<int:ticket_id>/review/create/', flux.views.review, name='review_create'), My template review … -
How to make media file's URL restricted to the unauthenticated users in Django?
I am going to build a Django storage application where users can upload files to the server. Users also can download their files from the server. To download the file, the server returns the URL of the media file to the user. I added a permission class, if the user is authenticated & owner of the file then return the URL of the media file, otherwise return 404. But there is a problem, if any unauthenticated user found the URL of the media file from the history of the browser, then he can download/access the file. How can I handle this case? -
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.