Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Python wasn't found, but I know that python is installed and in the path
I'm trying to get a django project up and running (my first). I keep getting this error when trying to run manage.py: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I did some reading on other stack overflow threads and it basically said that python wasn't in my path. So I checked and it's there. I did: py --version and got Python 3.8.1 I also did just py and got the python terminal. Anyways, I have no idea why this is happening. Any ideas? -
Django ValueError at / required parameter name not set
I am currently using my server via SSH, and I get this Django-related error when I try to run my server in Ubuntu. Value Error: https://i.stack.imgur.com/d1K6q.png Traceback Error 1:Traceback Traceback Error 2:Traceback -
Template doesnot exist at login/index
I was programming a login system but i don't know why i'm getting this error.The routes are ok. look at the circles -
Cannot connect to django rest api with react native network error
I'm new with django and react native. I try to make an app that sends data to django back end with axios but I have a network error. I tried to change my localhost ip in 192.168.xxx but nothing change. So I don't understand hy I don't have any request. Here is my code: Django : CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8081', 'http://localhost:19006', 'http://localhost:19002', 'http://192.168.101.6:19000', ) Axios: import axios from "axios"; export default axios.create({ baseURL: "http://192.168.101.6:8080/api", headers: { "Content-type": "application/json" } }); requests : import http from "../http-common"; const getAll = () => { return http.get("/tutorials"); }; const get = id => { return http.get(`/tutorials/${id}`); }; const create = data => { return http.post("/tutorials", data); }; -
Django set timezone into Postgres SQL view date
In my Django app and Postgress: I'ved got a view, model, orm code as below. I want to be able to set 'Asia/Tokyo' timezone as parameter so that in the django ORM code it can be configured dynamically. For example, on different occassion, it is set to 'America/Chicago' or 'Australia/Sydney'. How can I modify the sql view, model and orm to accept timezone parameters postgres sql view DROP VIEW IF EXISTS view_attendance_dates; CREATE OR replace view view_dates as <-- the name of the view SELECT created_at::date AT TIME ZONE 'Asia/Tokyo' as created_date, employee_id FROM mydb_attendance model.py class DateAttendanceModel(models.Model): created_date = models.DateField() employee = models.ForeignKey(Employee,on_delete=models.DO_NOTHING,null=True) class Meta: managed = False db_table = "view_attendance_dates" <-- here is where I put the view Django ORM (is it possible to put in the timezone somewhere here ? 'America/Chicago' or 'Australia/Sydney') from railercomapp.utils import convert_to_date filterdate_start = convert_to_date('2020-11-18') filterdate_end = convert_to_date(2020-11-30) employee_attendance_reports = DateAttendanceModel.objects.filter( Q(created_date__range=(filterdate_start,filterdate_end)) ) -
I can submit data but won't go to new page -or- go to new page and data doesn't get saved in Django
So the title kind of says it all. I have a form based on a model. The goal is to have the specific data entered, user presses submit, data gets saved to a Postgresql DB, user sees complete.html. However this is not the case. I can either get the data to save without changing pages, or the page will change but the data will not submit. I have put details on the specifics of I tried below. urls.py from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index-page'), path('feedback/', views.feedback_view, name = 'feedback'), path('complete/', views.complete, name = 'complete') ] models.py from django.db import models from django.utils import timezone from django.core.validators import RegexValidator class feedback(models.Model): RECENT_GROUND = [ ('PVT','Private'), ('INS','Instrument'), ('COM','Commercial'), ('MEL','Multi-Engine'), ] RATING = [ (1,'Poor'), (2,'Below Average'), (3,'Average'), (4,'Above Average'), (5,'Excellent'), ] id_field = models.AutoField(primary_key = True, serialize = True) added = models.DateTimeField(default = timezone.now) spid = models.CharField(primary_key = False, max_length=5, verbose_name = 'Enter the students FSA ID number:') recent_ground = models.CharField(max_length = 3, choices = RECENT_GROUND, verbose_name = 'Most recently completed ground school:') question1 = models.IntegerField(choices = RATING, verbose_name = 'This is question 1') question2 = models.IntegerField(choices = RATING, verbose_name = 'This is … -
How to fix heroku connection error when deploying my Django app
could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The following error is what I get when I open up my site on heroku. I'm not sure what is going on, but my settings are as follows... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('DB_NAME'), } } pushing to heroku master works fine but just when opening up my app heroku open I get that error and I am not sure how to fix it. -
Get a 'Session matching query does not exist' error when users auto login via chrome
Error page The website gets a 'Session matching query does not exist' error when users auto login via chrome. The error happens in the middleware that makes sure users can't login in different browsers. from django.contrib.sessions.models import Session class OneSessionPerUser: def __init__(self, get_response): self.get_response = get_response # One-time configuration and initialization. def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. if request.user.is_authenticated: current_session_key = request.user.logged_in_user.session_key if current_session_key and current_session_key != request.session.session_key: Session.objects.get(session_key=current_session_key).delete() request.user.logged_in_user.session_key = request.session.session_key request.user.logged_in_user.save() response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response Does anybody know what might be the problem here or does anybody know how to disable the chrome auto login? -
Django TemplateDoesnotExist / blog/home.html, blog/post_list.html
So I am trying to have my server uploaded using LinuxNode and I been following Corey Schaffer's tutorial. The server will run, but it produces an error. It runs when I am using the python3 manage.py runserver command in my regular linux terminal environment. When I ssh into my server and have it run, it comes up with an error. : global _loop if _loop is None: _loop = asyncio.new_event_loop() threading.Thread(target=_loop.run_forever, daemon=True).start() _loop.call_soon_threadsafe(asyncio.create_task, coro) test function class TestEmails(TestCase): def setUp(self): create_mock_data(self) def test_send_mail(self): fire_and_forget(send_mail(self.order)) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].to, [TEST_EMAIL]) self.assertEqual(mail.outbox[1].to, [DEFAULT_EMAIL]) is it possible to wait for the thread? furthermore when the test Destroying test database Im getting following error: Task exception was never retrieved sqlite3.OperationalError: database table is locked: In the send_mail its retrieving data from database...