Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Refused to display in a frame because it set 'X-Frame-Options' to 'deny' in django application
Error in browser console: Refused to display 'http://74.207.232.194/media/edas/881063.html?&output=embed' in a frame because it set 'X-Frame-Options' to 'deny'. My backend url http://74.207.232.194 which is a django application. In side my django application some html files is there inside media folder. I am trying to access and embel the htmls from backend media folder to my react.js application. But, It is not working with above error. Please have a look -
ORA-24338: statement handle not executed DJANGO PYTHON
I am using python 3.8, django 3.0.7 with connection to oracle database with version 18c Script my oracle procedure is My oracle procedure at the moment of executing the script it compiles, but at the moment of opening the application it does not deliver data of the cursor, it indicates error in the sentence for error -
How do I figure out what AWS RDS instance does my Django application need?
I was wondering what AWS RDS instance does my Django application need. How does one figure that out? What kind of benchmarks should my Django application have to be suited for T3 or M5? In the essence of the question, I want to find out how to figure out what kind of instance would be suited for my application. -
Why do I get [Errno 13] Permission denied: '/srv/hiim/media/Bookshelf.png' in Django?
So I have a Django application running on Ubuntu and nginx. I tried to let users upload photos, then ran into this error. (hiim is the name of my project, and Bookshelf.png is the image file I'm trying to upload) I did some research, and noticed that I need to do chmod or chown command in order to solve this. so I did sudo chown -R ubuntu:ubuntu media, because the problem was with the media directory. Then I did ls -al command, to see the ownership, and got this : drwxrwxr-x 2 ubuntu ubuntu 4096 Jul 15 04:09 media I thought the problem was solved but I keep getting the same error. What do you think is the problem? Thank you very much in advance. :) +++ FYI, here are my relate codes. settings.py MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Ckeditor not uploading images (Image source URL is missing.)
While creating blog posts I am unable to upload images through the editor. When I choose an image from my laptop and click 'OK' it says Image source URL is missing. forms.py from django import forms from .models import BlogPost from ckeditor_uploader.widgets import CKEditorUploadingWidget class BlogPostForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget()) class Meta: model = BlogPost fields = ('__all__') models.py from django.db import models from autoslug import AutoSlugField from ckeditor_uploader.fields import RichTextUploadingField import re html_tags_re = re.compile(r'<[^>]+>') class BlogPost(models.Model): title = models.CharField(max_length=100) featured_image = models.ImageField(upload_to='blog/%Y/%m/%d') content = RichTextUploadingField() timestamp = models.DateField(auto_now_add=True) slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') @property def plain_text(self): return html_tags_re.sub('', self.content) class Meta: verbose_name_plural = "Blog Posts" def __str__(self): return self.title settings.py INSTALLED_APPS = [ 'ckeditor', 'ckeditor_uploader', } CKEDITOR_UPLOAD_PATH = "uploads/" -
Login from example.com then route users to their subdomain schema in django-tenant-schemas
With django-tenant-schemas, I want to have a login form at the root URL: example.com. Then, based on which user logs in, they are routed to their respective subdomain schema: tenant.example.com. How would I go about doing this? -
Static Files not Displayed after Deployment to Google Cloud Run
I have a wagtail web application, It works perfectly in localhost but in production, the Debug is set to False and all the static files are not displayed in the deployed website, I am attaching the Dockerfile code below: # Use an official Python runtime as a parent image FROM python:3.7 LABEL maintainer="hello@wagtail.io" # Set environment varibles ENV PYTHONUNBUFFERED 1 ENV DJANGO_ENV production COPY ./requirements.txt /code/requirements.txt RUN pip install --upgrade pip # Install any needed packages specified in requirements.txt RUN pip install -r /code/requirements.txt RUN pip install gunicorn # Copy the current directory contents into the container at /code/ COPY . /code/ # Set the working directory to /code/ WORKDIR /code/ RUN python manage.py migrate RUN useradd wagtail RUN chown -R wagtail /code USER wagtail EXPOSE 8000 CMD exec gunicorn myweb_blog.wsgi:application --bind 0.0.0.0:80 --workers 3 The Production.py settings file is given below: from .base import * SECURE_BROWSER_XSS_FILTER=True FEATURE_POLICY = { 'geolocation': 'none', } #CSP_BLOCK_ALL_MIXED_CONTENT=True # SECURE_CONTENT_TYPE_NOSNIFF=True SECURE_FRAME_DENY=True SECURE_HSTS_SECONDS=2592000 SECURE_HSTS_INCLUDE_SUBDOMAINS=True SECURE_HSTS_PRELOAD=True X_FRAME_OPTIONS = 'DENY' SECURE_REFERRER_POLICY='same-origin' SECRET_KEY = 'A Secure Secret' ALLOWED_HOSTS = ['my domain'] DEBUG = False try: from .local import * except ImportError: pass --Base.py-- """ Django settings for myweb_blog project. Generated by 'django-admin startproject' using Django 3.0.4. For more … -
Django send reminder emails
So I have three staff users each one will be responsible for a task dealing with orders. One user will assign the manufacturing date "manu_date" in the model to the order. When the deadline of manu_date is in 7 days, I want to send an email to other users to notify them.How can I implement this function in Django? class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30) address = models.CharField(max_length=100) phone = models.IntegerField(max_length=11) method = (('Pay Upfront', 'Pay Upfront'),('Upon Delivery', 'Upon Delivery'),) shipping_method = models.CharField(max_length = 100, choices = method) language = models.CharField(max_length=30) box = models.CharField(max_length = 30) print_name = models.CharField(max_length=30) Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True) date_created = models.DateTimeField('date_created', default=timezone.now(), blank=False) manu_date = models.DateField('Manufacturing', null=True) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") updated_by = models.ForeignKey(User, null=True, related_name='updated_by_user', on_delete=models.CASCADE) date_updated = models.DateField(max_length=100, null=True) def is_manu_date(self): if self.manu_date is not None: return date.today() > self.manu_date -
Django: Does .count() force the queryset evaluation
I want to have a non evaluated count queryset. I know from Django docs that len() forces the evaluation but what about count()? Does this hit the database? queryset = MyModel.objects.all().count() -
vue frontend how to get django_filters FilterSet fields by django rest framework
i make a project! django rest framework as the backend! vue(element-ui) as the frontend! my views.py like this: class VpcSetsFilter(filters.FilterSet): class Meta: model = VpcSets fields = ['VpcId', 'VpcName'] class VpcSetsViewSet(viewsets.ModelViewSet): queryset = VpcSets.objects.all() serializer_class = VpcSetsSerializer filter_class = VpcSetsFilter i want vue get the fiedls values list ['VpcId', 'VpcName'] by zhe rest api,but how ? -
New message notification django-channels
I know someone has already asked this question in stackoverflow, in fact this is the question: New chat message notification Django Channels, the answer they gave is exactly what I want to do, also my code or project has the same code of the person who ask. The problem is the following, I took a deep look and tried it in many ways, unfortunately, it did not work for me and I did not understand it very well. I would love someone to explain it to me, and teach me either with my modified code or what should I do to adapt the notification system when the user receives a new message, my code is the following: consumers.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) other_user = self.scope['url_route']['kwargs']['username'] me = self.scope['user'] # print(other_user, me) thread_obj = await self.get_thread(me, other_user) self.thread_obj = thread_obj chat_room = f"thread_{thread_obj.id}" self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) await self.send({ "type": "websocket.accept" }) # await asyncio.sleep(10) async def websocket_receive(self, event): # when a message is received from the websocket print("receive", event) front_text = … -
How to delete object in django?
enter image description here @csrf_exempt def ajax_owner_delete(request, pk): product = Product.objects.get(pk=pk) product.delete() return HttpResponse(status=200) I am doing this, it deletes every field of a model, but object still exists(look at the image) -
Static Files in Django in Pycharm
I tried to make a css file in django, im using pycharm btw, for my templates and it says "*.css files are supported by Intellij IDEA Ultimate" Should I download that or I can pip install a css in pycharm? -
Django object has no attribute 'all'()
Using Django, I am calling a webpush package to push notifications that includes the following function: def send_notification_to_user(user, payload, ttl=0): from .models import PushInformation push_infos = user.webpush_info.select_related("subscription") for push_info in push_infos: _send_notification(push_info.subscription, payload, ttl) This gives the error "'ReverseManyToOneDescriptor' object has no attribute 'select_related'" referring to push_infos Alternatively, I have changed push_infos to be: push_infos = user.webpush_info.all() This just returns that "'ReverseManyToOneDescriptor' object has no attribute 'all'" The only workaround I have figured out is: push_infos = user.objects.get(username='user123').webpush_info.select_related("subscription") This works well for the specific user I call on, but does not allow me to call this function for multiple users. Is there another way I can call all users through push_infos? This may be an amateur question but I haven't found the answer after reading through the Django docs for Users. For further context, this function works fine as part of the webpush package when I call the package through the shell. I am trying to automate notifications by using celery and that is where I am encountering this issue. -
Can I Integrate my desktop app with Django Authentication?
I've been developing a graphical user interface with Python 2.7, wxPython, postgreSQL and SQLAlchemy. This gui is to see and extact data from sensors. I reached a point where a would like to have this softwate in multiple computer comunicating with a center database. To do this my GUI needs a authentication system, its been pretty hard for me to understand clearly how to make one from scratch. Since my project at some point would like to have a website that have access to this database i began reseaching about django, and that it can use postgreSQL. Django has its own authentication library. I'm starting to set up the blog and all the authentication for the webpage in python 3.8. my doubts are in if i can use this django authentication library and use it also to manage my desktop application since i want both of them o have access to the users and sensors data. -
SMTPAuthenticationError 535: In development
I am creating a password reset utility and I am getting this error in my localhost web server: SMTPAuthenticationError at /password-reset/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials i10sm742924qkn.126 - gsmtp') I have looked at other posts, turned on less secure apps, stored the in the password and username in the environment variable settings correctly ( I know because I printed them in shell. Output came out as expected ), and did the display unlock captcha. I am running code in windows powershell. This is my settings configuration: EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST_USER = os.environ.get('HOST_USER') EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_PASSWORD = os.environ.get('HOST_PASSWORD') EMAIL_USE_TLS = True -
Bitnami Django Stack - CronTab on Mac
I am trying to setup a Crontab on my Mac To run every 15 minutes using the DjangoStack. I am not really versed in coding but tried a few things and it isn't working. -
Why isn't one JavaScript file not loaded in Django-summernote?
So I'm using django-summernote, and everything is working fine except summernote-ext-print.js file is not loaded. Below are my summernote-related codes and I don't really see what when wrong when I've done exactly the same as instructed in the documentation in github. settings.py INSTALLED_APPS = [ ... 'django_summernote', ... ] ... DEBUG = True ... SUMMERNOTE_CONFIG = { 'iframe': True, 'lang' : 'ko-KR', 'summernote': { 'width': '100%', 'height': '450px', 'placeholder':'First sentence', 'toolbar': [ ['style', ['style',]], ['font', ['fontsize', 'bold', 'italic', 'strikethrough']], ['color', ['forecolor', ]], ['para', ['ul', 'ol', 'height']], ['insert', ['link']], ['misc', ['picture', 'fullscreen', 'print', 'help', ]], ], }, 'js': ( 'static/summernote-ext-print.js', ), 'js_for_inplace': ( '/static/summernote-ext-print.js', ), 'css': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', '/mvp/static/summernote.css', ), 'css_for_inplace': ( '//cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/theme/base16-dark.min.css', '/summernote.css', ), 'codemirror': { 'theme': 'base16-dark', 'mode': 'htmlmixed', 'lineNumbers': 'true', }, 'lazy': False, } SUMMERNOTE_THEME = 'bs4' X_FRAME_OPTIONS = 'SAMEORIGIN' ... MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('summernote/', include('django_summernote.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Thank you very much in advance. :) -
Most efficient way of setting foreign key for an object in Django models if you're only given a unique id but not the primary key
I'm using Django stripe and the Stripe webhook system. The models are kinda like the following: class Blah1(models.Model): id = models.AutoField(primary_key=True) blah2 = models.ForeignKey(Blah2, on_delete=models.SET_NULL, null=True) class Blah2(models.Model): id = models.AutoField(primary_key=True) random = models.IntegerField(unique=True) I'm given some random="asdfasdf" from Blah2. Assuming a Blah1 object has a blah2 attribute that is null, how would I set this foreign key to this object the most efficiently? I can't change Blah1 and Blah2's model since they're built in to the third-party package. The only thing I can think of is, since random is unique=True, there should be an index for it, so I can do a get query for the one object (e.g. blah1_obj.blah2 = Blah2.objects.get(random=random)). Is there any other way? Anything more efficient than two queries (SELECT then UPDATE)? -
Protect S3 Files From Public Viewing [duplicate]
I have a bucket in S3 with files in it. I built a dashboard in Django and want my logged in users to be able to access these files, but no one else. How can I protect the url of the file? One way I was thinking was with some sort of auth or maybe generating a one time link that can only be opened once. What is the standard? -
Django Taggit without using Forms
I had to change my form for Html design reasons and go old school. Everything was fine before (so I know it was working) but now I need to save manually. What I need is something like this: if request.method == 'POST': d = Diary() d.user = request.user .... d.tags = request.POST['tags'] d.save() Nothing is showing up for the tags. Before there was this and I suspect it all has something to do with the .save_m2m if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() # Without this next line the tags won't be saved. form.save_m2m() Here is the Model. class Diary ( models.Model ): user = models.ForeignKey ( settings.AUTH_USER_MODEL) .... tags = TaggableManager (blank=True) Is this possible? Thank you. -
Using Form Wizard with pages that have no forms
I am working on a Django project where I have about 7 pages all in order. Basically step 1 - 7. I would like for them to have some sort of navigation/progress bar above the content showing where they are in the pages and how much they have completed. The only thing I have found close to this is using Wizard Form. The only issue I run into with this is some pages do not have a form. Page 1 = Pure text explaining information Page 2 = Setup information Page 3 = Form Page 4 = Form Page 5 = Information Page 6 = Form Page 7 = Completion/Thanks Is it possible to still use the Wizard Form for this setup? Or is there a better method of doing what I am trying to accomplish? -
Use .values without using .annotate in Django
Is there a way I can group my query using .values without .annotate in Django? Is it require always to have the .annotate when you are using .values to group? Or there is another way to group my result queue other than .values. Here is my simple code: def fetchAllCustomers(request, salesperson): data = {'data': list(MCPRecord.objects.filter(col_sales_person=salesperson).values('col_customer', 'id').annotate(no_record=Count('col_customer')))} return JsonResponse(data, safe=False) Result: {"data": [{"col_customer": "N/A", "id": 2, "no_record": 1}, {"col_customer": "N/A", "id": 3, "no_record": 1}]} But I dont want to have the annotate everytime I'm grouping my cols in database. -
How do I construct complex django query statements?
I am not very familiar with SQL and so trying to make more complex calls via Django ORM is stumping me. I have a Printer model that spawns Jobs and the jobs receive statuses via a State model with a foreign key relationship to it. The jobs status is determined by the most recent state object associated with it. This is so I can track the history of states of jobs throughout its life cycle. I want to be able to determine which Printers have successful jobs associated with them. from django.db import models class Printer(models.Model): label = models.CharField(max_length=120) class Job(models.Model): label = models.CharField(max_length=120) printer = models.ForeignKey( Printer, related_name='jobs', related_query_name='job' ) def set_state(self, state): State.objects.create(state=state, job=self) @property def current_state(self): return self.states.latest('created_at').state class State(models.Model): created_at = models.DateTimeField(auto_now_add=True) state = models.SmallIntegerField() job = models.ForeignKey( Job, related_name='states', related_query_name='state' ) I need a QuerySet of Printer objects that have at least one related job with its most recent (latest) state object which has State.state == '200'. Is there a way to construct a compound call which will achieve this using the database and not having to pull in all Job objects to run python iterations on? Perhaps a custom manager? I've been reading posts … -
Bash script to run multiple Django application
I'm new to writing bash scripts and I would like to write one to start and stop multiple Django applications. For the stopping one, I've found a command pkill -f runserver which killed all running apps. However, for starting multiple applications, I cant seem to get it working. When I run one manage.py runserver command, it won't proceed onward from the first application unless I press ctrl + c. Is there a way to run multiple django application within one bash script? Thanks in advance.