Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error code H10 while deploying django app on heroku
hi i am trying to deploy my django app to heroku but it gives me this error: ** note " the build was successful " enter image description here this is another photo: enter image description here the error code: 2022-03-20T17:01:35.874001+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=37d48eef-1019-4eb1-93a5-50d4c8db7f6b fwd="46.248.201.72" dyno=web.1 connect=8ms service=634ms status=503 bytes=0 protocol=https 2022-03-20T17:01:35.874312+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/" host=beta-stega.herokuapp.com request_id=7054bc05-06f4-43c5-bdea-8b49a610054d fwd="46.248.201.72" dyno=web.1 connect=0ms service=236ms status=503 bytes=0 another error code (i think that): 2022-03-20T17:01:49.757829+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=dbe2cac6-8715-4525-a05a-0c88bb3c8815 fwd="46.248.201.72" dyno=web.1 connect=5000ms service=53ms status=503 bytes=0 protocol=https 2022-03-20T17:02:04.006106+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=ae1a7cae-51b4-461b-9ce6-b83b4966e78a fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https 2022-03-20T17:02:04.577385+00:00 heroku[router]: at=error w desc="App crashed" method=GET path="/favicon.ico" host=beta-stega.herokuapp.com request_id=e00b7566-3ccb-4a04-bdf5-8b814e6874bb fwd="46.248.201.72" dyno= connect= service= status=503 bytes= protocol=https website error image : enter image description here build log image : enter image description here ** note " the work fine on local host " can anyone help :) -
/opt/alt/python39/bin/lswsgi: No such file or directory
I have a shared Cpanel host with Litespeed web server. I want to deploy a django application on it. After creating Python application inside the Cpanel where I have not deployed the application on the host I try loading the web site, and instead of displaying django version I face 503 Unavailable!! Also inside the "stderr.log" file there is following error. /usr/local/lsws/fcgi-bin/lswsgi_wrapper: line 9: /opt/alt/python39/bin/lswsgi: No such file or directory -
how to fetch data from a list of dictionary using django
I am trying to develop a dictionary(using django) that contains a voice for pronunciation. everything goes fine but I cannot relate the audio with the word using the following query. Model.py class Warehouse(models.Model): word = models.CharField(max_length=200, blank=True) type = models.CharField(max_length=200, blank=True) gender = models.CharField(max_length=200, blank=True) meaning = models.TextField(max_length=2000, blank=True) synonyms = models.CharField(max_length=200, blank=True) antonyms = models.CharField(max_length=200, blank=True) usage = models.TextField(max_length=2000, blank=True) class Audio(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) audio_file = models.FileField(upload_to='audio') def __str__(self): return self.warehouse.word def delete_media(self): os.remove(path=MEDIA_ROOT + '/' + str(self.audio_file)) query.py def get_words_warehouse_matching(search_sting): try: dictionary_object = Warehouse.objects.filter(Q(word__icontains = search_sting)|Q(type__icontains=search_sting) | Q(gender__icontains=search_sting)|Q(synonyms__icontains=search_sting)|Q(antonyms__icontains=search_sting) words_list = [] for words in dictionary_object.iterator(): word_dictionary = {'id':words.id, 'word': words.word, 'meaning': words.meaning, 'synonyms': words.synonyms,'antonyms': words.antonyms} words_list.append(word_dictionary) return words_list views.py def search(request): context = {} warehouse={} if request.method == 'POST': context['data'] = get_words_by_matching(request.POST['searchString']) context['warehouse'] = get_words_warehouse_matching(request.POST['searchString']) voice = Audio.objects.filter(warehouse_id = warehouse.id) context['audio'] = voice return render(request, 'dictionary/word.html', context) I need to display the related audio file in the template so that I need to equate warehouse_id to Warehouse.id. How can I fetch the id from get_words_warehouse_matching (dictionary) so that I could use filter(warehouse_id = warehouse.id) in views. Or if there are any other better options, suggestions would be highly appreciated. Thanks in advance. -
No module named '_tkinter : on deploying to heroku
Am trying to deploy a Django React application on heroku but get error ModuleNotFoundError: No module named '_tkinter'. The application is running absolutely fine in local. But, after deploying in Heroku, I am getting the below error. remote: Traceback (most recent call last): remote: File "/app/manage.py", line 22, in <module> remote: main() remote: File "/app/manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate remote: app_config.import_models() remote: File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/config.py", line 300, in import_models remote: self.models_module = import_module(models_module_name) remote: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked remote: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked remote: File "<frozen importlib._bootstrap_external>", line 850, in exec_module remote: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed remote: File "/app/portfolioApi/models.py", line 1, in <module> remote: from turtle import title remote: File "/app/.heroku/python/lib/python3.9/turtle.py", line 107, in <module> remote: import tkinter as TK remote: File "/app/.heroku/python/lib/python3.9/tkinter/__init__.py", line 37, in <module> remote: … -
How to track which user is creating object for a model and how to show the object details only to that user in django
I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created the course model class course(models.Model): course_name = models.CharField(max_length=200) course_id = models.CharField(max_length=10) course_sec = models.IntegerField() classroom_id = models.CharField(max_length=50,unique=True) created_by = models.ForeignKey(User,on_delete=models.CASCADE) here if I use "the created_by" field in forms it appears to be a drop-down menu where every user is showing but I want to automatically save the user who creates the object views.py def teacher_view(request, *args, **kwargs): form = add_course(request.POST or None) context = {} if form.is_valid(): form.save() return HttpResponse("Class Created Sucessfully") context['add_courses'] = form return render(request, 'teacherview.html', context) forms.py from django import forms from .models import course class add_course(forms.ModelForm): class Meta: model = course fields = ('course_name', 'course_id', 'course_sec', 'classroom_id') -
Hello, I want to send the information of a JSON to different databases, the json that I must receive has the following format(Python, Django) [closed]
{ "Table 1": { "field1":"...", "field2":"..." }, "table2": { "field1":"...", "field2":"..." } } -
Can i styling django login views?
I trying using django login views form django.contrib.auth.views, but I'm confused while trying to style it, is there any solution for that? from django.contrib.auth import views as auth_views path('accounts/login/', auth_views.LoginView.as_view()), -
How to use is_active in class based LoginView?
I am using default User model and I want check whether the user is active or not before they log in... How can I do that? -
Reverse foreign key relation in django serializers
Can I save data in django in a reverse foreign key relation. Suppose I have models, class Author(models.Model): author_id = models.SlugField(default=None, blank=True) author_name = models.CharField(max_length=200) class Article(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) article_title = models.CharField(max_length=200) content = models.CharField(max_length=200) Suppose I want to save all articles with their author data what type of serializer should I use. I am receiving data in this form: article_data =[ { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } }, { "title":"ome title", "content":"content", "author":{ "author_id":"2", "author_name":"some name", } } ] How should I write my serializer to save such data. I dont want to write my logic views file. I dont want to loop over all my articles and then save article and author separately using two serialzer. What I want is calling a single serializer and passing the entire list to it: saveArticleAndAuthor(article_data, many=True) the serialzier must save author data to author table and rest of the data to article table. -
how to use font awesome icon as file upload input field for django template as bootstrap?
I am using bootstrap as the template. The form is designed as the font awesome icon will be the file upload field in the design. Is there any way to do it? I have no idea about that. I am sharing the template code here. If anyone can help me, I will be grateful. Thanks. <form method="POST" action="{% url '' %}"> {% csrf_token %} <div class="icons"> <div class="row"> <div class="col-4"> <a href="#"> <i class="fa fa-picture-o" aria-hidden="true"></i> <p>Gallery</p> </a> </div> <div class="col-4"> <a href="#"> <i class="fa fa-camera" aria-hidden="true"></i> <p>Camera</p> </a> </div> <div class="col-4"> <a class="" href="#" > <i class="fa fa-microphone" aria-hidden="true"></i> <p>Audio</p> </a> </div> </div> </div> <div class="mb-3"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="8" placeholder="Type your question here" name="description" ></textarea> </div> <button type="submit" class="btn">Submit</button> </form> -
Please any one out there how i can get pass this issue i encountered this issue most times in heroku when i push new code instead of auto migration
Operations to perform: Apply all migrations: admin, auth, authentication, contenttypes, ekzweb, sessions Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. please anyone out there how can i get pass this issue -
How to send email to admin in Django?
I'm building a web application that needs to send a notification to the admin when there is a low quantity of items in-store. Like if I have 10 pens, and someone recently buys 5 pens from my web application and I want to send a notification to admin if the quantity of pens is less than 5 or equal to 5 to notify him/her. Thanks ^^ -
Passing a variable vs a hard-coded string is not working on query search using Django shortcuts
I'm in the process of learning how to use Django. My goal is to grab an object (one hero and one villain) from the database using the names, (not id), passed in the URL as search params. I am successfully grabbing the values from the query params, however, when I try to pass the variable "hero" into the Django shortcut, (get_object_or_404(Super,name=hero)), I get a 'not found'. It works fine if I manually type out the string I'm searching for(get_object_or_404(Super,name="Bat Man")). Any ideas why this is and how I can make my query search dynamic by name? @api_view(['GET', 'POST']) def supers_list(request): type = request.query_params.get('type') hero = request.query_params.get('hero') villain = request.query_params.get('villain') if request.method == 'GET': supers = Super.objects.all() if type: supers = supers.filter(super_type_id__type = type) serializer = SuperSerializer(supers, many=True) return Response(serializer.data) elif hero and villain: # print(hero) result is "Bat Man" hero_found = get_object_or_404(Super,name=hero) # hero_found = get_object_or_404(Super,name="Bat Man") print('=====', hero_found) return Response('hello') else: heros = supers.filter(super_type_id__type = 'hero') villains = supers.filter(super_type_id__type = 'villain') heros = SuperSerializer(heros, many=True) villains = SuperSerializer(villains, many=True) result = {'heros':heros.data, 'villains':villains.data} return Response(result) -
Django form request method is always GET
This is the html code: <form method='POST'>{% csrf_token %} {{ form.as_p }} <input type='submit' value='save'/> </form> This is the path in url.py: path('student/create/', student_create_view, name='student-create') This is my code in views.py: def student_create_view(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save() form = StudentForm context = { 'form': form } return render(request, "personnel/student_create.html", context) I also tried action attribute and adding or removing "/" to the end of the path. -
django UserPassesTestMixin with parameter
Here's working version with user_passes_test. But I would like to replace position > 1 with parameter. I found that, it's possible to do with UserPassesTestMixin. But I don't know how. Can anyone help? def position_check(user): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = user.id ) return True if position > 1 else False @user_passes_test(position_check, login_url='loginPage') def index(request): pass @user_passes_test(position_check, login_url='loginPage') def exportReview(request): pass I was try: class PositionCheck(self): position = 0 if user.is_anonymous else user_control.objects.values( 'position__rank' ).get( user = self.request.user.id ) return True if position > (replace with parameter) else False class Review(PositionCheck, View): def index(request): pass def exportReview(request): pass -
Django - display Httpresponse in template
This is what I have in views This a function in javascript I get this message when I run the project However the responses are displayed in a blank page like this how do I get the httpsresponse to display in the same page in the chat window and not in a different page I'm completely new to Django and javascript . It would be of great help if anyone can help. Thanks in advance. -
Django-debug-toolbar not showing
I am using django 4.0.3 and django-debug-toolbar 3.2.4. For some reason, the toolbar is not showing on my server.I tried many ways but none of them worked for me. I will be very grateful for any help settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news.apps.NewsConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] WSGI_APPLICATION = 'mysite.wsgi.application' # debug_toolbar moved here. if DEBUG: MIDDLEWARE += [ 'debug_toolbar.middleware.DebugToolbarMiddleware', ] INSTALLED_APPS += [ 'debug_toolbar', ] INTERNAL_IPS = ['127.0.0.1', ] # this is the main reason for not showing up the toolbar import mimetypes mimetypes.add_type("application/javascript", ".js", True) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } urls.py if settings.DEBUG: import debug_toolbar urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Add hyperlinks from an array to elements of a table Django
I have a csv file with 3 columns. I want to display this table in a html but every element of the third column should have a hyperlink loaded from a python array in views.py. Currently, I am loading the table using pandas. My views.py: def passparam(request): data = pd.read_csv (r'/home/darkbee/django3-password-generator/media/test.csv') html_table = data.to_html(index=False) arra_containing_links["#link1","#link1",............."#link1","#link80"] context = {'loaded_data': html_table} return render(request, 'generator/password.html',context ) My password.html: {{loaded_data | safe}} Any help is very much appreciated <3 -
Apache/mod_wsgi log object issues upon importing some module
I have a Django application that runs on an Apache server, Ubuntu OS. I've recently added a new import statement of some module, that causes the following server error: File "/dataco_monitor/dataco_venv/lib/python3.7/site-packages/nebula/consts.py" in <module> 49. _is_interactive = os.isatty(sys.stdout.fileno()) Exception Type: OSError at / Exception Value: Apache/mod_wsgi log object is not associated with a file descriptor. I've tried to reproduce the issue by running the app's virtualenv (with the user that runs the server) and importing that module, but got nothing, all good. Also tried to run manually: os.isatty(sys.stdout.fileno()) , it returns 'True'. I've tried to search Google for this issue, haven't found any similar case. What can that be? Any input here will be much appreciated. Thanks -
Django digital ocean droplet isn't showing the website when connected with a namecheap domain
So I'm using a Django Digital Ocean droplet to run a website. I recently tried connecting the IP address of the droplet to a namecheap domain name, but when I connected them it only showed this on the domain: Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com. Thank you for using nginx. However, the website was working as intended on the IP address, can anyone tell me how to fix this? my abbreviated /etc/nginx/sites-available/defaultfile server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name sanskarhandicrafts.com; location / { try_files $uri $uri/ =404; } } I'm happy to provide more details -
User Data Posted to Django User Model API Fails Authentication
I have two deployed Django projects: A and B and both have User models for user authentication. But I want users of Project B who sign up to have accounts on Project A as well. So I created an API using DRF for the user model in Project A and I was able to post user data (username and password) from Project B to the API. But when I tried to login to Project A using the newly posted user data, it failed authentication, despite the data now bring present in Project A's API. Please could anyone help me identify what's wrong? I'd love to post code snippets but, cuz of the data, can't really do that, but based on the principle, what do you guys think the problem might be? -
ModuleNotFoundError: No module named 'django-angular'
I have already installed pip3 install django-angular Requirement already satisfied: django-angular in /usr/local/lib/python3.9/site-packages (2.3) Requirement already satisfied: django>=2.1 in /usr/local/lib/python3.9/site-packages (from django-angular) (3.2.12) Requirement already satisfied: asgiref<4,>=3.3.2 in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (3.4.1) Requirement already satisfied: sqlparse>=0.2.2 in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (0.4.2) Requirement already satisfied: pytz in /usr/local/lib/python3.9/site-packages (from django>=2.1->django-angular) (2021.3) but on running server it says File "/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-angular' I have already uninstalled & reinstalled it several times but no luck -
Subclassed form doesn't render customized input field in Django
I have a subclassed form which I want to render a custom max attribute on the input field. However, it doesn't return any form instance in the view and thus doesn't render any input field either: # views.py .. custom_max_attribute = qs_aggregates['total_equity'] print(custom_max_attribute) # prints 4000 withdraw_form = WithdrawForm(custom_max_attribute) print(withdraw_form) # prints nothing .. # template .. <div class="field-wrapper"> <div class="field-title">Set your Amount</div> <div class="withdraw-input-field">{{ withdraw_form.withdraw_amount }}</div> <!-- isnt rendered --> </div> .. # forms.py class WithdrawForm(forms.Form): """ A form to withdraw available funds from Farena to the users bank account """ def __init__(self, custom_max_attribute, *args, **kwargs): super().__init__(self, custom_max_attribute, *args, **kwargs) withdraw_amount = forms.FloatField(widget=forms.NumberInput(attrs={'min': 1, 'max': custom_max_attribute, 'step': 0.01})) -
async messages in admin
I created a task in the admin that is costly and should be carried out asynchronously. I would do something like def costly_task(**kwargs): def do_task(id): ## do stuff, you know, that is costly task = ThreadTask.objects.get(pk = id) task.is_done = True task.save() task = ThreadTask() task.save() t = threading.Thread(target = do_task, args = [task.id]) t.setDaemon(True) t.start() return {"id": task.id} With a models.py table: class ThreadTask(models.Model): task = models.CharField(max_length = 30, blank = True, null = True) is_done = models.BooleanField(blank = False, default = False) This works well, but I want to inform the admin of the runnig task, and also when it is finished. There is a very old (django 4.0 incompatible) package called django-async-messages which leverages the normal django-messages package to be used asynchronously. I googled but did not find anything of newer age ... any ideas on how to do this? Can I use djangos async processes to send out two messages: when task started (that one is easy) when task finished Django async send notifications -
I am getting soo many errors on my project please help me
This is my code: def Create_Database_Railway(): import mysql.connector mycon=mysql.connector.connect(host='localhost',user='admin',passwd='12345',port=3307) cursor=mycon.cursor() mycon.autocommit=True s1="create database railway" cursor.execute(s1) Create_Database_Railway() These are error: Create_Database_Railway() File "c:\Users\Admin\OneDrive\Desktop\New Proj\6475-DATABASE CREATION.py", line 3, in Create_Database_Railway mycon=mysql.connector.connect(host='localhost',user='admin',passwd='12345',port=3307) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector_init_.py", line 273, in connect return MySQLConnection(*args, **kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 114, in init self.connect(**kwargs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\abstracts.py", line 1009, in connect self._open_connection() File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 422, in _open_connection self._ssl, self._conn_attrs) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 230, in _do_auth self._auth_switch_request(username, password) File "C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\mysql\connector\connection.py", line 377, in _auth_switch_request raise errors.get_exception(packet) mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'admin'@'localhost' (using password: YES)