Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SeleniumBase Django Integration
I recently stumbled across a way to make selenium faster using SeleniumBase. I am working on a website that has to parse a google shopping page. It uses selenium to wake the page up because there is javascript on the page and it uses BeautifulSoup to parse the page contents... and it's slow. I have been trying for a few days now to integrate Django and SeleniumBase with no luck. The Django views combined with the class structure of selenium base is stretching my knowledge of raw python. I have a function at the bottom of my code that parses the page content that includes SeleniumBase and BeautifulSoup and a call of the function and forloop at the top to loop through the contents. I have gotten several error messages and I still think I am far away from the solution so I don't feel there is a need to post them here because none seemed too significant. Any help is greatly appreciated. P.S. I am slightly new to django and python and really new to Selenium and SeleniumBase def home(request): form = SearchForm(request.POST or None) if form.is_valid(): form.save() if request.POST: for google_post in google_initiate(request, self): #Do some stuff #Make … -
How to retrieve the method of a Django model by specifying parameters in the URL with REST framework?
I have a model Account with a ForeignKey user and a method total_value() that returns a float64. I would like to GET the float value by entering the account and user primary keys as parameters in the URL. To do that I catch parameters with request.query_params and select the desired Account object but the framework throws an error. What amI missing ? https://mysite/api/widget/total/?account=1&owner=1 'Account' object is not iterable Please find my code below. models.py class Account(TimestampedModel): name = models.CharField(max_length=20, null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def total_value(self): return do_stuff(self) serializer.py class TotalAssetsValueSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('total_value',) view.py class TotalAssetsValueView(viewsets.ModelViewSet): serializer_class = TotalAssetsValueSerializer http_method_names = ['get'] def get_queryset(self): user = self.request.query_params.get('user') account = self.request.query_params.get('account') return Account.objects.get(pk=account, user=user) I'm sure there an account with pk=1 and user=1, so maybe my mistake is that I return an object not a queryset. Unfortunnatly when I filter instead of get it return []. -
django.core.exceptions.ImproperlyConfigured: Set the DB_USER environment variable
This project was working good until I reinstalled django-environ to make DB_USER, exc After I tried to execute and I had this error ... settings.py from pathlib import Path import os import environ env = environ.Env( #Set casting, default value DEBUG=(bool, False) ) READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False) """if READ_DOT_ENV_FILE: environ.Env.read_env()""" #reading .env file #environ.Env.read_env() #False if not in os.environ DEBUG = env('DEBUG') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') DATABASES FROM settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env("DB_NAME"), 'USER': env("DB_USER"), 'PASSWORD': env("DB_PASSWORD"), 'HOST': env("DB_HOST"), 'PORT': env("DB_PORT"), } } .env file it is located at the same directory like settings.py DEBUG=False SECRET_KEY='KEY' DB_NAME=DB DB_USER=USER DB_PASSWORD=PASSWORD DB_HOST=HOST DB_PORT= And error File "D:\CRM\web\settings.py", line 96, in <module> 'USER': env("DB_USER"), File "D:\CRM\env\lib\site-packages\environ\environ.py", line 197, in __call__ return self.get_value( File "D:\CRM\env\lib\site-packages\environ\environ.py", line 407, in get_value raise ImproperlyConfigured(error_msg) from exc django.core.exceptions.ImproperlyConfigured: Set the DB_USER environment variable (env) -
AssertionError encrypt in django
so i want to encrypt text to audio mp3. but when i run the code, there's error message Exception Type: AssertionError. and it's say there's error at assert len(key) == key_bytes can someone please check what's error with the function? i want encrypt using AES 128 and 256, please help me. from Crypto.Cipher import AES from Crypto.Util import Counter from Crypto import Random import binascii key_bytes = 16 # Takes as input a 32-byte key and an arbitrary-length plaintext and returns a # pair (iv, ciphtertext). "iv" stands for initialization vector. def encrypt(key, testaudio): assert len(key) == key_bytes print(testaudio) print(key) # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key, AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(testaudio) print(iv) print(ciphertext) return (iv, ciphertext) -
django authentication model - login with emailed link?
Is there a way to set up the django authentication model where, instead of a password, users put in their email address, and then are emailed a link that they click on to login with? If so, are there any tutorials on how to set this up? -
Import "phonenumber_field.modelfields" could not be resolved
I have django project and I try to add phonenumber package, I've done 'pip install django-phonenumber-field[phonenumbers]' and I imported the library to my .models but it shows up as an error but it works anyways, the error is called: "Import "phonenumber_field.modelfields" could not be resolved(reportMissingImports)" how do I fix the problem so it won't tell me its a problem and will work like everything else? Please help :3 my code and error -
MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled - DJANGO + REACTJS
I have a django + reactjs application that I have deployed in digitalocean app platform. I am using the production build, made with command npm rub build, of reactjs and serving it with the django. I am using digitalocean spaces for static and media files sotrage and serving. Now after deployment I am getting the following errors in the console: Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. efused to execute script from 'https://solvelitigation.com/static/js/main.a796034b.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Manifest: Line: 1, column: 1, Syntax error. Refused to apply style from 'https://solvelitigation.com/static/css/main.e8b3c255.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. Because of the above errors nothing is being rendered in the page. I have no idea why this is happeing and how to solve them. Please suggest to me how to solve this.I have tried a number of solutions from … -
Git deleted my files while pull. How to restore the files?
Git deleted my files while pull. the deleted files were not committed. How do I restore that files back into my working directory? I have attached a screenshot for your reference. screenshot here -
Comment resolver ce bug?
NoneType' object has no attribute 'utcoffset Request Method: GET Request URL: http://127.0.0.1:8000/admin/events/evenement/add/ Django Version: 4.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'utcoffset' Exception Location: C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\timezone.py, line 256, in is_aware Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\lenovo\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Python Path: ['C:\web', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf', 'C:\Users\lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\odf'] Server time: Sun, 21 Aug 2022 17:51:06 +0000 -
Django pass variable to Python script
I have a Django app, with 2 pages: index.html and device_list.html Index page: <div class="search"> <form action="" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="text" class="input" name="UserInput"> </form> </div> <div class="btn"> <button class="btns" onclick="location.href='{% url 'script' %}'">Generate</button> </div> </div> here is device_list.html page: {% extends "base.html" %} {% block content %} {{output}} {% endblock content %} Views.py: def index(request): return render(request, 'index.html') def device_list(request): if request.method == 'POST': form = SiteCodeForm(request.POST) if form.is_valid(): command = ["python","run.py","VARIABLE" ] process = Popen(command, stdout=PIPE, stderr=STDOUT) output = process.stdout.read() print(output) ----- IM STUCK HERE ----- So I don't know how to proceed, and pass the variable from index page to the python script that I have in views. It actually runs the script, and I can see the result in the terminal, but the output won't show up in the device_list.html - it's empty. -
Django : NoReverseMatch
Im having issues with indexing inside reference point in url. I have quite complicated nested object of two raw quries and string inside tuple inside list. Point is that referencing sometimes works and sometimes does not and I don't really get why. This piece of html works really well. <td><a href="{% url 'company_info' pair.0.0.0.ticker %}">{{pair.0.0.0.ticker}}</a></td> But this one fails <td><a href="{% url 'company_info' pair.1.0.0.ticker %}">{{pair.1.0.0.ticker}}</a></td> What's more django properly renders this : <td>{{pair.1.0.0.ticker}}</td> But has problem with this one : <a href="{% url 'company_info' pair.1.0.0.ticker %}"> Which really indexes the same object. So in one place its ok and in another it fails. What might be causing that? Sorry if its a little bit messy explanation but html its not really my thing and I might lack some vocabulary. Best! -
Initialize django ModelForm user field with current logged user
I'm trying to initialize some fields of my NewArticleForm with static data. In particular, I want to set the author field with the current logged user/author, and shouldn't be modifyable. This page is reachable only from logged user, and the information is also stored in the url: path('<int:user_id>/create', views.add_article, name='insert'), forms.py: class NewArticleForm(forms.ModelForm): class Meta: model = Article fields = ['author','title', 'content', 'pub_date'] pub_date = forms.DateTimeField(initial=timezone.now()) def save(self, commit=True): article = super(NewArticleForm, self).save(commit=False) if commit: article.save() return article models.py: from django.db import models from django.contrib.auth.models import User class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() title = models.CharField(max_length=50) content = models.TextField() def __str__(self): return self.title def get_year(self): return self.pub_date.year def get_month(self): return self.pub_date.month views.py: @login_required def add_article(request, user_id): if request.method == 'POST': form = NewArticleForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Articolo inserito con successo!') return redirect('/blog_app/') else: messages.warning(request, 'Qualche campo non è corretto, operazione fallita.') form = NewArticleForm() return render(request, template_name='blog_app/insert.html', context={'insert_form':form}) How can I set author with the current logged user? Bonus question: Why pub_date field, which is a DateTimeField, is displayed as text type? I can't change it. -
Default tabular inline to a, b ,c & d
I want to default my tabular inline form to A B C D class AnswerInline(admin.TabularInline): model = Answer extra=4 -
IntelliJ IDEA not loading dependencies from docker compose - python django
I have set up a remote interpreter from the docker-compose option for a Django project. Still, it is showing me red squiggly lines under the package imports. How can I fix this? docker-compose.yml services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:14.5-alpine3.16 volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: Code ss Docker ss Docker config ss -
Calling same celery task multiple times in Django
I am totally new to celery and trying to call the same celery task multiple times parallel. Basically, my task creates some data in an external third-party app through API and export created data with a third-party generated id. Now if I run the same tasks multiple times, third-party generated id changes to the latest instance of the task. Can I know how can I solve this issue? I tried saving the third-party generated id with task id in the results backend, but then how to do I, access this data form results backend? Is there any other way to do it? -
Django - button redirecting to {% url 'index' %}
I can't find any solution on any article so I'm asking here. I'd like to make button which is gonna redirect user to specific url. I have already did it this way: <button onclick="location.href='create_recipe/'" type="button" >Create new Recipe</button> but instead of passing whole link I'd like to use {% url 'some_view' %} but I do not have an idea how I should do that. Is it even possible to do that ? It has to be <button>, edit: something like: <button type="button" class="btn btn-outline-secondary"><a href="{% url 'index' %}">Create new Recipe</a></button> also does not work -
What to use for building a chat based on js and webhooks?
I'm building a Django application with Myzap as free whatsapp REST API backend. How to build a chat on a HTML by using some jquery plugin and receive messages based on webhooks? Is there any free plugin to do this? -
Django ArrayAgg- unsupported lookup error
Here are my models simplified, only essential fields. class Employee(Model): /*some fields */ class EmployeeConnection(Model): manager = models.ForeignKey('employee.Employee', related_name="manager_connection") class EmployeeGrouper(Model): group = models.ForeignKey("EmployeeGroups") connection = models.ForeignKey("EmployeeConnection") ArrayAgg gives me the next error: Unsupported lookup employeegrouper_set for AutoField or join on the field not permitted .annotate( group_ids=ArrayAgg( 'employee__manager_connection__ employeegrouper_set__group' ) can anyone help me to understand why 'employee__manager_connection_id' works good in ArrayAgg , but 'employee__manager_connection__employeegrouper_set__group' this one doesnot? And how to make it work? -
How do i manually accept a users sign up request in a social media website using django?
So im working on building a user verification form , so what's supposed to happen is that' - - User will come & sign up in the website After signing up the user's details will be sent to a moderator Moderator will manually reiew the details & then he'll be allowed to join the website Please help me out with the approach to tackle this situation -
Why django runserver command starts 2 processes? What are they for? And how to distinguish between each in the code?
While building some standalone Django app, which will be running tasks in the background as a separate daemon Thread, I ran into a problem because it seemed as if there are two MainThreads when starting the Django server, each Thread has a different id. After digging more into the problem, it turned out that it's because it's actually two processes. Experiement: Run django-admin startproject example && cd example to start a new project. Edit example/settings.py adding imoprt os if it's not already imported and then add the line print(f"Current processes ID:{os.getpid()}") Run python manage.py runserver and look at the output Current processes ID:426286 Current processes ID:426288 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 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 21, 2022 - 15:30:42 Django version 2.2.12, using settings 'example.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Change any file (for example just add a new line to settings.py) and save and look at the output /pathtoproject/example/example/settings.py changed, reloading. Current processes ID:426417 Watching for file … -
I want to create a user in django but create_user() method doesn't work
I'm trying to create a user using create_user method but it's not working and not showing any errors in my views.py I have the following code from django.contrib.auth.models import User from django.views import View from django.shortcuts import render, redirect from django.contrib import messages class Signup(View): def get(self, request): return render(request, 'myqpp/signup.html') def post(self, request): username=request.POST.get('username') pas = request.POST.get('password') email = request.POST.get("email") user = User.objects.create_user(username, email, pas) user.save() return redirect('/signin/') class Signin(View): def get(self, request): return render(request, 'myapp/signin.html') def post(self, request): username = request.POST.get('username') pas = request.POST.get('password') user = authenticate(username=username, password=pas) if user is not None: login(request, user) print('Success') return redirect('/', context={"user":user}) else: print('Failed') messages.error(request, 'Bad Credentials') return redirect('/signin/') I always get the message "Bad credentials" and when I review the Users table in django admin/ page it shows that there is no new user added When I click the submit button on the signup page, console log is like this [21/Aug/2022 15:31:50] "GET /signup/ HTTP/1.1" 200 3907 Failed [21/Aug/2022 15:32:07] "POST /signin/ HTTP/1.1" 302 0 [21/Aug/2022 15:32:07] "GET /signin/ HTTP/1.1" 200 3304 I don't know what is the problem as it's not showing any errors This is myqpp/urls.py from django.urls import path from . import views urlpatterns = [ path('', … -
Page not found. Django blog page not rendering
I am new to Django and learning this python framework. I have created a virtual environment called Virtual_Django_Project and installed Django in it. Moving ahead I created folder called Django_project and added an app called blog you can see my files here File Directories. Error >Page not found at /blog/ blog.views.py Code from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('Home') blog.urls.py Code from django.urls import path from . import views urlpatterns = [ path('', views.home, name ='blog-home'), ] Main Django_Project.urls Code from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('blog.urls')), ] Can anyone tell me why my blog page is not opening and showing the error page not found? PS: Server is running in cmd. -
Error 111 connecting to 127.0.0.1:6379. Connection refused. cPanel (Django)
I'm using django-redis for caching. Everything works fine on local, but I got an error on production development (using cPanel). Does anyone know how to use django-redis on the production server? -
(django) I want to update it after registering the picture, but the picture doesn't come up whenever I update it
I'm making a review function, but if I register a picture in the review and update it, the picture doesn't come up properly. However, other writing contents are updated well. I don't know why only the picture doesn't show properly. here is view.py: def update(request, id): review = Post.objects.get(id=id) category = review.postType placeId = review.placeId if category == 'cafe': place = Cafe.objects.get(id=placeId) elif category == 'accomo': place = Accomodation.objects.get(id=placeId) else: place = Place.objects.get(id=placeId) if request.method == "POST": postGood = request.POST["postGood"] postBad = request.POST["postBad"] try: postImage = request.FILES['postImage'] except: postImage='NULL' ranking = request.POST["ranking"] Post.objects.filter(id=id).update(postGood=postGood,postBad=postBad,postImage=postImage,ranking=ranking) posts = Post.objects.filter(Q(postType=category)&Q(placeId=placeId)) total = 0 len_posts= len(posts) for p in posts: total += p.ranking place.star = total/len_posts place.save() return redirect(f"/reviewDetail/{review.id}") placeName = place.name location = place.location context = {"review":review, "placeName":placeName} return render(request, "reviewUpdate.html", context=context) here is update.html: def update(request, id): review = Post.objects.get(id=id) category = review.postType placeId = review.placeId if category == 'cafe': place = Cafe.objects.get(id=placeId) elif category == 'accomo': place = Accomodation.objects.get(id=placeId) else: place = Place.objects.get(id=placeId) if request.method == "POST": postGood = request.POST["postGood"] postBad = request.POST["postBad"] try: postImage = request.FILES['postImage'] except: postImage='NULL' ranking = request.POST["ranking"] Post.objects.filter(id=id).update(postGood=postGood,postBad=postBad,postImage=postImage,ranking=ranking) posts = Post.objects.filter(Q(postType=category)&Q(placeId=placeId)) total = 0 len_posts= len(posts) for p in posts: total += p.ranking place.star = total/len_posts place.save() … -
Django/Python thread returns --> TypeError: 'str' object is not callable
I have the following thread that returns the error TypeError: 'str' object is not callable # traceback Exception in thread Thread-164: <Thread(Thread-162, started daemon 6162526208)> Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner [21/Aug/2022 14:29:36] "GET /tentacle/ HTTP/1.1" 200 24 self.run() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) TypeError: 'str' object is not callable # threads.py def post_publisher_thread(): """ A thread that executes the post publisher """ t = threading.Thread(target=run_post_publisher()) t.start() print(threading.current_thread()) with run_post_publisher being a function inside utils.py. Why is this error popping up? I also checked these answers but it seems I don't pass strings, but a function to the target parameter already.