Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use wildcards for key/object to generate aws pre-signed url in django
My requirement is to upload multiple webm files(which are captured using webrtc) to s3 using one time generated pre-signed url. I have tried below code to generate pre-signed url and using postman to upload files def create_presigned_url(method_name,s3object,expiration=36000): try: response = s3_client.generate_presigned_post(S3Bucket, Key = "", Fields=None, Conditions = [ ["content-length-range", 100, 1000000000], ["starts-with", "$key", "/path-to-file/] ], ExpiresIn=expiration) except Exception as e: logging.error(e) return None return response Getting the below error when i tried from postman -
Image is not saving in folder. ( Also added :- " <form method="post" enctype="multipart/form-data"> " in templates )
new_blog.html {% block content %} <p>Add a New Blog:</p> <div class="container"> <form method="post" enctype="multipart/form-data"> <form action="{% url 'mains:new_blog' %}" method='post'> {% csrf_token %} <table> {{ form.as_p }} </table> <button type="submit">Save Changes</button> </form> </div> {% endblock content %} models.py class Blog(models.Model): blog_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) blog_title = models.CharField(max_length=500,default='') image = models.ImageField(upload_to='blogs',blank=True,null=True) forms.py class BlogForm(forms.ModelForm): class Meta: model = Post fields = ('blog_title','image',) I have tried everything but the image is not saving in the folder and not showing in the Local Host page. Please help me in this. I will really appreciate your Help. -
Python json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm trying to make a web api that accepts image and return location of faces in it. i copied the tutorial from https://www.pyimagesearch.com/2015/05/11/creating-a-face-detection-api-with-python-and-opencv-in-just-5-minutes/ at first it worked just fine, i was able to send image url from python project to django. However today, it no longer works, and giving me json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) error. I've deleted the code and re-copy it from the article, did not change anything, and it still giving me the exact same error. heres the django views.py code : FACE_DETECTOR_PATH = "{base_path}/cascades/haarcascade_frontalface_default.xml".format( base_path=os.path.abspath(os.path.dirname(__file__))) @csrf_exempt def detect(request): # initialize the data dictionary to be returned by the request data = {"success": "dipshit"} # check to see if this is a post request if request.method == "POST": # check to see if an image was uploaded if request.FILES.get("image", None) is not None: # grab the uploaded image image = _grab_image(stream=request.FILES["image"]) # otherwise, assume that a URL was passed in else: # grab the URL from the request url = request.POST.get("url", None) # if the URL is None, then return an error if url is None: data["error"] = "No URL provided." return JsonResponse(data) # load the image and convert image = _grab_image(url=url) # … -
Adding mysql database credentials to environment variable results in operational error
I'm deploying a django web app with Heroku. I have a MySql database. When my settings.py file contains hardcoded password and username for the mysql database, everything works. I decided to store my username and password in environment variables, and rewrote the settings.py file as shown below. DB_USER = os.environ.get('DB_USER') DB_PASS = os.environ.get('DB_PASSWORD') DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': BASE_DIR / 'db.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'NAME': 'pahlisch', 'USER': DB_USER, 'PASSWORD': DB_PASS, 'HOST': '123.mysql.database.azure.com', 'PORT': '3306', 'OPTIONS': {'sql_mode': 'STRICT_ALL_TABLES'} } } Next, I added my local environment variables to Heroku. When I attempt to load the site, I get the following message. (1045, "Access denied for user ''mattrw2'@'44.167.157.221' (using password: NO)") I don't understand what is wrong. -
Django: File upload and save using Ajax
I'm not sure if somehow the directory is wrong or there's just some kind of common mistake in my code, but I just am not able to save my uploaded file to a folder, or more specifically, the media folder as demonstrated in a lot of examples. I'm just taking a text field and the file and saving it in the DB using Ajax, and it works too, except that whatever file I'm selecting, it's not getting saved in the media folder even if I create one manually nor is it creating one on its own either. I can get this to work without Ajax but not with it. Maybe it's something related to how I'm sending and handling data over Ajax, but I've gone through tons of forums to try and fix it but no results so far. I've double checked everything else such as the settings.py config and the libraries that I've imported, everything looks to be in order. I'm sharing the code below. index.html <body> <div class="container-fluid"> <div class="col-md-4"> <form id="data" enctype="multipart/form-data"> <label for="docn"> <input type="text" id="docn" placeholder="Please enter document name"> </label> <label for="docc"> <input type="file" id="doc" name="docu"> </label> <button type="button" onclick="enterdata()">Submit</button> </form> </div> </div> <script> function … -
django, detail: Authentication credentials were not provided. (CSRFToken)
] ------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export const CSRFToken = () => { const csrftoken = getCookie('csrftoken'); console.log('token : ' + csrftoken); return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getplayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value) return ajax.get('/api/player/', {headers: {'X-CSRFToken': state.CSRFToken.props.value }} ).pipe( map(response => { const player = response.response; return getplayerSuccess({player}); }), catchError(error => of({ type: GET_player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django(python) ------ view.py class Listplayer(generics.ListCreateAPIView): permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer I can not speak English very well. hope you understand. I want to use csrftoken, but details: no authentication credentials were provided. An error occurs. What is the reason? If you know, let me … -
Django Search Implementation, conditional routing
I am trying to implement basic search functionality with Django. If exact search query page exists, display that page If there is a page title that contains what was queried, show results of all If neither, display a message stating no results found I'm just learning, so I tried functional views and class based views. I've spent a really long time on documentation/videos/textbooks and don't see how to get the intended behavior out of class-based view. I understand collecting object_list and getting query_set, but how do you then route to those three different conditions. I tried overriding dispatch() and as_views() method to no avail. Tried with a Django form class and without. For some reason, the functional view keeps executing the first try statement instead of throwing a DoesNotExist exception when the exact match isn't found. So it shows the entry page instead of the search results page. It seems like the request.GET is None type no matter what, as when I try to print nothing shows up. urls.py from re import search from django.urls import path from . import views from .views import IndexPageView, SearchView app_name = "wiki" urlpatterns = [ # ex: /wiki/ path("", views.index, name="index"), # path("", … -
How to customized this [Authentication credentials were not provided] error message in django rest framework
When I don't pass the header in postman then DRF give me this msg. {"detail": "Authentication credentials were not provided."} But I want custom message like. { "status": False, "message": "Authentication credentials were not provided.", "data": {} } -
Post matching query does not exist
urls.py path('posts/',views.posts,name='posts'), path('<id>',views.detail_view,name='detail_view'), views.py def detail_view(request,id): context = {} context["data"] = Post.objects.get(id=id) return render(request, 'mains/show_more.html', context ) def posts(request): posts = Post.objects.all().order_by('-date_added') context = {'posts':posts} return render(request, 'mains/post.html', context) post.html {% block content %} {% for topic in posts %} <a>{{ topic.description}}</a> <a href="{% url 'mains:detail_view' topic.post_owner.id %}">Show More</a><br> <br> {% empty %} No yet.</li> {% endfor %} </ul> <a href="{% url 'mains:new_post' %}">Add a New Diary</a> {% endblock content %} show_more.html {% block content %} {{ data.post_title }} {% endblock content %} Post matching query does not exist. This error is raising when i click on show_more in posts page. Please Help me in this. I will really appreciate your Help. -
Best way for creating websocket in django
I want to implement a WebSocket. I use the Django rest framework. I tried the channels. Does the socket keep alive for a long time in the channel? What is the best way to do this in Django? -
403 Permission Denied message Django
When I go to update my contact object, I receive a 403 Permission Denied Message. I am trying to get my application to block users that didn’t author the contact to block them out but at the moment it's blocking everyone. When I first created the Contact Book model, it only had the [‘first name, last name, email, phone number, and date_added ] fields. Once I realized that I needed to add a created_by field I inserted and migrated it to my database. The two solutions I have tried include are: Tried adding both null= True and blank = True to my created_by field in my model as an argument for ForeignKey. I have set the default argument for my ForeignKey to an instance of the User. So with that being said below is my code Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib import messages from django.views import generic from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin ) from .models import ContactBook from .forms import ContactForm class ContactUpdateView(LoginRequiredMixin, UserPassesTestMixin, generic.UpdateView): model = ContactBook fields = ['firstname', 'lastname', 'email', 'phone_number', 'occupation'] template_name = 'book/contact_form.html' def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) def test_func(self): contact = self.get_object() if … -
Django - Updated multiple models in single table form
Is there a way to update three different models in a single row in a table? The three models share the same foreign key to another model. -
Passing variable to permission class in DRF gives an error
I'm trying to use the following permission class in many apps in the project, the only change needed is the model class that user data is checked from. Permission class: class IsAuthorOrForbidden(permissions.BasePermission): """ Check if the requesting user the author or not """ def __init__(self, modelClass): self.modelClass = modelClass def has_permission(self, request, view): # get the needed model instance or 404 if not available instance = get_object_or_404(self.modelClass, pk=view.kwargs['pk']) # Check if the requesting user is the author if instance.user == request.user: return True return False The permission class in the view class: class TextNoteGenerateShareKeyAPIView(generics.UpdateAPIView): """ Generate a new text note share key """ authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated, IsAuthorOrForbidden(modelClass=TextNote)) ... When I run the tests, i get this error: return [permission() for permission in self.permission_classes] TypeError: 'IsAuthorOrForbidden' object is not callable Is it possible to do it like this or should I write this permission class in every app in my project? -
Preview and cut a portion of selected video with javascript or jquery before uploading it to server
I am working on a video streaming site like youtube but i want my users to upload videos that are less than 10 minutes. How do i let my users select a specific portion of the video they want to upload when they select a video that is longer than 10 minutes? It's a Django project and I was looking for a Javascript or jquery plugin to do this. Any help would be really appreaciated. Thanks. -
My JavaScript doesn't run when the html is in a form
HTML I have some simple html input here and I would like to put it in a POST form <form method="POST"> {% csrf_token %} <input type="text" id="myTextInputID" placeholder=" Your amazon URL"> </form> JAVASCRIPT function search(){ var inputValue = document.getElementById("myTextInputID").value; } document.getElementById("myTextInputID").addEventListener("keyup", function(event) { if (event.keyCode === 13) { event.preventDefault(); var input = document.getElementById("myTextInputID").value; document.getElementById(search()); var error = document.getElementById("error") if (input.includes("https://www.amazon.co.uk/")){ error.style.display = "none"; }else{ error.style.display = "block"; setTimeout(function(){error.style.display = "none";} ,2000) } } }); function togglePopup(){ document.getElementById("popupe-1").classList.toggle("active"); } And I have my if function here when I don't have my user input as a post method it works perfectly fine, but when I add the post method the page just reloads each time and doesn't run my javascript function -
Using formsets for my fileupload does not work when doing an update class based view only on create in django
I have used as many examples online as I could cobble together in an attempt to get my two simple models to have the ability to do an inline formset allowing me to add many files to a technial drawing. This is not working, I can only add one file for the Create and the update only updates the Technical_Entry model, not a file...which in of itself acts funny. The UI ona create shows one spot to add a file, then save the entire record and its child record. That works. The update, the UI shows the file that was saved earlier..(great!) but then has two more 'choose file' slots (random?) and adding a file to those does nothing when the save is clicked. It doesn't remove the file previously added in the create, but it also does not save the new file added to the now three slots (one used, two free). So update does not work for the files for some reason. class Technical_Entry(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) ema = models.ForeignKey(EMA, on_delete=models.CASCADE) system = models.ForeignKey('System', on_delete=models.CASCADE) # are SYSTEMS RELATED TO SUBSYSTEMS OR JUST TWO GROUPS? sub_system = models.ForeignKey(SubSystem, on_delete=models.CASCADE) drawing_number = models.CharField(max_length=200) drawing_title = models.CharField(max_length=255) engineer = … -
Formatter black is not working on my VSCode...but why?
I have started using Python and Django and I am very new in this field. And this is my first time to ask a question here...I do apologise in advance if there is a known solution to this issue... When I installed and set VSCode formatter 'black' (after setting linter as flake8), the tutorial video tutor's side shows up pop-up like 'formatter autopep8 is not installed. install?'. So what I did was... manually input 'pipenv install flack --dev --pre' on terminal. manually input "python.formatting.provider": "black", to 'settings.json' on '.vscode' folder. Setting(VSCode) -> flake8, Python > Linting: Flake8 Enabled (Also modified in: workspace), (ticked the box) Whether to lint Python files using flake8 The bottom code is from settings.json (on vscode folder). { "python.linting.pylintEnabled": false, "python.linting.flake8Enabled": true, "python.linting.enabled": true, "python.formatting.provider": "black", # input manually "python.linting.flake8Args": ["--max-line-length=88"] # input manually } I found a 'black formatter' document. https://github.com/psf/black & it stated... python -m black {source_file_or_directory} & I get the following error message. Usage: __main__.py [OPTIONS] [SRC]... Try '__main__.py -h' for help. Error: Invalid value for '[SRC]...': Path '{source_file_or_directory}' does not exist. Yes, honestly, I am not sure which source_file_or_directory I should set...but above all now I am afraid whether I am on … -
Django - after login, redirect user to the page he/she was on
I am currently working on a Django application and I am currently have an issue. The issue is that when the user is not logged in, and on the blog post page(In this case "post_detail") and hit the like button, the user is directed to the login page. However, once the user is signed in, the user is redirected back to the home page(In this case "blog_home" which shows a list view of all the blog posts). Now, that is not what I wanted. I wanted the user to go back to the blog post page("post_detail" page). After researching the problem, I realized it had to do with the LOGIN_REDIRECT_URL. However, after trying to fix the issue, I am having a hard time to redirect the user to the specific page. Is there any ideas on how I can make it work? Any input is truly appreciated. Settings.py: LOGIN_REDIRECT_URL = '/redirect' views.py(blog): def wherenext(request): if request.user: return HttpResponseRedirect(reverse('post_detail')) else: return HttpResponseRedirect(reverse('blog_home')) ... @login_required(redirect_field_name="post") def LikeView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) liked = False if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) ... class BlogDetailView(DetailView): model = Post template_name = 'blog/post_detail.html' ... def get_context_data(self, *args, … -
add a custom id parameter in the curl command
I want to let my users include a custom "id" parameter in the curl command. I can't seem to get this to work for some reason. Here is the current curl command. curl -X POST -H "Content-Type: application/json" -d @/Users/name/desktop/test.json http://127.0.0.1:8000 After I pass this parameter to my curl command, how would I access the passed in value in my django function. For reference, this is what my django function header looks like: def train_view(request): -
Passing a list through <a href = "{% url 'list_item' %}"> in django
I have to add links to list items listed in the main body of the page that redirect the user to the page that the list items represent. The list items are fetched from a function in views.py which fetches the list items from another file named util.py. However, I don't understand how to add those hyperlinks while iterating through the list items i.e the part I wrote as <a href = "{% url '....' %}">. This is the code for index.html, the page where the list items along with the hyperlinks are to be shown: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href = "{% url '....' %}">{{ entry }}</a></li> {% endfor %} </ul> {% endblock %} This is the function that gets the list from util.py and stores it in a list named entries: from django.shortcuts import render from . import util def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) This is the orginal function from util.py that returns the list to the index function in views.py. def list_entries(): """ Returns a list of all names of encyclopedia … -
Where to put code that converts from an external representation to a django model?
I have a code organization question: In my django application, I frequently move back and forth between pandas dataframes and django models. I currently use the DataFrameManager from django-pandas to go from django model to dataframe by using Foo.objects.to_dataframe(), but to do the reverse I just have a bunch of stand-alone functions in a module and it's starting to get a little messy. I think I would like that code to live with the model. Is there an established convention for where object conversion code like this should go? Similar to how Managers work for queries? -
Test result in django response is 302 instead of 200 or 404
Im building survey app using this repository but i already made few changes, the web is running but it keep using 302 instead of 200 or 404 on POST request evertime i run test from test_survey_detail.py it always gives me the same fail messages FAIL: test_when_publication_date_is_in_future_survey_is_not_visible_via_post (survey.tests.views.test_survey_detail.TestSurveyDetail) when publish_date is in the future the survey should be hidden for post requests ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/yourname/practice/python/django_projects/django_survey/survey/tests/views/test_survey_detail.py", line 101, in test_when_publication_date_is_in_future_survey_is_not_visible_via_post self.assertEqual(response.status_code, 404) AssertionError: 302 != 404 here is the test_survey_detail.py import logging from django.conf import settings from django.urls.base import reverse from survey.models import Answer, Response from survey.tests import BaseTest LOGGER = logging.getLogger(__name__) class TestSurveyDetail(BaseTest): def test_survey_result(self): self.login() response = self.client.get(reverse("survey-detail", args=(2,))) self.assertEqual(response.status_code, 200) response = self.client.get(reverse("survey-detail", args=(4,))) self.assertEqual(response.status_code, 404) response = self.client.get(reverse("survey-detail", args=(1,))) self.assertEqual(response.status_code, 200) def test_multipage_survey(self): """ Checks that multipage survey is working. """ self.login() response = self.client.post(reverse("survey-detail", args=(5,)), data={"question_11": 42}) self.assertEqual(response.status_code, 302) response_saved = Response.objects.filter(user__username=settings.DEBUG_ADMIN_NAME, survey__id=5) self.assertEqual(len(response_saved.all()), 0) self.assertRedirects(response, reverse("survey-detail-step", args=(5, 1))) response = self.client.post(reverse("survey-detail-step", args=(5, 1)), data={"question_12": "yes"}) self.assertEqual(response.status_code, 302) response_saved = Response.objects.filter(user__username=settings.DEBUG_ADMIN_NAME, survey__id=5) self.assertEqual(len(response_saved.all()), 1) self.assertRedirects( response, reverse("survey-confirmation", args=(response_saved[0].interview_uuid,)), ) def test_multipage_survey_edit(self): """ Checks that a multipage survey can be rightfully edited. """ self.login() # first creates the initial response response = self.client.post(reverse("survey-detail", … -
Differenciate Logging Messages for Django Error Report
I have been trying to figure out a way to distinguish between loggings from the production server or development server or local server. Right now, I have python-telegram-handler 2.2, which sends logs to a Telegram group chat via a bot. Below is the LOGGING part of the base.py in the settings directory. The codes are exactly the same in all of those servers because localhost code gets merged to the development branch(which is responsible for the development server), and when the development branch is ready, it gets merged to the master branch, which is responsible for the production server. Is there a way to tweak the settings so that the telegram log tells us which server has the error? Thanks a lot! settings/base.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, }, 'formatters': { 'simple_trace': { 'format': '%(asctime)s,%(msecs)d %(levelname)-8s %(message)s', } }, 'handlers': { 'telegram': { 'class': 'telegram_handler.TelegramHandler', 'token': '1489551033:AAHbIvspcVR5zcslrbrJ9qNK2yZ1at0yIMA', 'chat_id': '-429967971', 'formatter': 'simple_trace' } }, 'loggers': { '': { 'handlers': ['telegram'], 'level': 'INFO', 'propagate': True, }, }, } And I also have a middleware that is responsible for sending logs of request body whenever the responses are 400 or 500. api/custommiddleware.py import json … -
Django Admin: UI glitch
I'm getting a very weird visual glitch in my admin dashboard. Essentially, each model registered has tons of "+Add" buttons all the way to the bottom of the page, where we hardly see the table. If I shrink the window down to 1/3 its size, then the glitch disappears. Seems like a media query-related issue of some sort. Has anyone ever seen this? Any idea what causes this? Full screen Shrink window 1/3 screen -
How to add a model field to a django model
I have an app where I have a bunch of users and each user has a watchlist of stocks. I know I can use a manytomany relationship to model this since each user will have multiple stocks and vice versa, but it gets really messy on the admin (since I have a list of stocks and I have to click on each one to find out which user(s) it belongs to). class Stocks(models.Model): user = models.ManyToManyField(User) name = models.CharField(max_length = 30) def __str__(self): return self.name I am wondering if there is any way I can set it up so that when I click on an individual user, I can see all the stocks they have on their watchlist. I was initially thinking there might be a way to add a field in the user model that contains all of their stocks.