Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What factors should I consider choosing a web app development company for my project?
I have Cubet in mind as I search for recommendations on the right web app development company to build a web app for my company. I'm seeking suggestions related to technology, design, and user experience, particularly with a focus on Cubet's expertise and capabilities. Any advice or recommendations are highly valued and appreciated in making an informed decision I have Cubet in mind as I search for recommendations on the right web app development company to build a web app for my company. I'm seeking suggestions related to technology, design, and user experience, particularly with a focus on Cubet's expertise and capabilities. Any advice or recommendations are highly valued and appreciated in making an informed decision -
why am i not able to open the admin page before migration?
while you are creating a project and starting an app, you will run the server and get an appropriate page. and adding an /admin to the 8000 will show the admin page, but is it possible to get the admin page before migration?i tried to open the admin page by adding, /admin to the url before migrating. -
django-constance CONSTANCE_ADDITIONAL_FIELDS from model
I have User table, I need to implement the dropdown list to admin panel, where you can choose only one user. I installed django-constance, and add this code to my settings.py file: ... CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend' CONSTANCE_ADDITIONAL_FIELDS = { 'users_select': ['django.forms.fields.ChoiceField', { 'widget': 'django.forms.Select', 'choices': ( (None, "-----"), User.objects.all().split(",")) ) }], } CONSTANCE_CONFIG = { 'DEFAULT_USER': ('', 'default user', 'users_select'), } I faced with the problem, that I couldn't use Model import in settngs.py. How can I solve this problem and use model data in Constance list? -
OpenBLAS blas_thread_init: pthread_create failed for thread 1 of 4: Operation not permitted
OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:43:00 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:59 [2023-06-26 10:42:59 +0000] [21] [INFO] Booting worker with pid: 21 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [20] [INFO] Booting worker with pid: 20 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [19] [INFO] Booting worker with pid: 19 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [16] [INFO] Worker exiting (pid: 16) 2023-06-26 15:42:58 [2023-06-26 10:42:58 +0000] [15] [INFO] Worker exiting (pid: 15) 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 1 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 3 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 2 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 current, -1 max 2023-06-26 15:42:58 OpenBLAS blas_thread_init: pthread_create failed for thread 3 of 4: Operation not permitted 2023-06-26 15:42:58 OpenBLAS blas_thread_init: RLIMIT_NPROC -1 … -
Django api file managment
I was curios what is the best way to store api views in Django in one file or in separate, because my project is quite big. regular views i am storing in different files for managment. -
gettin this error ,TemplateSyntaxError at / Could not parse the remainder: '>=18' from '>=18'
Gettin this error, TemplateSyntaxError at / Could not parse the remainder: '>=18' from '>=18' and my code is written here, <table class="table"> <thead> <tr> <th scope="col">S.No</th> <th scope="col">Name</th> <th scope="col">Age</th> <th scope="col">Can Vote </th> </tr> </thead> <tbody> {% for people in people %} <tr> <td>{{forloop.counter}}</td> <td>{{people.name}}</td> <td>{{people.age}}</td> <td> {% if people.age >=18 %} can Vote {% else %} can't Vote {% endif %} </td> </tr> {% endfor %} </tbody> </table> I am trying to create a django project which detects yu can vote or not -
how to convert list to class 'django.db.models.query.QuerySet'
I want to use django_filter, but my datatype is list. it shows that list has no attribute model myfiler1 = Orderfilter(request.GET, queryset=mylist) I want to use django_filter, but my datatype is list. it shows that list has no attribute model myfiler1 = Orderfilter(request.GET, queryset=mylist) so how to convert my list to django.db.models.query.QuerySet -
ImportError: cannot import name 'Students' from 'django.contrib.auth.models' Django
I am currently trying out python Django version 4.2.2 to do a project for an activity, I would like to ask what seems to be the problem because whenever i run my project file in VSCode terminal I get the following errors Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "C:\Python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 133, in inner_run self.check(display_num_errors=True) File "C:\Python39\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python39\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 494, in check for pattern in self.url_patterns: File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python39\lib\site-packages\django\utils\functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python39\lib\site-packages\django\urls\resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) File "C:\Python39\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 … -
WebSocket connection to 'ws://127.0.0.1:8000/ws/wdym/' failed: dashboard.js:2
So I'm working on my personal django project to create a real-time web application using channel and websocket. But it shows this error: 'WebSocket connection to 'ws://127.0.0.1:8000/ws/wdym/' failed: dashboard.js:2' in the console and this error: 'Broken pipe from ('127.0.0.1', 50536)' from the terminal. Can you tell me what the issues are and the solution to it? Thanks! I use: python 3.10.11 channels 4.0.0 channels-redis 4.1.0 This is routing.py `from django.urls import re_path from .consumers import DashboardConsumer # websocket url list websocket_urlpatterns = [ re_path('ws/wdym/',DashboardConsumer.as_asgi()), ]` this is urls.py inside the application named game `from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static from .consumers import DashboardConsumer urlpatterns = [ path("", views.home, name="home"), path("<int:id>",views.todo, name="todo"), path("list/", views.list, name="list"), path('wdym/', views.dashboard, name="dashboard") ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` this is consumers.py `from channels.generic.websocket import AsyncWebsocketConsumer #import the websocket import json class DashboardConsumer(AsyncWebsocketConsumer): async def connect(self): print('connection') await self.accept() self.send(text_data=json.dumps({ 'type':'connection_established', 'message': 'You are connected' })) async def disconnect(self, close_code): print(f'connection closed with code: {close_code}') async def receive(self, text_data): text_data_json = json.loads(text_data) # get the data in json strings which get loaded to a json object. message = text_data_json["message"] sender = text_data_json["sender"] print("message",message, sender) await self.send(text_data=json.dumps({ # send data … -
How to get SSL-certified django-daphne app?
I am working on deploying dockerized Django app (4.0) with channels and daphne (4.0). I am using pure gunicorn for WSGI and daphne for ASGI both. I have deployed the app and is working fine in http without SSL certified. However, I can't make it work to use HTTPS, because it fails the test. I have now spent many hours without success finding solutions. certbot log certbot | Saving debug log to /var/log/letsencrypt/letsencrypt.log certbot | Skipped user interaction because Certbot doesn't appear to be running in a terminal. You should probably include --non-interactive or --force-interactive on the command line. certbot | Account registered. certbot | Requesting a certificate for codeforkitchen.com certbot | certbot | Certbot failed to authenticate some domains (authenticator: webroot). The Certificate Authority reported these problems: certbot | Domain: codeforkitchen.com certbot | Type: unauthorized certbot | Detail: 23.92.26.102: Invalid response from http://codeforkitchen.com/.well-known/acme-challenge/_yTtIrfLPkCPzyrkDISG3MjSS6a3d2asZAxMUQZIc1Q: 404 certbot | certbot | Hint: The Certificate Authority failed to download the temporary challenge files created by Certbot. Ensure that the listed domains serve their content from the provided --webroot-path/-w and that files created there can be downloaded from the internet. certbot | certbot | Some challenges have failed. certbot | Ask for help or … -
How to run scheduled tasks in django
Lets say that I need to update an array of length 100 at 15th of each month irrespective of whether a URL is accessed or not. The server should be able to handle incoming requests while executing the function that will update the array. How do I do this? -
Django DRF integration with HDFS using a singleton pattern for resource efficiency and performance
I am trying to integrate Django DRF (Django REST Framework) server with HDFS (Hadoop Distributed File System). However, I couldn't find any official libraries that provide direct integration between Django and HDFS. Therefore, I am considering using native Python libraries for HDFS. However, these libraries typically require creating a client and making calls, which could potentially result in resource wastage and performance degradation. To address this concern, I have implemented a singleton pattern as shown in the code snippet below. from django.http import HttpResponse from hdfs import InsecureClient class HDFSClient: _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super().__new__(cls) cls._instance.client = InsecureClient('http://localhost:9870', user='root') return cls._instance def read_file(self, file_path): with self.client.read(file_path) as reader: file_contents = reader.read() return file_contents def read_hdfs_file(request): hdfs_client = HDFSClient() file_path = '/test.txt' file_contents = hdfs_client.read_file(file_path) return HttpResponse(file_contents) I have implemented a singleton pattern to ensure that only one instance of the HDFS client is created and used throughout the Django application. This approach aims to minimize resource wastage and improve performance. However, I am unsure if this solution effectively resolves the resource and performance concerns. I would like to know if there are better alternatives or approaches to address these issues. -
Python: APNs error with pyapns_client3 package: 'check your code and try again later'
Hey guys I am trying to send apple push notification for voip call and I am using this package pyapns-client3==3.0.5. I have setup the voip services and certificates as per the apple developer documentation. But when I try to send notification, I am getting this exception check your code and try again later and I can't find the error in my code. Can someone help with solving this issue? Or is there a better package or code to send apple push notification? alert = IOSPayloadAlert(title=f"Call From {name}", subtitle='Incoming call', body=f'Incoming call from {name}') payload = IOSPayload(alert=alert) notification = IOSNotification( payload=payload, topic='com.company.app', // bundle identifier push_type="voip", ) with APNSClient( mode=APNSClient.MODE_PROD, authentificator=TokenBasedAuth( auth_key_path=f"{settings.APNS_AUTH_KEY}", auth_key_id=settings.APNS_KEY_ID, team_id='XXXXXXXXX' ), root_cert_path=None, ) as client: try: client.push(notification=notification, device_token=apn_token) except UnregisteredException as e: logger.info(f'device is unregistered, compare timestamp {e.timestamp_datetime} and remove from db') except APNSDeviceException: logger.info('flag the device as potentially invalid and remove from db after a few tries') except APNSServerException: logger.info(f"try again later") except APNSProgrammingException: logger.info('check your code and try again later') else: logger.info('everything is ok') Can anyone help with a better approach or help find error in this code? Thanks -
Django form save via jQuery Ajax POST request when I m submit the URL I m redirect to main form page to JSON response page
I'm using Django form and save via jQuery ajax post request. When submit the form I don't know why redirect to JSON response page and also I don't know why I m not getting response on same page in success:funcation urls. path("iEasy/Group-Type/Add/form/masterside/", views.Add_GrpPage, name="add_grp_page_m"), View.py @login_required(login_url='/') def Add_Handle_M(request): if request.method == "POST": try: form = HandleMaster_Form(request.POST) if form.is_valid: forms = form.save(commit=False) forms.create_by = request.user #forms.save() msg_error=messages.success(request,"Added") except: msg_error=messages.error(request,str(form.errors)) return JsonResponse({'msg_error':msg_error}) Html File <form id="handle_add_form" action="{% url 'add_handle_m' %}" method="post"> {% csrf_token %} {{Handle_Form}} <div class="mt-1"> <button type="submit" class="btn btn-primary">Save</button> </div> </form> **jQuery AJAX ** var add_handle_m = $('#add_handle_m'); add_handle_m.submit(function(e){ e.preventDefault(); var form_data = new FormData(this); $.ajax({ type:montadd_handle_mh_add_form.attr('method'), url:add_handle_m.attr('action'), data: serializedData, success: function(data, status){ if (status) { alert("Added") location.reload(true) } else{ alert(data.data) } }, }); }); -
Why does heroku say there is a dyno running after "ps:scale" but then "ps" says no dynos running?
I built a Django app and I'm trying to use heroku to publish it online. I've tried running the app locally and it works fine, but when I try heroku ps:scale web=1 as soon as i try heroku ps it says that there are no dynos running. Why is this? How do I get my app to run from the heroku website? Thank you for your help and understanding! In the image below my CLI was glitching out so it had text where it didn't belong. I did enter heroku ps not herokeroku ps eroku ps. -
Django deployment error in pythonanywhere
After finishing all the steps of deployment in pythonanywhere.com I got the error at wsgi.py file To remove the error and make the django application live. I have got the error at line:31 of wsgi.py file. At the part of DJANGO settings. -
Bug? <textarea> automatically adding line break
I am trying to simulate a mini wikipedia and one of its functions is to allow the user to edit a page, for that, I am using markdown and converting to HTML, then get user's input and save it as markdown file. The problem is that whenever the page is edited, its add line break automatically. I am probably missing something. Where is my logic fault? Here the page display the HTML for whatever content. Another page -> Edit get_entry() converts markdown to HTML <form action="edit" method="get"> <input type="hidden" name="title" value="{{ title }}"> <input type="submit" value="Edit Page"> </form> def edit(request): if request.method == "GET": title = request.GET.get("title") text = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "title": title, "text": text }) And here the save process. Edit -> Edit <form action="edit" method="post"> <input type="hidden" name="title" value="{{ title }}"> <textarea name="text" rows="10" cols="20" wrap="hard">{{ text }}</textarea> <input type="submit" value="Submit"> {% csrf_token %} </form> def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) elif request.method == "POST": title = request.POST.get("title") text = request.POST.get("text") util.save_entry(title, text) return redirect(f"/{title}") … -
django nginx failed (13: Permission denied)
I get this permission error everytime I try to access media files failed (13: Permission denied) I have tried the solutions provided on the similar questions but they don't seem to be caused for the same reason. Media folder permissions: drwxr-xr-x 3 ubuntu www-data 4096 Jun 26 21:55 media This is also the same for the folder and file I'm trying to access. I checked the nginx site config and everything seems to be okay and pointing at the same path but the problem is still there. When I try to run the command sudo -u www-data ls /home/ubuntu/library/media/ it says ls: cannot access '/home/ubuntu/library/media/': Permission denied I'm new to nginx and ubuntu so I don't know what exactly is the problem here. -
AssertionError on PUT unit TestCase
I'm creating a unit test for a PUT method which purpose is creating new database entry. The problem seems to be I can't retrieve the saved fields string in the right format. The result strings are surrounded with square brackets. Faulty part of tests.py: def test_create_task(self): self.client.login(username='user1', password='password1') data: dict[str, str] = { 'name': 'Nowe zadanie', 'description': 'Nowy opis', 'status': 'Nowe', 'username': 'user1', } response = self.client.post('/api/tasks/', data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Task.objects.count(), 4) self.assertEqual(Task.objects.last().name, 'Nowe zadanie') self.assertEqual(Task.objects.last().description, 'Nowy opis') self.assertEqual(Task.objects.last().status, 'Nowe') self.assertEqual(Task.objects.last().user, self.user1) create method from views.py: def create(self, request, *args, **kwargs): username = request.data.get('username') try: user = User.objects.get(username=username) except ObjectDoesNotExist: raise serializers.ValidationError('Invalid username.') request_data = request.data.copy() request_data.pop('username', None) task = Task.objects.create(user=user, **request_data) serializer = TaskSerializer(task) response_data = serializer.data response_data['username'] = user.username return Response(response_data, status=status.HTTP_201_CREATED) Task model class from models.py(im also using django-simple-history library): class Task(models.Model): objects = models.Manager() STATUS_CHOICES = [ ('Nowe', 'Nowe'), ('W toku', 'W toku'), ('Rozwiązane', 'Rozwiązane'), ] id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=False) description = models.TextField(blank=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='Nowe') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) history = HistoricalRecords() def __str__(self): return self.name console output: ====================================================================== FAIL: test_create_task (tasks_app.tests.TaskTestCase.test_create_task) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\hunes\Desktop\Studia\tasks_project\tasks_app\tests.py", line 48, in test_create_task self.assertEqual(Task.objects.last().name, 'Nowe zadanie') AssertionError: … -
Django filter dynamic field name based on queryset
I have a queryset with a lot of annotations and i have this two fields: price price_after_discount now i want to write a max_filter for it based on value. but i need to do this that if price_after_discount is not 0, do the filter on that and if its is 0 then do the filter based on price. I know this code is not working, just sth that you can understand the question better: value = 200 queryset.filter( Case( When( price_after_static_discount=0, then=F("price") ), default=F("price_after_discount") )__lt=value ) -
Django query for string literal that starts with field value
I am using Graphene with Django, and have a case where I need to retrieve the Django content type that corresponds to a class name with "Node" added, where something like this: ContentType.objects.get(model__something="MyModelNode") would retrieve a ContentType with "model" equal to "MyModel". If it were the other way around, I'd use "model__istartswith='MyModel'". In SQL I'm looking for something like: SELECT * FROM some_table WHERE $1 ILIKE 'MyModel%'; but I don't see how to do that with a queryset. Any ideas? -
django allauth only one email per user
With the django-all-auth default templates / views, the user can have several email address (with only one primary) I'd like to force the user to have only one email address, how can I do that please? -
Pycharm Django connect to MSSQL databse
I am a totally beginner in django. If the question is stupid, please let me know how I should do. I already create the pycharm django project and want to connect to the MSSQL database. I see most of the solving ways is using django-mssql-backend but I am in company computer and our system does not has this package. And I used to use jupyter notebook to connect the databse successfully, here is the code I used in the jupyternotebook database = pyodbc.connect("Driver={ODBC Driver 17 for SQL Server};" "Server= DBName;" "Database=Staging;" "Trusted_Connection=yes;") query1 = """ select * FROM [Staging].[dbo].[viewname] df1=pd.read_sql_query(query1,database) df1 I am wondering can I do the same way in django project to connect to database? django project folder Here is the django project folder. If I can do what I do in jupyternotebook, which .py should I add the code in? Sorry for the stupid question and any help is really apprecaited! -
How to filter by table-A from table-B (table-A is linked to table-B, not the otherwise)
I have the following models: # models.py class Movement(models.Model): class Direction(models.TextChoices): SENT = 'S', _('Sent') RETURNED = 'R', _('Returned') case = models.ForeignKey(Case, on_delete=models.CASCADE, unique=False, null=False, blank=False, db_index=True, db_column='case_id') direction = models.CharField(unique=False, null=False, blank=False, db_index=False, max_length=1, choices=Direction.choices, default=Direction.SENT, db_column='direction') date = models.DateField(auto_now=False, auto_now_add=False, db_index=True, default=current_date, db_column='date') class Case(models.Model): class Meta: constraints = [models.UniqueConstraint(fields=['number', 'year', 'kind', 'police_station'], name='unique_case2')] class Kind(models.TextChoices): MISDEMEANOR = 'M', _('Misdemeanor') TRAFFIC = 'T', _('Traffic') police_station = models.ForeignKey(PoliceStation, on_delete=models.PROTECT, unique=False, null=False, blank=False, db_index=True, db_column='police_station_id') name = models.CharField(unique=False, null=False, blank=False, db_index=True, default='', max_length=100, db_column='name') number = models.SmallIntegerField(unique=False, null=False, blank=False, db_index=True, db_column='number') year = models.SmallIntegerField(unique=False, null=False, blank=False, db_index=True, default=current_year, db_column='year') kind = models.CharField(unique=False, null=False, blank=False, db_index=False, max_length=1, choices=Kind.choices, default=Kind.MISDEMEANOR, db_column='kind') registered_at = models.DateTimeField(auto_now=False, auto_now_add=False, db_index=True, default=current_datetime, db_column='registered_at') Some facts about the Movement table: The Movement table may have multiple records for the same case. The direction field can not have the same value for two records in a row. (ex: if the last Movement record for case_id = 2 is the direction = 'S', the next movement must be direction = 'R'). And I would like to filter cases by their last movement's directions from CaseAdmin class, into three types: Sent. Returned. Has no movement yet. Now how to build a … -
How to include django template file from an install python package?
I have an install python package with structure myapp templates/ myapp/ base.html and my project with structure myproject testapp/ templates/ layout.html I install the package myapp into myproject and from the layout.html file I want to extend the file base.html from the package myapp. Normally, if myapp is a local app inside myproject I can simply do {% extends myapp/base.html %} But if myapp is a install package how can I do that ?