Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slow iframe ReactJS and Django
It is the first time that I ask a question here, I always read their answers and they help me a lot. I am developing a web page in ReactJS that receives information from surveillance cameras that come from the backend that is mounted in django, my problem is that I am showing them through an iframe on the frontend and they are seen with terrible fluency and I need that the visualization is online since in the current way it does not serve me. I leave you some code snippets to see if you can help me. Thank you! I have tried with react-video, react-player and it does not play anything (it remains black) I have only been able to show it with iframes and as an object import React from 'react'; import { FullScreen, useFullScreenHandle } from "react-full-screen"; function OnFullScreen() { const handle = useFullScreenHandle(); const url = sessionStorage.getItem('url'); return ( <div> <FullScreen handle={handle} id="fullScreen"> <iframe title = "iFrame" frameBorder = "0" allowFullScreen scrolling = "no" src={`http://localhost:8000/video_feed/${url}`} id="iFrame" > Su Navegador Web no admite iFrames. </iframe> </FullScreen> <button onClick={handle.enter} className="btn btn-success mb-5 mt-2"> Pantalla Completa </button> </div> ); } export default OnFullScreen; -
IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm a beginner at Django and this is my first project without a book or tutorial. I started my project with a Custom User class, base on AbstractUser. After that, I used the third-party package django-allauth to handle user registration flow, and it all worked fine. Users could only sign up and login with their email and username was not required as expected. The problem started when I changed the sign up form in the django-allauth configs. In this new form I added some custom fields when the user signed up, but that gave me this error that I can't fix. One important thing is that the new users are created, even though I keep getting this error. I've read a lot of question on the same issue but none helped me to fix my problem. Here is my models.py: class CustomUser(AbstractUser): email = models.EmailField(verbose_name="Email", unique=True, max_length=250) first_name = models.CharField(verbose_name="Nome", max_length=100, null=True) last_name = models.CharField(verbose_name="Sobrenome", max_length=250, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name', 'university', ] My forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name', 'major', 'university',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('first_name', 'last_name', 'major', 'university',) And my admin.py: class CustomUserAdmin(UserAdmin): … -
How should I call API request automatically from Twitter?
I want user's tweet data whenever they tweet new. But without running script every 15 minutes to know whether they have new tweet or new. It takes lots of resources. Is there any way that I will get data only when they tweet? -
How to prevent AWS EC2 server from running indefinitely?
I have a Django app that users can submit video through to be processed via a python script running OpenCV on a separate EC2 instance. As this is a moderately expensive server to run (p2.Xlarge ~ $3.00/h) it is only spun up when the video is submitted and I want to ensure that it doesn't continue to run if there is some hiccup in the processing. If the program works fine the instance is properly shut down. The problem is sometimes the python script gets hung up (I can't seem to replicate this on it's own which is a separate problem) when the script doesn't fully execute the server continues to run indefinitely. I have tried the solution provided here for self terminating an AWS EC2 instance. The solution works if the server is idle but doesn't seem to work if the server is busy trying to process the video. Is there a better way to make sure the server doesn't run longer than x minutes and stop it, even if the server is in the middle of a process? The code I'm currently using: import paramiko import boto3 import sys from botocore.exceptions import ClientError import json from time import … -
how to manage websocket connection in django use asgi
my application like this # asgi.py import os from django.core.asgi import get_asgi_application from websocket_app.websocket import websocket_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings') django_application = get_asgi_application() async def application(scope, receive, send): if scope['type'] == 'http': # Let Django handle HTTP requests await django_application(scope, receive, send) elif scope['type'] == 'websocket': # handle websocket connections here await websocket_application(scope, receive, send) else: raise NotImplementedError(f"Unknown scope type { scope['type'] }") # websocket.py async def websocket_application(scope, receive, send): while True: event = await receive() if event['type'] == 'websocket.connect': await send({ "type": "websocket.accept" }) if event['type'] == 'websocket.disconnect': break if event['type'] == 'websocket.receive': try: # result = json.loads(event['text']) await route(scope, event, send) except Exception as e: await send({ "type": "websocket.send", "text": e.__repr__() }) I want to send a message to A client when I received a message from B client, but i have no idea how can I find a websocket connection and send message to A client. I think I should do something to manage multiple websocket connection, but I have no idea how to do it. -
How to use 'view.kwargs' correctly
I am trying to add a Profile Image for a user in a page next to his username which is working fine and I have tried to use the same logic to add the profile image but it didn't work and I don't know what is the reason, there is no error message showing it is simply not showing because probably it is not written correctly. I am trying to understand how to use the query function correctly so this is a trial for me Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username'), profile=self.kwargs.get('profile')) <---------------------------- Here is my trial to add profile return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') Here is the template {{ view.kwargs.username }} <---------------------- Showing correctly <embed class="profile_image" src={{ view.kwargs.user.profile.image.url }}> <------------- not appearing -
photoshop 3d mockup change its texture programmatically
I'm plannin on buying 3d mockups for my products. My website is using django. Before I used to use blender on server to make mockups like below: when a user / administrator uploads a product dlajgo celery to put a texture of image / color on the product using blender/pyton script but I found out there is similar function on photoshop. https://creativemarket.com/webandcat/3770816-Folded-Fabric-Mock-up I really would like to use this mockup and would like to know if there is any similar way to programmatically change its texture image like blender/python on server side(centos 7) Thanks! -
.env keyError in django project
I'm having a hard time because my django project. Who can help? I'd like to thank you for your help. set .env in proeject Root path SECRET_KEY=exampleKey DEBUG=False DB_ENGINE=django.db.backends.mysql DB_NAME=example DB_USER=admin ...Blah Blah project settings.py import os import environ env = environ.Env(DEBUG=(bool, False), ) environ.Env.read_env() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ...Blah Blah And when run the project I get an this error message. Django_workspace/asone/asone/.env doesn't exist - if you're not configuring your environment separately, create one. "environment separately, create one." % env_file) raise KeyError(key) from None KeyError: 'SECRET_KEY' During handling of the above exception, another exception occurred: /Django_workspace/asone/venv/lib/python3.7/site-packages/environ/environ.py", line 277, in get_value raise ImproperlyConfigured(error_msg) django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable I have a hard time because I'm a django beginner. Who can help? I'd like to thank you for your help. thank you for watching I'll be waiting for your response -
Is there a way to have a list type object in Django models?
I'm starting my first solo Django project and have run into how to store things on my database. What I'm doing is trying to create a web-based grocery store. I'm wanting to add an order model where I can store a user and then a list or optimally a dictionary of what they want. I know the dictionary may be a stretch, but is there some way to create a model list? I've looked at similar questions and seen the JSON option I'm not really sure how I can make that work since I can't manipulate that in the admin. Thanks in advance. -
Not able to save foreign key serializer value
I have two models namely Media and Source. Source is a foreign key field in Media table. Below code shows the Serializer needed by REST API and to save the Media information. What problem I am facing is that whenever I tried to POST data on MEDIA rest end point, Source value is not getting stored. It shows null. {"id":44,"category":["deepfake"],"source":null,"status":"under_review","nsfw":false,"severity":"unknown","title":"Lakshmi Menon Deepfake(Bollywood Sexy Tease)","description":null,"type":"video","url":"https://adultdeepfakes.com/v1940539","file":"https://adultdeepfakes.com/wp-content/uploads/videos/B_LAKSHMI_MENON_AS_MAID_FUCKING_TRAILER_PAID_REQ_o_c_optimized.mp4","image":null,"data":{"views":"213","likes":"1","dislikes":"0","tags":""},"published_at":"2020-08-20T09:00:39Z","created_at":"2020-08-21T00:37:06.654294Z","updated_at":"2020-08-21T00:37:06.654305Z","persons":[]} What I tried is remove source = SourceSerializer(many=False, read_only=True) code and save. It works!! But then in rest api it doesn’t show the source details. Can anyone please advise me how I could get best of both the worlds? class MediaSerializer(serializers.ModelSerializer): """Serializer for the Media model """ category = CustomSlugRelatedField( queryset=Category.objects.all(), many=True, read_only=False, slug_field="name", ) source = SourceSerializer(many=False, read_only=True) class Meta: model = Media fields = "__all__" read_only_fields = [ "created_at", "updated_at", ] -
Redirected to index after search query in another url in Django
so I added another html page to my project besides the index. The page technically works but it does not render any results, only redirects me to index expressing the result of the else condition in that function. I am not sure why this is happening, it's as if the search queries of my html template were not working. This is my view: from django.shortcuts import render, HttpResponse from django.views.generic import ListView import requests def people(request): people = [] if request.method == 'POST': people_url = 'https://ghibliapi.herokuapp.com/people/' search_params = { 'people' : 'name', 'people' : 'gender', 'people' : 'age', 'people' : 'eye_color', 'q' : request.POST['search'] } r = requests.get(people_url, params=search_params) results = r.json() if len(results): for result in results: people_data = { 'Name' : result['name'], 'Gender': result['gender'], 'Age' : result['age'], 'Eye_Color' : result['eye_color'], 'Films' : result['film'] } people.append(people_data) else: message = print("No results found") print(people) context = { 'people' : people } return render(request,'core/people.html', context) def index(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() if len(results): for result in results: movie_data = … -
raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES
I want to create a new app using 'python manage.py startapp' in my files but I am getting this error. raise ImproperlyConfigured("settings.DATABASES is improperly configured. " django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. here is the databases in my seetings.py: DATABASES = { 'default': dj_database_url.config(), } db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) This is after migrating to heroku. -
Why am I still getting 'DeferredAttribute' object has no attribute 'objects'?
After a few days of searching, I still am unable to get over this hurdle. I'm just trying to print a list of descriptions from Sellers as a view. Here's what I'm working with... models.py: from django.db import models class Sellers(models.Model): index = models.BigIntegerField(blank=True, null=False) seller = models.TextField(db_column='SELLER', blank=False, null=False, primary_key=True) block = models.TextField(db_column='BLOCK', blank=False, null=False) street = models.TextField(db_column='STREET', blank=False, null=False) space = models.TextField(db_column='SPACE', blank=False, null=False) description = models.TextField(db_column='DESCRIPTION', blank=True, null=True) document_with_idx = models.TextField(blank=False, null=False) document_with_weights = models.TextField(blank=False, null=False) class Meta: managed = False db_table = 'Sellers' def __str__(self): return self.index ''' views.py: from django.http import HttpResponse from search.models import Sellers def search(request): output = Sellers.description.objects.all() return HttpResponse(output) ''' Any direction would be appreciated, I feel like I've read every related post related to this. Figured it was about time to post a question with my exact setup. Thanks! -
TypeError in Django Application
I am making a Django application. It's a wikipedia page that will allow you to create a new page if you click . The path is in urlpatterns is: path("create", views.create, name="create") The function in views.py is: def create(request): if request.method == 'POST': form = Post(request.POST) if form.is_valid(): title = form.cleaned_data["title"] textarea = form.cleaned_data["textarea"] entries = util.list_entries() if title in entries: return render(request, "encyclopedia/error.html", {"form": Search(), "message": "Page already exist"}) else: util.save_entry(title,textarea) page = util.get_entry(title) page_converted = markdowner.convert(page) context = { 'form': Search(), 'page': page_converted, 'title': title } return render(request, "encyclopedia/entry.html", context) else: return render(request, "encyclopedia/create.html", {"form": Search(), "post": Post()}) The error message I am getting is: TypeError: decoding to str: need a bytes-like object, NoneType found -
Bad Gateway when configuring nginx with. Django app container and Gunicorn
I'm using docker-compose to deploy a Django app on a VM with Nginx installed on the VM as a web server. but I'm getting " 502 Bad gateway" I believe it's a network issue I think Nginx can't access the docker container! however, when I use the same configuration in an Nginx container it worked perfectly with the Django app but I need to use the installed one not the one with docker. This is my docker-compose file: version: "3.2" services: web: image: ngrorra/newsapp:1.0.2 restart: always ports: - "8000:8000" volumes: - type: volume source: django-static target: /code/static - type: volume source: django-media target: /code/media environment: - "DEBUG_MODE=False" - "DB_HOST=…” - "DB_PORT=5432" - "DB_NAME=db_1” - "DB_USERNAME=username1111" volumes: django-static: django-media: And this is my nginx.conf file: upstream web_app { server web:8000; } server { listen 80; location /static/ { autoindex on; alias /code/static/; } location /media/ { autoindex on; alias /code/media/; } location / { proxy_pass http://web_app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } #For favicon location /favicon.ico { alias /code/assets/favicon.ico; } # Error pages error_page 404 /404.html; location = /404.html { root /code/templates/; } } Does anyone know what is the issue? Thank you! -
When http doesn't return answer I get UnboundLocalError
I have a website and I was trying to add a feature so that when you look for a movie title that doesn't exist, you get a message that says "Not results found". However, when I try the feature that I added with the else statement, I get this error: "UnboundLocalError at / local variable 'movie_data' referenced before assignment". It only happens when I search for something that doesn't exist. Why is it happening? This is my view: def index(request): movies = [] if request.method == 'POST': film_url = 'https://ghibliapi.herokuapp.com/films/' search_params = { 'films' : 'title', 'films' : 'description', 'films' : 'director', 'films' : 'release_date', 'q' : request.POST['search'] } r = requests.get(film_url, params=search_params) results = r.json() for result in results: movie_data = { 'Title' : result['title'], 'Release_date': result['release_date'], 'Director' : result['director'], 'Producer' : result['producer'], 'Description' : result['description'] } movies.append(movie_data) else: message = 'Not results found' context = { 'movies' : movies } return render(request,'core/index.html', context) -
Problem with CheckboxSelectMultiple from a CharField ModelForm in Django
I'm having trouble getting my form to save in Dajngo due to the following error on validation: <ul class="errorlist"><li>pt_medical_condition<ul class="errorlist"><li>Select a valid choice. [&#x27;anx&#x27;, &#x27;Bip&#x27;] is not one of the available choices. >pt_surgical_history<ul class="errorlist"><li>Select a valid choice. [&#x27;bre&#x27;, &#x27;pca&#x27;] is not one of the available choices. I've got this model: class pt_data(models.Model): condition_choices = [('ane', 'Anemia'), ('anx', 'Anxiety'), ('art', 'Arthritis'), ('ast', 'Asthma'), ('Bip', 'Bipolar'), ('ca', 'Cancer'), ('clo', 'Clotting disorder'), ('chf', 'CHF'), ('mdd', 'Depression'), ('cop', 'COPD'), ('ger', 'GERD'), ('gla', 'Glaucome'), ('hiv', 'HIV/AIDS'), ('ibs', 'IBS/Crohn\'s'), ('hld', 'High cholesterol'), ('ckd', 'Kidney disease'), ('ner', 'Nerve/Muscle disease'), ('ocd', 'OCD'), ('ost', 'Osteoporosis'), ('pai', 'Pain disorder'), ('pts', 'PTSD'), ('sch', 'Schizophrenia'), ('sei', 'Seizures'), ('sca', 'Sickle cell anemia'), ('su', 'Substance use disorder'), ('thy', 'Thyroid disease')] surgery_choices = [('app', 'Appendix removal'), ('bra', 'Brain surgery'), ('bre', 'Breast surgery'), ('cabg', 'CABG'), ('pca', 'Cardiac stent'), ('cho', 'Gallbladder removal'), ('col', 'Bowel surgery'), ('csec', 'C-section'), ('fra', 'Bone fracture repair'), ('her', 'Hernia repair'), ('hys', 'Uterus removal'), ('joi', 'Joint replacement'), ('lun', 'Lung surgery'), ('spi', 'Spine/back surgery'), ('thy', 'Thyroid surgery'), ('ton', 'Tonsil removal'), ('strf', 'Tubal ligation'), ('strm', 'Vasectomy'), ('wei', 'Weight reduction surgery')] pt_medical_condition = models.CharField(max_length=100, blank=True, null=True, choices=condition_choices) pt_surgical_history = models.CharField(max_length=100, blank=True, null=True, choices=surgery_choices) And this form: class ptForm(forms.ModelForm): class Meta: model = pt_data fields = ('__all__') widgets … -
I can not seem to register a namespace
My project was running fine, but then I decided to remake the entire thing and I keep getting the same error. I am trying to link all_blogs.html to detail.html. In all_blogs.html I have this a tag: . Every time I try to runserver I get the message "NoReverseMatch at /'blog' is not a registered namespace". From what I understand, we can register a namespace by adding "app_name = (namespace)" in urls.py. I did this and yet for some reason I still get the error. I am sure it has something to do with what I have in urlpatterns. Please check out my code and github link to see the entire project. github Thank you in advance for your efforts. Error page: NoReverseMatch at / 'blog' is not a registered namespace Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: NoReverseMatch Exception Value: 'blog' is not a registered namespace Exception Location: C:\Python38\lib\site-packages\django\urls\base.py in reverse, line 83 Python Executable: C:\Python38\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\Admin\\Desktop\\webDev\\xennialsworld', 'C:\\Python38\\python38.zip', 'C:\\Python38\\DLLs', 'C:\\Python38\\lib', 'C:\\Python38', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Python38\\lib\\site-packages'] Server time: Thu, 20 Aug 2020 22:54:36 +0000 My urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from … -
My model has a manytomanyfield field. I want to see the string value of this field and save it with the string value
My model has a manytomanyfield field. I want to see the string value of this field and save it with the string value Model.py class Advertise(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True) interior_feature = models.ManyToManyField(to="advertise.InteriorFeature") Serializer.py## class AdvertiseMainSerializer(ModelSerializer): class Meta: model = Advertise fields = '__all__' -
elastic beanstalk key pair issue SSH
my django website is down and it's been one week without a result. The eb deploy is giving me issues even after updating many different version of wsgi.py the ec2 server is not accepting request load balancer is showing 404 I suspecting some sort of attack/corruption but, not sure. If I try to add key pair to my EB configuration- security it starts going into a infinite loop and new ec2 is created. SSH into instance dose not work all ports 22 http/https are set up. C:\Users\nor\Desktop\website>eb deploy Creating application version archive "app-200820_133953". Uploading: [##################################################] 100% Done... 2020-08-20 20:51:22 INFO Environment update is starting. 2020-08-20 20:51:45 INFO Deploying new version to instance(s). 2020-08-20 20:52:05 ERROR Your WSGIPath refers to a file that does not exist. 2020-08-20 20:52:19 INFO New application version was deployed to running EC2 instances. 2020-08-20 20:52:19 INFO Environment update completed successfully. [![auto created instance after adding key pair ][1]][1] -
Update session variable while request ongoing [Django]
I am using Django's session variable to store a list of requests and their status. When a task is started an entry is added to the session storage with request.session["history"][id] = new_entry(status=PENDING) When the request completes I set the value to request.session["history"][id] = new_entry(status=COMPLETE) But when the session variable is queried while the task is still running the new entry with status = PENDING is not in the session storage. def view(request): request.session["history"][id] = new_entry(id=k, status=PENDING) run_task() # --> takes time request.session["history"][id] = new_entry(id=k, status=COMPLETE) def get_history(request): history = request.session["history"] # --> does not contain new_entry(id=k, status=PENDING) when task is running EDIT The request.session.modified value is set to True after every update -
Using for loop to seperate formsets with <hr> only between forms and not at beginning or end
I only want the horizontal rule between each form and not at the beginning or end. How can I alter the code so that the last horizontal rule is removed and how many different ways are there to doing this? <form method="POST"> {% csrf_token %} {% for form in formset %} {{ form.as_p }} <hr> {% endfor %} <button type="submit">Add Family Members</button> </form> Here's another example: mylist = ['Tom', 'John', 'Jack', 'Joe'] for i in mylist: print(i) print('----------') How can I alter the code so that '--------' is printed between the names but not at the end? -
Django form not showing up
I am new to django and trying to show a form in an html file and I don't see the fields . I can see everything except the form. Task: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. views.py def index(request): entries = util.list_entries() searched = [] if request.method == "POST": form = Search(request.POST) if form.is_valid(): item = form.cleaned_data["item"] for i in entries: if item in entries: page = util.get_entry(item) page_converted = markdowner.convert(page) context = { 'page': page_converted, 'title': item, 'form': Search() } return render(request, "encyclopedia/entry.html", context) if item.lower() in i.lower(): searched.append(i) context = { 'searched': searched, 'form': Search() } return render(request, "encyclopedia/search.html", context) else: return render(request, "encyclopedia/index.html", {"form": form}) else: return render(request, "encyclopedia/index.html", { "entries": util.list_entries(), "form":Search() }) layout.html <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form method="post" action="{% url 'index' %}"> {% csrf_token %} {{form.item}} </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'create' %}">Create New Page</a> </div> <div> <a href="{% url 'random' %}">Random Page</a> </div> {% block nav %} {% endblock %} </div> -
Want to know , why when I am using django project.I cannot save html file
I want to know why when I am using python framework django in vs code.I can not save html file as html file.It is automatically converted into dj file. And also in the file html shortcut (like ! for template) is not working .Please help me -
Pass javascript output to a html <div> as a parameter
I have a m_template.html file which has a script as follow: <script> $("#id_country").change(function () { var countryId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: '/ajax/ajax_load_cities', data: { 'countries': countryId // add the country id to the GET parameters }, dataType: 'json', success: function (data) { // here data comes from url output or load_cities function $("#preview-items").html(data.tags); } }); }); </script> In the same template.html I defined a section like: <div id="preview-items"> {% for item in itemslist %} <label class="btn btn-primary mr-1"> <input type="checkbox" id="checklist" value="{{ item.0 }}"> <span> {{ item.1 }} </span> </label> {% endfor %} </div> and load_cieties: def load_cities(request): .... data = { 'tags': list(cities) } return JsonResponse(data) My Question: How to pass data.tags which is a list of tuples to section as a parameter that within which I be able to style list items as I already defined in ? data.tags is something like [(id1, name1), (id2, name2), (id3, name3), ..] The problem is $("#preview-items").html(data.tags); line which rather than passing list, replaces list in the <div> so at the moment I have something like: id1name1,id2name2,id3name3,...