Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error after deleting app from django project
I am new to Django so please excuse my ignorance... I have been working on an e-commerce project with django in VS code. Everything was working fine until I thought I'd add an account feature. From the terminal I did a startapp account. Not long after doing this, I decided to go another route and not make an account app. So I deleted the account directory from the explorer from right clicking and selecting the delete option. Now, when I ran the server to make sure I didn't break anything, I did in fact break everything. I am using the venv and I do have my Onedrive open since the directory is saved in there. This is the error I got: (Django_projects) PS C:\Users\kylec\OneDrive\Documents\school_files\team_project\Django\bookify> py manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\kylec\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kylec\.virtualenvs\Django_projects-1wiE7bc9\lib\site-packages\django\__init__.py", line 24, in … -
How to change the background of input field with text (django form)?
I am building a form so when the button is clicked the function starts. So basically if the condition is True --> green, otherwise if False --> Red function check() { let correctAnswer = '{{ correct_answer }}'; let givenAnswer = document.getElementById('correct_answer').value; let exerciseForm = document.getElementById('form'); let form = document.getElementById('correct_answer'); if (givenAnswer === correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(76, 234, 76)'; form.style.backgroundColor = 'rgb(76, 234, 76)'; } else if (givenAnswer != correctAnswer) { exerciseForm.style.backgroundColor = 'rgb(245, 69, 69)'; form.style.backgroundColor = 'rgb(245, 69, 69)'; } }; {{ sentence }} {{ form.correct_answer }} When I don't enter any text it seems to work. When I fill in some text it doesn't work any more. -
sorting feed by engagement Django
So, I´m currently working on a Social Media application where you can share image posts. Each post can be liked, and/or disliked by each user. At the moment, the feed is sorted by most recent post, however, I would like to sort it by engagement (number_of_likes + number_of_dislikes = engagement_count --> of all users). I´m new to python and quite unsure how to start. I had a few tries of using a class model and creating a list (engagement_count) in the def index(request): in views.py but I´m quite unable to connect the dots to something that makes sense. Please help me out with some tips how to approach this... thx. Here is the code. views.py: def index(request): #user_object = User.objects.get(username=request.user.username) #user_profile = User.objects.get(user=user_object) user_following_list =[] feed = [] user_following = FollowersCount.objects.filter(follower=request.user.username) for users in user_following: user_following_list.append(users.user) for usernames in user_following_list: feed_lists = Post.objects.filter(user=usernames) feed.append(feed_lists) feed_list = list(chain(*feed)) posts = Post.objects.all() Post.objects.order_by('number_of_likes') return render(request, 'index.html', {'posts': posts}) def like_post(request): username = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) #set up a filter so that a user can only like it a post once --> disable in project to give unlimited likes and dislikes like_filter = LikePost.objects.filter(post_id=post_id, username=username).first() if like_filter == None: … -
How to connect a python discord bot with a django website and execute commands over it
How can I connect my Python Discord Bot with my Django Website to execute commands like sending a message to a channel? -
Difference between Django `BaseCommand` loggers and `logging.getLogger()`
When writing custom Django management commands, the docs recommend using self.stdout and self.stderr. class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write("Hello world!") self.stderr.write("Something went horribly wrong") I've typically used the logging module in the past: import logging logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): logging.info("Hello world!") logging.error("Something went horribly wrong") A few questions: Is there a difference between the Django BaseCommand loggers and the logging logger? Does the Django BaseCommand logger use the logging module under the hood? If so, what level does self.stdout and self.stderr use? -
S3 presigned url: 403 error when reading a file but OK when downloading
I am working with a s3 presigned url. OK: links works well to download. NOT OK: using the presigned url to read a file in the bucket I am getting the following error in console: <?xml version="1.0" encoding="UTF-8"?> <Error><Code>AuthorizationQueryParametersError</Code><Message>Query-string authentication version 4 requires the X-Amz-Algorithm, X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, and X-Amz-Expires parameters.</Message> and here is how generate the url with boto3 s3_client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'), region_name='eu-west-3') bucket_name = config("AWS_STORAGE_BUCKET_NAME") file_name = '{}/{}/{}/{}'.format(user, 'projects', building.building_id, file.file) ifc_url = s3_client.generate_presigned_url( 'get_object', Params={ 'Bucket': bucket_name, 'Key': file_name, }, ExpiresIn=1799 ) I am fairly new to use s3 buckets so I am not sure what is wrong here, and searching around on SO and online has not been very helpful so far. Could anyone point me in the right direction? -
django views.py render difference in localhost and server
I have a problem with Django on the server side. everything is ok with the local host. but after uploading project files to the server some context of one app views.py are rendering differently. (the desired form is like local host numbers.) context.update({ 'data_u': around(array([mean(ui), std(ui), skew(ui), kurtosis(ui, fisher=False), mean(uf), std(uf), skew(uf), kurtosis(uf, fisher=False)]), 4), 'filtered_file': filtered_file, }) return render(request, 'filteration/statistics.html', context=context) on local host: on server: Also, the dynamic download link does not work on the server and I am not able to get the true URL of the file. I have used filtered = Despiking.objects.get(user=user, project_name=project_name) filtered_file = filtered.excel_file.url on localhost and it works ok. but in the server, I get an empty string. what I am doing wrong? -
How do I fix a error request in django python?
We have this problem in Django3: no1 = request.GET.get('no1') no2 = request.GET.get('no2') this output the message int the port: no1 = request.GET.get('no1') AttributeError: 'WSGIRequest' object has no attribute 'get' The solution with only .get('no..') or .GET('no...') is not useful, it outputs: TypeError at /result 'QueryDict' object is not callable -
Django API test.py 'TypeError: 'str' object is not a mapping'
I'm trying to write tests for a Django API, but I'm getting this error: TypeError: 'str' object is not a mapping Test.py class ProteinFamilyTest(APITestCase): def test_proteinFamilyReturnSuccess(self): proteinFamily = ProteinFamilyFactory.create(pk=1, domain="PF00360") url = reverse('ProteinFamilyDetail', kwargs={'pk':1}) response = self.client.get(url, follow=True) response.render() self.assertEqual(response.status_code, 200) What am I doing wrong? -
Django or Flask?
I am trying to build a webpage app that allows easy access to a tool that I built in python. The tool currently takes in csv files and then processes them and outputs a data frame with all necessary information. I guess I ultimately want a web app that allows a user to select csv files from their desktop and then outputs the data frame on the same page. What is the best software to do this? -
json loop from model in Django
How would I be able to create a loop on items, to further build up more items values. this is how my json looks, just not sure on the on the loop part to add extra items to the json_data so 1 or 20 items could be sent json_data = { 'data': { 'type': 'Delivery', 'customer_feedback': None, 'warehouse_address': None, 'items': [ { 'id': '5b22055510c92b1a046ece21', 'sku': '12387654', 'quantity': 8, }, { 'id': '5b22055510c92b1a046ece06', 'sku': '12387654', 'quantity': 5, }, ], }, response = requests.post('https://api.url', headers=headers, json=json_data) -
Sending a list value via ajax to view in Django
I'm trying to send a list from template to view Django via ajax. After I send that, I get same list as a string format! index.html <script> ... var provinces_list = [] var obj = document.getElementById('objectSelected'); for (var i=0; i<obj.length; i++) { provinces_list.push(obj.options[i].value) } var jsonText = JSON.stringify(provinces_list); $.ajax({ method: "GET", data: { 'P_list': jsonText }, url: '{% url '...' %}', dataType: 'json', success: function (context) { ... } }) </script> view.py provincesList = request.GET.get('P_list') when I debug, I get the list as str format: provincesList={str}'["X","Y","Z"]' I want to get value as a list. how can do that? thanks in advance -
Ensuring one task of a kind is being executed at a time. (Multiple tasks of different kinds can be executed concurrentlly) celery python
Let's say I have created two shared tasks: from celery import shared_task @shared_task def taskA(): #do something pass @shared_task def taskB(): #do something else pass I am using celery to perform certain tasks that will be invoked by the users of my Django project. I have no issue with taskA and taskB being executed at the same time. But, if taskA is already being executed, and another user tries to invoke taskA again, I want to show them an error message. Is there a way to do that? -
A weird behaviour of get_media_prefix of Django
I am monitoring a weird behaviour in the working of my django application. Sometimes the get_media_prefix returns a mix between static and get_media_prefix. I ask here because I have not found any solution in the searchers and If anyone could have any idea because server and web application do not shown any error, It just returns the incorrect path since is a mix between two paths. The django template is: {% load static %} <!DOCTYPE html> ... <script src="{% static "js/bootstrap.bundle.min.js" %}"></script> </head> <body> ... <img src="{% get_media_prefix %}{{ website.avatar }}" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> ... View: def index(request): results = cache.get(1) if not results: # REDACTED code cache.set(1, foobar, 86400) return render(request,'index.html',{"Foobar" : foobar}) else: return render(request,'index.html',{"Foobar" : foobar}) Apache2 server: Alias /static/ /home/xxx/xxx.xxx/yyy/static/ Alias /media/ /home/xxx/xxx.xxx/yyy/media/ ... <Directory /home/xxx/xxx.xxx/yyy/static> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> <Directory /home/xxx/xxx.xxx/yyy/media> <LimitExcept POST GET> Require all granted </LimitExcept> </Directory> The weird situation always begins randomly and always looks like fix with a restart of apache2. for i in {1..20};do curl -s https://xxx.yyyy/ |grep avatar ; done <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" alt="Blog avatar"></img> <img src="/media/avatar/avatar2.webp" width="60" height="60" class="img-fluid rounded-circle" … -
Why does website not look like a module path?
I am going through a Django tutorial, and after creating my app directory, linking the urls.py files, and adjusting the views.py file, I am getting the error ImportError: website doesn't look like a module path. here is the full error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 25, in import_string module_path, class_name = dotted_path.rsplit(".", 1) ValueError: not enough values to unpack (expected 2, got 1) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\servers\basehttp.py", line 47, in get_internal_wsgi_application return import_string(app_path) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "C:\Conda\envs\DjangoTutorial\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\Dustin Oliver\Desktop\Coding Notes\Django\DjangoTutorial\dentist\dentist\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\wsgi.py", line 125, in __init__ self.load_middleware() File "C:\Conda\envs\DjangoTutorial\lib\site-packages\django\core\handlers\base.py", line 40, … -
Django CSRF Protection Issue
I've just started building an API with Django for the first time and I've run into an issue while trying to test an endpoint with Postman. When I send a POST request to the endpoint http://localhost:8000/arithmetic/ containing the following JSON: { "expression": "1 + 2 × 3" } <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding: 0; margin: 0; } body * { padding: 10px 20px; } body * * { padding: 0; } body { font: small sans-serif; background: #eee; color: #000; } body>div { border-bottom: 1px solid #ddd; } h1 { font-weight: normal; margin-bottom: .4em; } h1 span { font-size: 60%; color: #666; font-weight: normal; } #info { background: #f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top: 10px; } #summary { background: #ffc; } #explanation { background: #eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> </div> <div id="info"> <h2>Help</h2> <p>Reason given for failure:</p> <pre> CSRF token from the &#x27;X-Csrftoken&#x27; HTTP header has incorrect length. </pre> <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or … -
"Looks like your app is listening on 127.0.0.1. You may need to listen on 0.0.0.0 instead." Django project deployment to Railway app error
I want to deploy my Django project to the Railway app(deployment application). I have followed the instructions from this article but still I am getting this error "Looks like your app is listening on '127.0.0.1'.you may need to listen on '0.0.0.0' instead. " I don't know how to get rid of this error. Any help is accepted. -
Could not parse the remainder: '[i]' from 'l[i]' - Django
I am trying to use 'for i in r' as a way to simulate 'for i in range()' as shown in https://stackoverflow.com/a/1107777/14671034 . The r in my case is just a list of numbers from 0 to 10. 'l' is list of objects, here is .html file : {% for i in r %} {% for j in l[i] %} <tr> <td>{{j.a}}</td> <td>{{j.b}}</td> </tr> {% endfor %} {% endfor %} here is the part of views.py: am = [i for i in range(len(list_of_objs))] context = {'l': list_of_objs, 'r': am} everything worked just fine when i was passing list of object instead of list of numbers -
Install PGAdmin4 on Ubuntu
I'm from Iran and i need to install PGAdmin4 for my Ubuntu. To be honest i spent 12 hours time to install this application but after this i realized that the packets coming from server are disable due to internet restrictions from government. is there a way for me to install it ? the issue is raised when i trying to run this command : sudo sh -c 'echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list && apt update' the command line is waiting for receive a response but didn't get it. I installed Postgres but i can't install PGAdmin4. can anyone help me out ??? thanks a lot for your comments. I try to install PGAdmin4 but i couldn't do that. please help me... thanks -
save .xlsx file writen by pandas and export as a django model
I am going to have a web app that does some processing on user data and is going to give him/her back an excel file of processed data in Django. here is my app/views.py function: @login_required(login_url='/signin/') def processing(request): ... # read imported file (uploaded by user) and do the process. # finally have 3 uf, vf, wf array. ... # save the file in "excel_file = models.FileField" from pandas import DataFrame, ExcelWriter data = { 'uf': uf, 'vf': vf, 'wf': wf, } excel_data = DataFrame(excel_data) despiked = Despiking( #other models excel_file=excel_data.to_excel(???), ) despiked.save() return render(request, 'filteration/despiking.html', context=context) how can I save the excel_data into its model (excel_file) and create its media into Media directory? I already have read django pandas dataframe download as excel file question, but wasn't able to fix the problem with HttpResponse. any help would be greatly appreciated -
django mysql connection don't respect databases settings in settings.py
This is my database connection string in settings.py. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "HOST": "127.0.0.1", "PORT": os.getenv("DB_PORT", '3306'), "NAME": os.getenv("DB_DATABASE", 'sm'), "USER": os.getenv("DB_USER", 'root'), "PASSWORD": os.getenv("DB_PASSWORD", ''), } } As above the host specified 127.0.0.1 but when I run python manage.py runserver database connection error with the wrong hostname. django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'172.18.0.1' (using password: NO)") As you can see I wrote hostname 127.0.0.1 but in the project, it is connecting 172.18.0.1 I really appreciate, it if someone gives me an answer to this issue. Thank you. -
How to add icons or emoji in django admin buttons
So I have some buttons in django admin and I need to add something like that: ⬅️➡️↩️↪️ to my admin buttons, but I have 0 idea how to do this and I feel like I am the first ever person to ask that question on the internet, google didnt help :)) Can you guys suggest something? Button for rotating photo in admin Tried to paste this ⬅️➡️↩️↪️ in the name of buttons, but it doesnt work like that xD -
How to set html attributes to Django form created using model
I have model class Listings(models.Model): user_id = models.ForeignKey( User, on_delete=models.CASCADE ) title = models.CharField(max_length=180) desc = models.CharField(max_length=900) price = models.IntegerField(validators=[MinValueValidator(1)]) img = models.ImageField(upload_to='uploads') timestamp = models.DateTimeField(auto_now_add=True) And form class class ListingForm(ModelForm): class Meta: model = Listings fields = ('title', 'category', 'price', 'desc', 'img') labels = { 'desc': 'Description', 'img': 'Upload photo', 'price': 'Starting price' } I want to add HTML attributes like min="0" or remove required from my img = models.ImageField(upload_to='uploads') for example. How can I implement this? I found in stack overflow method with widgets = {'price': IntegerField(attrs='min': 0}) and I also tried ...forms.IntegerField... but I had TypeError: __init__() got an unexpected keyword argument 'attrs' And I also found solution with def __init__(self, *args, **kwargs): super(Listings, self).__init__(*args, **kwargs) self.fields['price'].widget.attrs.update({ 'min': 1 }) (I added it to my form class) But also did not work super(Listings, self).__init__(*args, **kwargs) TypeError: super(type, obj): obj must be an instance or subtype of type [05/Jan/2023 19:22:01] "GET /create_listing HTTP/1.1" 500 60691 -
Django compare two users of a model and if one is the current user return the other user
I have this really simple friendship model that just consists of two users. After all if user1 is friends with user2 then user2 is friends with user1 automatically. I would like to filter all the results by the current user and if a row contains the current user I would like to return the other user. So basically I want to return all records if the current user is either userone or usertwo and if the current user is usertwo swap the values so the current user is userone. Currently it works but only one way using the following model, serializer and view Model: class Friendship(models.Model): userone = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendone" ) usertwo = models.ForeignKey( User, on_delete=models.CASCADE, related_name="friendtwo" ) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: unique_together = ["userone", "usertwo"] def __str__(self): return "{} is friends with {}".format(self.userone, self.usertwo) def save(self, *args, **kwargs): if self.userone == self.usertwo: return "Same person friendship should happen mentally" else: super().save(*args, **kwargs) serializer: class FriendSerializer(serializers.ModelSerializer): profile2 = serializers.SerializerMethodField() class Meta: model = Friendship fields = [ "usertwo", "profile2" ] def get_profile2(self, obj): profile2_obj = Profile.objects.get(id=obj.usertwo.profile.id) profile2 = ProfileSerializer(profile2_obj) return profile2.data and view: class FriendList(generics.ListAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = … -
Why is django.conf.urls.static.static returning an empty list?
I'm trying to allow serving files from my media directory, but the media url isn't getting included... here's my code: from django.conf.urls.static import static urlpatterns = [ ... ] if settings.LOCALHOST_DEVELOPMENT: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) From a Django shell session: >>> from django.conf import settings >>> settings.LOCALHOST_DEVELOPMENT True >>> settings.MEDIA_URL '/media/' >>> settings.MEDIA_ROOT '/Users/[my username]/code/survey_server/media' >>> from survey_server import urls That last call return a list of urls without media url... >>> from django.conf.urls.static import static >>> static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) [] ... and it looks like the media url wasn't included because that static call is returning an empty list. Why is this empty?