Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Granting a user access to view data based on their permissions
I have a basic CRUD web application in Django using a database with Postgres 12 that simply displays articles based on a search. I need to implement a system such that the articles returned from a user's search are articles that the user only has access to. For example, if my articles table article is populated id|title|summary|source |category --+-----+-------+--------+-------- 0 |... |... |NYTimes |politics 1 |... |... |BBC |environment 2 |... |... |BBC |politics 3 |... |... |Wired |technology 4 |... |... |NYTimes |fashion If a user makes a search, but only was granted access to view sources NYTimes and BBC as well as only categories politics, then the the user would only see id|title|summary|source |category --+-----+-------+--------+-------- 0 |... |... |NYTimes |politics 2 |... |... |BBC |politics Right now I implemented this schema. |user_group| |data_permission| |id |-----|group_id | |name | |column | |value | and use this raw query to filter the results. SELECT * FROM article a INNER JOIN data_permission p0 ON p0.group_id = %s AND p0.column = 'source' AND p0.value = a.source INNER JOIN data_permission p1 ON p1.group_id = %s AND p1.column = 'category' AND p1.value = a.category; It's a simple problem, but I'm having trouble understanding if … -
Django/PyCahrm. Relocation project to another PC with /venv can`t find `dotenv` module and can`t to install it
I relocate my Django project (mysite) with /venv to another Computer. On first computer it works good. And where was istalled 'dotenv' module. In PyCharm i set my Project Interpreter as: Python 3.7 (mysite) C:\Users\User\mysite\venv\Scripts\python.exe But 'python manage.py runserver' in new computer raises: ModuleNotFoundError: No module named 'dotenv' But in ../mysite/venv/Scripts presence file dotenv.exe. And sobfolder ../venv/lib/site-packages/dotenv/ too. In PyCharm-Settings-Project Interpreter in Package list presense python-dotenv 0.14.0 Ok. I try to install dotenv by pip, but it raise error: C:\Users\User\mysite\mysite>pip install dotenv Collecting dotenv Using cached https://files.pythonhosted.org/packages/e2/46/3754073706e31670eed18bfa8a879305b56a471db15f20523c2427b10078/dotenv-0.0.5.tar.gz Complete output from command python setup.py egg_info: Command "python setup.py egg_info" failed with error code 1 in C:\Temp\pip-wheel-4a1x88l2\distribute\ Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\installer.py", line 126, in fetch_build_egg subprocess.check_call(cmd) File "C:\Users\User\Anaconda3\lib\subprocess.py", line 347, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['C:\\Users\\User\\Anaconda3\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', 'C:\\Temp\\tmpz_ip4m3r', '--quiet', 'distribute']' returned n on-zero exit status 1. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Temp\pip-install-07by3weo\dotenv\setup.py", line 23, in <module> scripts=['scripts/dotenv'] File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\__init__.py", line 152, in setup _install_setup_requires(attrs) File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\__init__.py", line 147, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "C:\Users\User\Anaconda3\lib\site-packages\setuptools\dist.py", line 676, in fetch_build_eggs replace_conflicting=True, File "C:\Users\User\Anaconda3\lib\site-packages\pkg_resources\__init__.py", line 766, in resolve … -
Translating URL patterns in Django
I am trying to internationalize a dictionary Django web application and I am having problems with translating URLs. Here is my project's urls.py: from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = [] urlpatterns += i18n_patterns( path(_('dictionary/'), include('dictionary.urls')), ) Here is my app's urls.py: from django.utils.translation import gettext_lazy as _ app_name = "dictionary" urlpatterns = [ path("", views.index, name="index"), path(_("define"), views.define, name="define"), path(_("define/<slug:headword_slug>"), views.headword, name="headword"), ] I have translated and compiled all the necessary files in my locale folders for both the project and app. When I change the language prefix in the URL, templates, forms, and various error messages are all translated very successfully. However, even though the language of the content changes, my URL patterns are always displayed in English. What am I doing wrong? -
UnboundLocalError at /index/register/ .local variable 'context' referenced before assignment
local variable 'context' referenced before assignment.I need a explaination Views.py from django.shortcuts import render from memoster.forms import UserForm, UserProfile from django.http import HttpResponseRedirect, HttpResponse # ----LOGIN---- # from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.urls import reverse def home_index(request): return render(request, 'home_index.html') def index(request): return render(request, 'index.html') def register(request): if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfile(data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user profile.save() else: print(user_form.errors, profile_form.errors) else: user = UserForm() profile = UserProfile() context = {'user': user, 'profile': profile} return render(request, 'registration.html',context) def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('memoster:index')) else: return HttpResponse("Account Not active") else: print("username{} and password {}".format(username, password)) print("Invalid credentials") else: return render(request, 'login.html') @login_required def user_logout(request): logout(request) return HttpResponseRedirect(reverse('home_index')) traceback enter image description here Request Method: POST Request URL: http://127.0.0.1:8000/index/register/ Django Version: 3.1.1 Exception Type: UnboundLocalError Exception Value: local variable 'context' referenced before assignment Exception Location: C:\Users\Faris\PycharmProjects\djangoProject3\memoster\views.py, line 40, in register Python Executable: C:\Users\Faris\PycharmProjects\djangoProject3\venv\Scripts\python.exe Python Version: 3.8.3 Python Path: ['C:\Users\Faris\PycharmProjects\djangoProject3', 'C:\Python38\python38.zip', 'C:\Python38\DLLs', 'C:\Python38\lib', 'C:\Python38', 'C:\Users\Faris\PycharmProjects\djangoProject3\venv', 'C:\Users\Faris\PycharmProjects\djangoProject3\venv\lib\site-packages'] -
SMTP Connection failed unexpectedly Django Email Message
I am using trying to send emails to 500 contacts by iterating over each. The reason is send_mass_mail won't work for over 100 emails. Below is my code for e in data: email = EmailMessage( 'subject', 'body', 'myemail@gmail.com', e, headers={'Message-ID': 'foo'}, ) email.send() While it works perfectly for around 100 emails, I get this error when I tried 500 emails Exception while running run() in 'inventory_management.scripts.many_load' Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\email_notifications.py", line 65, in run_from_argv super().run_from_argv(argv) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\email_notifications.py", line 77, in execute super().execute(*args, **options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\utils.py", line 62, in inner ret = func(self, *args, **kwargs) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\commands\runscript.py", line 283, in handle run_script(script_mod, *script_args) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django_extensions\management\commands\runscript.py", line 161, in run_script exit_code = mod.run(*script_args) File "D:\Work\Others\BTech\SCode\emporium_apparel\inventory_management\scripts\many_load.py", line 48, in run print(email.send()) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "D:\Tools\Anaconda\envs\heroku_env\lib\site-packages\django\core\mail\backends\smtp.py", line 69, in open self.connection.login(self.username, self.password) File "D:\Tools\Anaconda\envs\heroku_env\lib\smtplib.py", line 698, in login self.ehlo_or_helo_if_needed() File … -
django - How can I add different AppConfigs for testing different apps?
In my project I have two apps: main_app and reusable_app. reusable_app is supposed to be independent and reusable in other projects. It has its own models and signals. And I connected a lot of these signals to receivers in main_app. Doing ./manage.py test runs tests for both main_app and reusable_app. But the tests for reusable_app break when the signals are called because data needed for main_app to process these signals is not there. I don't want to have to load/setup data for main_app in reusable_app's tests. So, the solution would be to disconnect the signal receivers. Also, reusable_app tests should not have to know about disabling any signal receivers. I can create different AppConfigs that selectively connect or not these signal receivers. But how do I change the AppConfig depending on which app I'm running the test for? -
How to display Foreignkey Data in Django html page?
I want to get data from related foreign-key models, but I am unable to get data from the related model, Please let me know how I can do it. I want to display name value from Model2 table.. here is my models.py file... class Model1(models.Model): name=models.Charfield(blank=True) class Model2(models.Model): name=models.CharField(default=None) model1=models.Foreignkey(Model1, related_name='model_one', on_delete=models.CASCADE) here is my views.py file... def display_data(request, id): test_display=Model1.objects.filter(pk=id).first() return ender(request, 'page.html', {'test_display':test_display}) here is my test.html file where i am displaying name from Model2 table <p>{{test_display.model_one.name}}</p> -
Dynamic price range filter in Django
I have a product model with attributes name, price, description, category. I want to create a dynamic price range filter with check boxes in the view. for example if I query my product like below: get_products = Product.objects.filter(category='Men') Now if the above query has a list of products with min_price = 500 and max_price=5000 then I would like to have 4 set of price range filters like below: 1)500-1500 2)1501-2500 3)2501-3800 4) 3801-5000 But the above should be dynamic based on min and max price value. I have tried to use range(min,max,steps) but it is very difficult to generate a dynamic price range filter. Any help is highly appreciated. -
How to use mailgun post for callback
I am trying to retrieve MailGun event data into my Django application but when I try and parse this I keep getting a type error or None object error. What is the correct way of parsing this? I have tried the below but it returns a TypeError: 'NoneType' object is not subscriptable: def mailgun(request): event_data = request.POST.get('event-data')['event'] This is an image of a postbin that receives a webhook request: What is the correct way of using a mailgun response? -
Heroku Django Celerey: raised unexpected: ValueError Server 500 error
I am trying to schedule some tasks one Django celery on my Heroku application however, I have got an error: raised unexpected: ValueError('Redis URL must specify one of the following schemes (redis://, rediss://, unix://)',) Now for your reference, I have three settings files for my production and development environment with a common one. My app is called register and the file containing the wsgi.py is: register -settings ----common.py ----production.py ----development.py -celery.py -wsgi.py Now in my production.py file I have: from register.settings.common import * import os from urllib.parse import urlparse import django_heroku DEBUG = False ALLOWED_HOSTS = ['mysite.herokuapp.com','wwww.mysite.com','mysite.com'] #EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') #EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') redis_url = urlparse(os.environ.get('REDISTOGO_URL', 'redis://localhost:6959')) CACHES = { 'default': { 'BACKEND': "django_redis.cache.RedisCache", 'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port), 'OPTIONS': { 'DB': 0, 'PASSWORD': redis_url.password, } } } CELERY_BROKER_URL=os.environ.get('REDISTOGO_URL') CELERY_RESULT_BACKEND=os.environ.get('REDISTOGO_URL') CELERY_BROKER_TRANSPORT_OPTIONS = { "max_connections": 2, } STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals(),logging=False) And in my celery.py file I have: from __future__ import absolute_import import os from celery import Celery from django.conf import settings import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'register.settings.production') app = Celery('register') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) I do not know what is causing this error as when I do heroku config I can see that the config vars are set correctly. This is also … -
How to deal with duplicate apps in Django project?
I downloaded a django project folder and am trying to run the project. I created a virtual environment, installed the requirements.txt and tried the python manage.py runserver command but it returned with populate() isn't reentrant error. After looking at some other answers on stack overflow, i got proper traceback and got this instead: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: admin But these are my installed apps and there are no duplicates: `INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_user_agents', 'haystack', 'home', #'TNI', #'analytical']` How do I fix this? Am I missing some steps? -
Django ModuleNotFoundError: No module named 'mysite.settings' when trying to host application with wsgi server
So I wanted to deploy my first django application on a cherryPy webserver using wsgi. And I have issues with os.environ['DJANGO_SETTINGS_MODULE']. When trying to run application callable it throws error, that module is not found. Project structure: ResourceManager ResourceManager ResourceManager __init__.py cherryserver.py settings.py urls.py wsgi.py SimpleResourceManager migrations __init__.py admin.py apps.py models.py serializers.py tests.py urls.py views.py manage.py wsgi.py file: import os import sys from django.core.wsgi import get_wsgi_application BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,BASE_DIR) os.environ['DJANGO_SETTINGS_MODULE'] = 'ResourceManager.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ResourceManager.settings') application = get_wsgi_application() cherryserver.py: import cherrypy from ResourceManager.ResourceManager.wsgi import application if __name__ == '__main__': # Mount the application cherrypy.tree.graft(application, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server object server = cherrypy._cpserver.Server() # Configure the server object server.socket_host = "0.0.0.0" server.socket_port = 8080 server.thread_pool = 30 # Subscribe this server server.subscribe() cherrypy.engine.start() cherrypy.engine.block() Application works fine when using command runserver 8080, but when i tried to run it on different server. It says ModuleNotFoundError: No module named "ResourceManager.settings". So i tried: Change where cherryserver.py is located in directory, I have added additional lines of code to wsgy.py file and I'm running out of ideas what is wrong when I'm deploying my app on different server. Why I'm using cherryPy, well I have … -
nginx/django/uwsgi: can't load admin static css files
I have searched extensively and found many similar/related questions, none of the answers/suggestions solve my problems. I'm trying to describe my problems as in details as possible. Please bear with me for my lengthy post. I'm following the steps in the document https://docs.djangoproject.com/en/3.1/intro/ to create the polls app under mysite project and the app works as expected when I run "python manage.py runserver 0:8000" (accessed as http://hostname:8000/) to serve the pages. But I get problems when I run nginx and uwsgi (use port 80 and socket) to serve pages. There're no errors and I can access all pages. But the admin page (http://hostname/admin/) doesn't display properly as if no css files in effect. My project root is /data/webapps/mysite and I have the following codes in nginx.conf. location /static { alias /data/webapps/mysite/static; # your Django project's static files - amend as required } Under the project root directory, I have directories mysite, polls, static, templates and some other files, such as manage.py (all according to the document at the link above). In mysite/settings.py, I have the following lines. STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATIC_URL = '/static/' Under the directory static, I have directories admin and polls and under static/admin, I have directories … -
Cannot get is_valid() to go back to template with bound form
In the Django docs, it says "We call the form’s is_valid() method; if it’s not True, we go back to the template with the form. This time the form is no longer empty (unbound) so the HTML form will be populated with the data previously submitted, where it can be edited and corrected as required." I am trying to get this behaviour to work. In views.py: def test(request): if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): return redirect('auctions/test.html') else: form = TestForm() return render(request, 'auctions/test.html', {'form': form}) In forms.py: class TestForm(forms.Form): testnumber = forms.DecimalField(max_digits=1) In test.html: <form action="{% url 'auctions:test' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> Now, when I submit the form with a number that is more than 1 digit, is_valid() evaluates to False. When that happens, the docs says the template should be rendered with the bound form and the error. Instead, nothing happens, and I get ValueError: The view auctions.views.test didn't return an HttpResponse object. It returned None instead. -
Python Django saved posts computed method
Assuming im using the default django model, a Post model (code below) and a SavedPost model that links a User to a Post (if the certain user with the certain post exists then that post is saved for that user) and a Follower model that links 2 user (similar to SavedPost). What im trying to do: An API that for a user, they get all posts for the users they follow, in addition each of these posts has an extra 'field' to say if that post is saved or not. class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post_type = models.CharField(max_length=1, choices=[('B', 'Blog'), ('V', 'Video')], default='B') file_path = models.URLField(null=True) title = models.CharField(max_length=255) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class SavedPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Meta: # A user can save a post only once. unique_together = ('user', 'post') class Follower(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower") created_at = models.DateTimeField(auto_now_add=True) class Meta: # A user can follow another user only once unique_together = ('user', 'follower') API View: @permission_classes([IsAuthenticated,]) @api_view(['GET']) def get_following(request): user = request.user following = Follower.objects.filter(follower=user).values('user') # saved_posts = SavedPost.objects.filter(user=user, post__user__in=following).order_by('-post__created_at') posts = Post.objects.filter(user__in=following).order_by('-created_at') serializer = PostSerializer(posts, … -
The include tag in Django isn't working properly
so I have a lot of repeated code in my templates and one of them are the link tags for CSS in my html templates. Since they are all similar i put them in a separate file and used the include method like this {% include 'path to file' %} the problem is when running the website is that the page is not using any of the CSS and what's confusing even more is that if i view the page source on chrome it shows that all of the CSS link tags are there. so how can i fix this ? -
Django returning old value for update User
I've created a simple on a settings page. It contains a few basic data such as First Name, Last Name (default Django User model) and then it links to a One to One model called Profile, which have more fields such as Address, City and State. I update it as follows in my views: def post(self, request): try: data = request.POST user_data = User.objects.get(id=request.user.id) first_name = data['first_name'] last_name = data['last_name'] phone = data['phone'] address = data['address'] address_two = data['address_two'] city = data['city'] state = data['state'] zip = data['zip'] country = data['country'] user_data.first_name = first_name user_data.last_name = last_name user_data.profile.phone = phone user_data.profile.address = address user_data.profile.address_two = address_two user_data.profile.state = state user_data.profile.city = city user_data.profile.zip = zip user_data.save() return render(request, 'pages/settings_profile.html', context={'success': "Settings updated"}) except Exception as e: print(e) print('error') return render(request, 'pages/settings_profile.html', context={'error':"Oops, an error occured saving your settings. If this keeps happening, please screenshot this and contact support."}) So this saves 100% fine.. however as the the page reloads after submitting, everything would be updated, except the first_name and last_name... but then when I refresh the page it then returns the new data. Why would the One to One fields update on my template on initial page load after saving, … -
Django: Default file serving doesn't work correctly
I'm trying to make a simple system which lets the users to change their profile pictures. So basically when the user uploads any new image the system works as it should, but I added a function which sets the default picture with: profile_pic = models.ImageField(null=True, blank=True, default='profile_pic1.png') When I create a new user I can see this view in the new user settings: After I upload the new image I can see this (The image is rendered correctly, I can see it displayed): This is the error: My settings.py MEDIA_ROOT = os.path.join(BASE_DIR, '') MEDIA_URL = '/images/' Also, I'm using nginx, and this is the line which I included, but I don't think that it's working. location /media/ { alias /home/interkodas/interkodas_web/images/; } -
Prevent multiple submits in django form - setAttribute disable to false is not triggered
I'm trying to prevent users from clicking the submit button more than once on a django form. My form looks like this: <form method="post" autocomplete="off" enctype="multipart/form-data" id="expense-form"> {% csrf_token %} {{form}} <button id="expense-submit-button" class="uk-button uk-button-secondary uk-button-small" type="submit"> <span id="spinner-payment-button" class="spinner-border spinner-border-sm spinner-js"></span> Submit </button> </form Then in a script tag on the same template I got this document.getElementById("expense-form").addEventListener('submit', functSubmit); function functSubmit(event) { var button = document.getElementById("expense-submit-button") var spinner = document.getElementById("spinner-payment-button") button.setAttribute("disabled", true) spinner.classList.remove("spinner-js"); } When I hit the submit button, the form saves as usual, but the "disabled" attribute is never applied and the user can still click "submit" multiple times which results in multiple records in my db. Why isn't the event listener triggered? The reason I need this is because I got a form that takes some time to process (a few seconds) and I just need to signal to the user that its actually working as expected. -
How do i change the logged out redirect page?
Im currently trying to finish my learning log app using python and django , but i keep having a small error(if i could call it that way) . Whenever i log out from the website i get redirected to the default django logged out page : I have created a logged_out.html file and its located in the same folder as botht the registration one and login . I think my mistake might be either in the *base.html file here: <li class = "nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log Out</a> </li> or in the settings file if i have to include something that tells what to use . Thank you in advance. -
Cannot get recover password mails in Django using webmails.It sends mail from views.py but fails in sending password recovery mail
this works fine EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '**********' this fails in sending password recovery mails but works fine while sending from views.py EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_HOST = 'mail.mydomains.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'alert@mydomains.com' EMAIL_HOST_PASSWORD = '*************' -
how to capture and send image to Django using Ajax?
I'm trying to capture image from webcam using java-script and pass the same image to the Django. I've come to know that this would require ajax to work. But apparently form data is not passed to the Django. I've also tried to append image to form data but it won't work. Is there any way to make this work? Here's my Code <html> <body> <form method="post" enctype="multipart/form-data" id="uploadimage" data-toggle="validator"> <div class="form-group"> <!-- Stream video via webcam --> <video playsinline autoplay></video> <canvas id="canvas" width="600" height="450"></canvas> <img src="" id="detect-data" name="detect-data" width="600" height="450"> </div> <div class="form-group"> <button type="submit" id="submit" class="btn btn-lg">Next</button> </div> </form> <div class="clear"></div> <!-- js --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Script to capture image from webcam --> <script> const constraints = { video: true }; // create canvas const canvas = document.getElementById('canvas'); // get image const image = document.getElementById('detect-data'); // get capture button const captureVideoButton = document.getElementById('submit'); // get video element const video = document.querySelector('video'); navigator.mediaDevices.getUserMedia(constraints). then((stream) => { video.srcObject = stream }); captureVideoButton.onclick = function () { canvas.width = video.videoWidth; canvas.height = video.videoHeight; canvas.getContext('2d').drawImage(video, 0, 0); // Other browsers will fall back to image/png image.src = canvas.toDataURL('image/jpeg'); // call ajax function to pass data to django do_ajax(image) } function do_ajax(img) { … -
Django Application has become slow ever since I connected it to an online database
The app works perfectly fast and smooth if connected to an sqlite local db but is extremely slow when connected to postgresql/mongodb. -
how can I use something from a reusable app that is implemented in the main app in django?
I have a django app that is supposed to be used by different products, so it is a reusable app. This reusable app has DRE views, but for some views, I dont want to have always the same view permissions but instead I would like the final application (the product) to implement the view permission, because they can vary. For example: from rest_framework import permissions class MyCustomPermission(permissions.BasePermission): def has_permission(self, request, view): return finalAplicationPermission(request) if finalAplicationPermission else True and then use this custom permission in my view from rest_framework import generics from reusable_app import permissions class MyView(generics.GenericAPIView): permission_classes = (permissions.MyCustomPermission,) filterset_fields = ("somefield",) Any suggestion? Thanks in advance. -
Django-React Spotify Authentication with New User
I'm setting up a Django-React app and trying to allow users to login via Spotify which then takes them to a signup page to add username, bio, etc. or takes them to their profile page if they have already signed up. What's the best way to do this? I have been trying to use Django-allauth but having difficulty using this with React and not Django templates. Thanks.