Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
403 Forbidden with Django Permission error
I cannot seem to have a user create a post without having a 403 error display after creating an account, would anyone be willing to take a look at the code and see if they can tell me why I the user is not automatically placed into the default group when creating account from django.shortcuts import render, redirect from .forms import RegisterForm, PostForm from django.contrib.auth.decorators import login_required, permission_required from django.contrib.auth import login, logout, authenticate from django.contrib.auth.models import User, Group from .models import Post @login_required(login_url="/login") def home(request): posts = Post.objects.all() if request.method == "POST": post_id = request.POST.get("post-id") user_id = request.POST.get("user-id") if post_id: post = Post.objects.filter(id=post_id).first() if post and (post.author == request.user or request.user.has_perm("main.delete_post")): post.delete() elif user_id: user = User.objects.filter(id=user_id).first() if user and request.user.is_staff: try: group = Group.objects.get(name='default') group.user_set.add(user) group.user_set.remove(user) except: pass try: group = Group.objects.get(name='mod') group.user_set.remove(user) except: pass return render(request, 'main/home.html', {"posts": posts}) @login_required(login_url="/login") @permission_required("main.add_post", login_url="/login", raise_exception=True) def create_post(request): if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect("/home") else: form = PostForm() return render(request, 'main/create_post.html', {"form": form}) def sign_up(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return redirect('/home') else: form = RegisterForm() return render(request, 'registration/sign_up.html', … -
Django UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 5: invalid continuation byte
for the first time I am asking for help because I have not seen such a problem before, I rummaged through Google and did not find an answer, although other people had similar situations, but their solutions did not fit( Username in english path too ) Problem: first django project, manage.py runserver have error. Performing system checks... System check identified no issues (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. August 04, 2022 - 01:06:46 Django version 4.1, using settings 'base.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\pthn\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\pthn\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\pthn\lib\site-packages\django\utils\autoreload.py", line 64, in wrapp er fn(*args, **kwargs) File "C:\pthn\lib\site-packages\django\core\management\commands\runserver.py", line 158, in inner_run run( File "C:\pthn\lib\site-packages\django\core\servers\basehttp.py", line 236, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "C:\pthn\lib\site-packages\django\core\servers\basehttp.py", line 76, in __init__ super().__init__(*args, **kwargs) File "C:\pthn\lib\socketserver.py", line 452, in __init__ self.server_bind() File "C:\pthn\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "C:\pthn\lib\http\server.py", line 140, in server_bind self.server_name = socket.getfqdn(host) File "C:\pthn\lib\socket.py", line 756, … -
Django app fails to load in iframe despite using CSP_FRAME_ANCESTORS
I'm looking to load a Django site of my design into an iframe. For this, I added the following lines in my Django settings.py file: MIDDLEWARE = [ ... 'csp.middleware.CSPMiddleware', ... ] . . . CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') So that I can load my site from any address of my localhost. However, when I load my site at the following url:http://localhost:3000/searchEngine I get in the devtools inspector the following error: Refused to frame 'https://gkwhelps.herokuapp.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self' localhost:*". I tried to find the solution on this stack overflow question, on this blog, also on another blog on the internet and again on this blog and tried to replace CSP_FRAME_ANCESTORS by CSP_FRAME_SRC like this: CSP_FRAME_SRC = ["'self'", 'localhost:*'] #instead of CSP_FRAME_ANCESTORS = ("'self'", 'localhost:*') but that didn't solve the problem and the header was even ignored. Still, I would like to be able to load my site in an iframe from any port on my localhost. -
How create table (with values) in database from .sql or .txt file which I will take from user via django website
I have a form with input tag type=field, What I want is when user upload .txt or .sql file. My django view read that file and execute whole file in my already connected database, and create all tables and values which user's file have. I tried few things but I am facing errors like I read file like this var2 = request.FILES['myfile'].read().splitlines() But when I print var2 I notice that there are many single quotes ('), \r, \s, \n, \t in var2. Can any pro guy guide me what to do? Thank You In Advance. -
Forbidden (CSRF token missing.): /ckeditorupload/ in django?
When i try to upload an image in the admin panel of django, i get this Forbidden (CSRF token missing.): /ckeditorupload/ i have this result in my console. here my model from django.db import models from django.contrib.auth.models import User from ckeditor.fields import RichTextField from ckeditor_uploader.fields import RichTextUploadingField # Create your models here. STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) #content = RichTextField(blank=True, null=True) image = RichTextUploadingField() #image = models.ImageField(upload_to='featured_image/%Y/%m/%d/') # created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title my views from django.views import generic from .models import Post from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt @method_decorator(csrf_exempt, name='dispatch') class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' I tried to exempt the CSRF but i get same issues, & when i delete the middlewareCsrf it's dont works too, since i'm using the admin django and not a custom post method, i dont know where to pass the {{ csrf_token }} Thanks for your help :) -
Trying to Debug Python Django application with VS Code remote-containers not running
I've been using the remote-containers in VS Code to run a Python Django application successfully for a couple of months, as I have an M1 machine and it's just a nightmare trying to install all the dependencies locally, and it was working really well. I came back to the application yesterday and now it's suddenly not working, the container seems to build without any issues and I can see it's running, and the build logs don't present any errors. But when I try and run with or without debugging the it pops up the run tool bar (start, stop, step ect) for a second and then stops with no output or errors at all. Has anyone seen this before? or have any ideas how to try and get it running again? Using the rebuild container and rebuild container without cache commands both seem to run without errors I updated both VS Code and Docker to the latest version I tried cloning the repository again I verified that the docker image builds locally without issue The vs code remote containers plugin seems to still be working because I tried it with a Flask application example I used before to demo the … -
My Django App works on my local development server but does not work on my Linode VPS
I have the exact same code deployed locally on development server and Linode Virtual Private Server. The Local site works fine, but when I try to access the same url on the VPS, I see this in the browser: This site can’t be reached XXX.XXX.XXX.X refused to connect. Try: Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED Even when I go to the admin site it is broken. I have narrowed the change down to my views.py and settings.py file changes, as I was making one code change at a time to try and find out where the VPS did not like my code. I am unable to understand why the Django App just seems to break. My views.py function, the last line of code will be called: def start_or_end_fast(request): if request.method == 'POST' and 'start_fast' in request.POST: start() return HttpResponseRedirect(reverse('start_or_end_fast')) elif request.method == 'POST' and 'end_fast' in request.POST: print('mmmmm') end() return HttpResponseRedirect(reverse('start_or_end_fast')) elif request.method == 'POST' and 'duration' in request.POST: duration = time_difference() return render(request,'startandstoptimes/index.html', {'duration': duration}) else: return render(request,'startandstoptimes/index.html') settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development … -
Django Management Command For Exporting Model data
I am trying th create a management command to export model data in csv but it is not working can anyone help me to export the data to the csv. just two field name i added to export that data to csv . import csv from appdirs import unicode from django.core.management.base import BaseCommand def _write_csv(meta): f = open(meta['file'], 'w+') writer = csv.writer(f, encoding='utf-8') writer.writerow( meta['fields'] ) for obj in meta['class'].objects.all(): row = [unicode(getattr(obj, field)) for field in meta['fields']] writer.writerow(row) f.close() print ('Data written to %s' % meta['file']) def your_model(): from new_db.models import Product meta = { 'file': '/tmp/your_model.csv', 'class': Product, 'fields': ('name','id') } _write_csv(meta) class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Product Moved To CSV.") -
is using multitable inheritance that bad in django and shoud i use it for my case?
basically, I have the following models for products: class Category(models.Model): name = models.charfield() class Product(models.Model): ....... class PhyscialProduct(Product): category = models.ForeignKey(Category) ......... class Course(Product): ......... class Book(Product): ......... I had to do it like this because each product has its own fields, but I was reading how multi-table inheritance "that it's evil", and because mostly going to work with the subclasses of the Product class, should I use content type and generic foreign key instead, or using multi-table inheritance is not that bad? -
How to access many-to-many field associated with specific model id in Django?
For a specific project id, I would like to be able to access all users associated with the project. models.py is below: class IndividualProject(models.Model): project = models.CharField( max_length = 64 ) group = models.ForeignKey( Group, on_delete=models.CASCADE, related_name = "project_group", blank=True, null=True, ) user = models.ManyToManyField( UserProfile, blank = True, ) def __str__(self): return f"Project {self.project}" If I do IndividualProject.objects.get(id = 1), I would like to be able to see all of the users associated with that project. I can find all projects associated with a specific user per the below: test = UserProfile.objects.get(id = 1) test.individualproject_set.all() Is there a way to do the above but using a specific project? Thank you! -
Django 4.0.1 django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. when I run make migrations
I changed something in the Request model and tried running makemigrations and it is giving me this error $python manage.py makemigrations Traceback (most recent call last): File "/Users/raymond/Documents/GitHub/Management/manage.py", line 22, in <module> main() File "/Users/raymond/Documents/GitHub/Management/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models self.models_module = import_module(models_module_name) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/raymond/Documents/GitHub/Management/request/models.py", line 7, in <module> class Request(models.Model): File "/Users/raymond/Documents/GitHub/Management/request/models.py", line 9, in Request teacher = models.ForeignKey(User, on_delete=models.CASCADE, choices=[(u.username, u) for u in User.objects.filter(profile__teacher_status=True)], related_name='teacher') File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 974, in filter return self._filter_or_exclude(False, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 992, in _filter_or_exclude clone._filter_or_exclude_inplace(negate, args, kwargs) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/query.py", line 999, in _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) File "/Users/raymond/opt/anaconda3/envs/python388/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1375, in add_q clause, _ = … -
Error when installing a chart library in ReactJS @16.13.1
I am trying to install a chart library in a react app, but I am getting the same error. I am using version @16.13.1 for ReactJS, for python @3.8.2 and django @3.2.10 and "@material-ui/core": "4.9.14". Could you help me, please, to find out which is the problem and which library I should use with the versions listed above? Thank you gyp verb `which` failed Error: not found: python2 -
Updating manytomanyfield unchecks previous objects
My project consists of a Book model which holds all sorts of different genres of books. For example romance, horror, sci-fi and so on. Each user then has a reading list. Which is a model that looks like this: class Readinglist(models.Model): user = models.OnetoOnefie(User, on_delete=models.CASCADE) books = models.ManyToManyField(Books) The reading list is then presented to each user by category. To be able to add books to each category, have I created unique views (the categories are not that many). The horror view looks like this: class UpdateReadingListHorror(UpdateView): model = ReadingList form_class = ReadingListHorrorForm The ReadingListHorrorForm looks like this: class ReadingListHorrorForm(forms.ModelForm): book = forms.ModelMultipleChoiceField(queryset=Books.objects.filter(genre='Horror'),widget=forms.CheckboxSelectMultiple, label='') class Meta: model = ReadingList fields = ['books',] All the other views and forms for the other genres look the same, only the query set in the form is changed to match it. The problem is that when I update the Horror category, the books in the other categories get unchecked and are no longer tied to the user's reading list. I can't understand why this is happening. How can I prevent this from happening? -
Python requests cannot resolve Docker-Compose services
I have 2 docker-compose set ups in separate repos. When I run them I want them to talk to each other on the same network. Both apps are up and running and are on the same network by using docker inspect. But when I try to make requests from nhec_ter_app to vtn_app using python requests it's not able to resolve. docker-compose.yml 1 version: '3.2' services: vtn_app: &app tty: true cap_add: - SYS_PTRACE build: context: . args: requirements: requirements/development.txt container_name: vtn environment: - DEBUG=False - PYTHONUNBUFFERED=1 - TESTING_USER=oh_hey_there - SQL_USER=postgres - SQL_HOST=postgres - SQL_PASSWORD=postgres - SQL_DB=postgres - SQL_PORT=5432 restart: always volumes: - .:/app:delegated depends_on: - postgres ports: - 8000:80 - 8080:8080 - 8081:8081 command: make adev networks: - nhec-ter_ter-web-net postgres: image: postgres:10 container_name: vtn_postgres environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres ports: - 5432:5432 networks: - nhec-ter_ter-web-net networks: nhec-ter_ter-web-net: external: name: nhec-ter_ter-web-net docker-compose.yml 2 version: "3.9" services: nhec_ter_app: build: . command: python manage.py runserver 0.0.0.0:8000 container_name: nhec_ter environment: - DEBUG=True - PYTHONUNBUFFERED=1 - TER_BASIC_AUTH_USER=pricesAdmin - TER_BASIC_AUTH_PASSWORD=Barry0325! - CELERY_BROKER_URL=redis://broker:6379/0 - VTN_API_URL=http://vtn_app/ - VTN_API_TOKEN=NHEC_UTILITY volumes: - .:/code ports: - "9000:8000" depends_on: - db - celery-worker - broker networks: - nhec-ter_ter-web-net nhec_ter_test: build: . command: python manage.py test container_name: nhec_ter_test environment: - DEBUG=True - … -
how to pass data from Django to react without database
I am doing a dashboard app using Django and react. The user 's data is from Dynamics CRM API. I created a function in python to fetch all the info I need for the dashboard from the api. What I want to do is to pass the user 's data (business orders) from Django -
Class Based Views Form neither Valid nor Invalid (Django)
I'm new to Django Class Based Views and I can't get my form to pass through neither form_valid() nor form_invalid(). I have taken most of this code from the Django allauth module, so I extend some mixins (AjaxCapableProcessFormViewMixin & LogoutFunctionalityMixin) that I do not know well. This form is meant to allow users to change their passwords upon receiving an email. As it is now, users are able to change their password but since the form_valid() function is never triggered, they do no get redirected to the success URL as is intended. Instead the password change is registered but the users stay on the same page. The functions dispatch(), get_form_kwargs() & get_form_class() are all triggered and behave in the way that they should. Still, it's unclear to me why they execute in the order that they do (dispatch() is triggered first, then get_form_class() and finally get_form_kwargs(). I suppose they implicitely have an order as presented in this documentation: https://ccbv.co.uk/projects/Django/4.0/django.views.generic.edit/FormView/) I am lacking some intuition about how this works, therefore I don't know if there is a way to redirect to the success URL without passing through form_valid() because that would also solve my problem. Here is my code: class PasswordResetFromKeyView(AjaxCapableProcessFormViewMixin, … -
why django command not working in vscode?
when I create new commande in my terminal (in vsCode) or cmd .. the command it doesn't work nothing happens -
how can i get an object in templates by using django sessions?
so basically im making an E-commerce website. and i want to implement sessions in it. i stored product.id as a key and product.quantity as a value in a dictionary called cart and stored in the session request.session['cart'] = cart if i print request.session['cart'], it prints keys and values like this {'10': 2, '15': 1, '11': 1} as it should be but i wanna do is to get product object in templates by this session. i wanna get all the product details(name,price, etc) by its id in cart.html is there any way i can do that? should i use custom template filter and how can i use that? Code id = request.POST.get('id') obj_id = Product.objects.get(id=id) cart = request.session.get('cart') if cart: quantity = cart.get(id) if quantity: cart[id]= quantity+1 else: cart[id] = 1 else: cart={} cart[id] = 1 request.session['cart'] = cart print(cart) return redirect('index') what i was doing is store product obj as key in cart but it showed an error.. -
django web app and recording and storing video on server
I'm creating a Django exam portal web-app which will access user's camera and record user for monitoring his activity during exam and once he finishes his exam I want to store the recording into server's media folder in video format. I've tried mediaStream API of javascript and it works fine but I'm not able to store the data in server. Does anyone have any idea or knows any framework in python which I can use to complete my webapp? -
How can I create proper m2m signals in Django for get notifications?
My motive is to create a signal for ProductREVIEWS so that when a user gives a review on a particular product then the seller will get a notification like ' user given feedback on your product'. I created a signal but it didn't work. Please check it up and give me a relevant solution. signals.py: @receiver(m2m_changed, sender = ProductREVIEWS.product) def send_notification_when_someone_give_feedback(instance, pk_set, action, *args, **kwargs): pk = list(pk_set)[0] user = User.objects.get(pk=pk) if action == "post_add": Notification.objects.create( content_object = instance, user = instance.user, text = f"{user.username} given feedback on your product.", notification_types = "ProductREVIEWS" ) models.py: class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) class ProductREVIEWS(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='userREVIEW',on_delete=models.CASCADE) product = models.ForeignKey(Products, related_name='productREVIEWrelatedNAME',on_delete=models.CASCADE) feedBACK = models.TextField(blank=True, null=True) views.py: def user_notifications(request): notifications = Notification.objects.filter( user = request.user, is_seen = False ) for notification in notifications: notification.is_seen = True notification.save() return render(request, 'notifications.html') context_processors.py: from notification.models import Notification def user_notifications(request): context = {} if request.user.is_authenticated: notifications = Notification.objects.filter( user = request.user ).order_by('-created_date') unseen = notifications.exclude(is_seen = True) context['notifications'] = notifications context['unseen'] = unseen.count() return context templates: {% if notification.notification_types == 'ProductREVIEWS' %} <a href="{% url 'quick_view' notification.content_object.id %}"> {{ notification.text }} </a> {% endif … -
Using session data ion custom permissions Django
I want to validate session data in custom permission, when i tried to access session data inside permissons it is showing None.Please help on this. class IsEmployee(permissions.BasePermission): def has_permission(self, request, view): if (request.session.get(request.user) and request.session[self.request.user.email].get("project_id")) is not None: project_id = request.session.get("project_id") if Employee.objects.filter(user_id=self.request.user, project_id=project_id, status="A", project__status='A'): return True else: return False Result throws None -
hasattr(value, "contribute_to_class") returns KeyError: 'contribute_to_class' (Django 4.0.6)
A Django 1.1 / Python 2.7 project that I'm attempting to run on Python 3.10 / Django 4.0.6. A Python related error (i.e. old import) or a django code error (i.e. missing field that's now mandatory) pops up, I fix it and rerun. The current error, however, is coming from django/db/models/base.py, from this function - def _has_contribute_to_class(value): # Only call contribute_to_class() if it's bound. return not inspect.isclass(value) and hasattr(value, "contribute_to_class") I found this ticket - https://code.djangoproject.com/ticket/30309 that explains that hasattr is unreliable, but seems to be ignored. Has anyone encountered this issue, and managed to find a solution other than staying on Django 1.1? -
Django Add Related in Custom Form
Django Admin Add-related I would want to have the highlighted functionality in my custom form. What steps should i take? That is, from my Add Contact form, select a registrar if existing or add one and have the id as an input in the registrar field. -
Trouble Building OpenShift from Private Git Repository
I'm using OpenShift 4.10.20 to host/build a Django project (v4) I'm running into trouble building the application. These are the errors that I get when I build: Error: ErrImagePull Failed to pull image "visibility-testing-application:latest": rpc error: code = Unknown desc = reading manifest latest in docker.io/library/visibility-testing-application: errors: denied: requested access to the resource is denied unauthorized: authentication required Error starting build: an image stream cannot be used as build output because the integrated container image registry is not configured I'm using a source secret to pull the code from my private git repository to my image. I used the 'Import from Git' wizard for this. Import from git How I can fix this? -
How to filter based on a field in the custom through model using rest serializer?
I have two models with many to many relation. The many2many table is created and linked to the parent tables by the 'through' attribute. ModelA(modles.Model): name = charfield() ModelB(models.Model): subject = charfield(default=1, choices = [1,2,3]) people = ManyToManyField(ModelA, through="MOdelAB") ModelAB(models.Model): status = integerfield() modela_id = foreignkey() modelb_id = foreignkey() ModelB_Serializer(serializers.Serializer): modela = ModelASerailizer(many=True) class Meta: model = ModelB exclude = ... fields = ... depth = 1 This returns all the A objects in the through table, but I want to filter only the ones with status=99. Is there a nice way to do that?