Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app cannot delete AWS S3 bucket items
DISCLAIMER: (I'll put it at the top so people don't just skip and not read) I just recently started using AWS so I still don't understand a lot of things and yes, I already did the research on this subject and every post I found said to "make the bucket publicly available" which is something I would like to avoid and that should not be the correct answer since, in the tutorial I was following, the guy used it as private blocking all outside access. The upload of an Images works without issues, so I would roule out any problem with the connection itself, but when I try to delete one I get the error An error occurred (AccessDenied) when calling the DeleteObject operation: Access Denied I was following a tutorial about how to connect the bucket to django. The steps I took: Created a bucket (not public like it said in the tutorial) Created a User Group with "AmazonS3FullAccess" policy Created a User inside the group with both the S3 full access and the "AWSCompromisedKeyQuarantineV2" policy Generated the necessary keys (secret and access) The S3FullAccess policy should be this one: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": … -
Django Model Inheritance: Every
In Django, I want to have several models of the same type: ANode, BNode, CNode are all of type "Node". In the database, you can look up a "Node" by id, then quickly get what kind of Node it is (ANode, BNode, CNode), and then reference that node. Every node is only of one specific node type, and there are node "Nodes", only "ANodes", "BNodes", "CNodes". There may be many kinds of Nodes (A-Z) each with different fields. I can picture the underlying SQL: there is a "Node" table with an ID column and an enum field keeping track of which type of Node it is. How can I implement that? -
How to let Django serve images when hosting on Vercel
I deployed a Django project on Vercel. The app is responsible for serving data to a Next.js frontend. However, the images don't get served while other data do. GET request to the images return NOT FOUND error after deploying to Vercel. I have studied all similar questions on this platform but none seems to solve my problem. I have this in my settings.py file: STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/article_photos') I'm serving only the article_photos. I have this in my project urls.py file: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the structure of my media folder: I have struggled with this problem throughout the whole day. Any help will be appreciated. Update: This is my vercel.json file: { "builds": [{ "src": "core/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } }], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "core/wsgi.py" } ] } This is my my build_files.sh echo "BUILD START" python3.9 -m pip install -r requirements.txt python3.9 manage.py collectstatic --noinput --clear echo "BUILD END" Update 2: Below is the error returned: … -
Python Django and parallel process
I'm making a delayed messaging service in Django. I reached the task manager. In theory, it should be launched in parallel with Django, its task is to “read the database” and send messages. I used "multiprocessing Pool", the code was entered into manage.py. It confuses me that when starting, one of the processes fires twice, “ok” in the screenshot. Using a parallel process, the site is assembled and works properly. why is that? Are there any better practices? Result: не ok не ok Performing system checks... Watching for file changes with StatReloader System check identified no issues (0 silenced). November 10, 2023 - 16:55:45 Django version 4.2.6, using settings 'WhiteRabbit.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ok 2023-11-10 16:56:44.743514 ok 2023-11-10 16:56:45.275028 manage.py: import os import sys from multiprocessing import Pool from automation.task_messanger import task_messanger def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WhiteRabbit.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': with Pool(processes=2) as pool: pool.apply_async(task_messanger, ) pool.apply_async(main(), ) # main() … -
How to generate ID card or certificate in Django with any kind of template as MS Word or PPT or PDF?
I need help to make a ID card or document in django to provide user their ID card or any dynamic documents such as certificates. And provide as PDF I tried, Python docx library. with that it is possible to create a docx file and even add an image. but if i use a template and when i want to replace a text in the docx and the text is in text-box in word then its not replacing. Btw, I solved that. but now i can't replate a image in appropriate place in word. SEE THE TEMPLATE IMAGE . Here if i want to add an image and the image i want to place is in the center Top. but i can't do it. So Please if you can help with this that's fine else , Please give a way that how can i edit a document template with python Just need to generate dynamic document. CODE : def myreplace(file, regex, replace): for p in file.paragraphs: if regex.search(p.text): inline=p.runs for i in range(len(inline)): if regex.search(inline[i].text): text=regex.sub(replace, inline[i].text) inline[i].text=text for table in file.tables: for row in table.rows: for cell in row.cells: myreplace(cell, regex, replace) def ReadingTextDocuments(fileName): doc = Document (fileName) completedText … -
Django Filter a Queryset based on Prefetched FK Relationsship
I have 2 models below, and I am trying to run a query on JournalLineItems that filters out entries that have no associated GeneralLedger entry. My queries are not able to find the right items as I am querying wrong. class JournalLineItem(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) ... class GeneralLedger(SafeDeleteModel, UUID, TimestampModel): id = models.AutoField(primary_key=True) journal_line_item = models.ForeignKey('accounting.JournalLineItem', null=True, on_delete=models.CASCADE, related_name='general_ledger', db_index=True) Overall I can do this, but I want it done on the DB level with a queryset filter: for line_item in JournalLineItem.objects.filter().prefetch_related('general_ledger').using(client_url).order_by('-accounting_period', '-pk'): # only deal with ones that are not in the GL if not line_item.general_ledger.exists(): ... When I try this, the query is not right: JournalLineItem.objects.filter(general_ledger=None).prefetch_related('general_ledger') or JournalLineItem.objects.filter(general_ledger__is_null=True).prefetch_related('general_ledger') -
Not Logging the supplier when suppplier has more then 1 product in his list
this project is about supplier and client management system when we login to client it is working perfect but when I log in to supplier it is throwing error... if we add more than one product in supplier list then it's not logging in that account again. only allowing 1 order . this is the model of my code. # models.py from django.contrib.auth.models import User from django.db import models from django.shortcuts import render, redirect,HttpResponse from django.contrib.auth.models import User from .models import * from django.contrib.auth import authenticate, login,logout from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth import authenticate, login class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15) address = models.CharField(max_length=255) class Supplier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='products/') from here views.py start of start of the code def signup(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') Confirm_Password = request.POST.get('Confirm_Password') user_type = request.POST.get('role') if password != Confirm_Password: return HttpResponse("Your password and confirm password are not the same!!") elif User.objects.filter(email=email).exists(): return HttpResponse("Email Already Exist") # Create the user elif user_type == 'client': # ... existing code for client registration ... mobile = request.POST.get('mobile') address = request.POST.get('address') … -
Make dynamic imports of ts module absolute path in js using Webpack
I'm using Webpack as a bundler. My project contains .ts files with dynamic imports. And everything works just fine. But It is Django project and compressor doesn't see modules to which path is build dynamically. Is there a way to make webpack not build path to module but put it as full string in .js file? This is how it looks now: const obj = await import('../components/MyComponent/MyComponent'); In bundled js: const e = await r.e(3802).then(r.bind(r, 73802)); It is building a path to this module. And I would like to have it as an absolute path. Is there a way to do so? -
Django increment string value without race condition
On save I want to receive names like name, name(1), name(2). I implemented the following code: with transaction.atomic(): same_name_count = Folder.objects.filter( owner=validated_data["owner"], name__iregex=r"%s(\s\(\d+\))?" % validated_data["name"], ).count() if same_name_count: validated_data["name"] = f"{validated_data['name']} ({same_name_count+1})" folder = Folder.objects.create(**validated_data) But I still receive race condition and receive same names when I run this code in celery task. I also tried select_to_update to lock all rows somehow and get correct count -
How to use Accessors in Django, in which django-tables2 is connected, to display links to pages with data about each field in the table?
It is necessary in Django, in which django-tables2 is connected, to output a field with a link to a page with data about this field by get_absolute_url(). To do this, I need to use Accessors, but how??? class GostTable(tables.Table): # get_absolute_url() I need on field 'name'! class Meta: model = Gost template_name = "django_tables2/bootstrap.html" fields = ('name', 'short_name') I haven't any ideas about using Accessors... -
Making Request to django restframework from a deployed django project
I have a project that was created using django and drf along with jquery's ajax for sending post and get request to my django server url. But I am having an issue when I deploy the project on railway. If I run my project on my localhost or 127.0.0.1:8000 it works totally fine but when I try to make request to my server after deploying it fails and shows a CORs error on my browser dev panel. I tried adding my domain to CORS_ALLOWED_ORIGINS in my settings.py file but that does not fix the problem. I also added my domain to CORS_ORIGIN_WHITELIST still yet no progress. Please how do I fix this error. #settings.py CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://127.0.0.1:3000', 'https://my-domain.com', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'https://my-domain.com', ] ALLOWED_HOSTS = ['*'] CSRF_TRUSTED_ORIGINS = ['https://my-domain.com', 'http://127.0.0.1'] #main.js $.ajax({ url: https://my-domain.com/api/blogview, type: "GET", dataType: "json", I tried those codes in my settings.py file yet no progress. And that is how I am making my ajax requests. I also tried order drf endpoints but I still get the same errors on my browser dev panel. These are the errors I got when I run the following command to mimmick a non local server. -----> … -
How to display multiple video streams in django from streamlit?
I have a code that should show a video on a django page. I’m trying to convert it from streamlit to django, but without success. Please tell me how to implement this? Multiple threads arrive and all of them need to be shown on one page in Django like video-wall. Code in streamlit: video_placeholders = [st.empty() for _ in range(3)] for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image) resized_image = cv2.resize(annotated_frame, (1024, 768)) video_placeholders[i % 3].image(resized_image, channels="BGR", use_column_width=True, caption=f"Video {i + 1}") The Django code I’m trying shows images from all cameras in one place, but each thread should have its own display: def video_stream(request): def generate_frames(): for i, result in enumerate(results): image = result.orig_img detection_results = model(image)[0] detections = sv.Detections.from_ultralytics(detection_results) detections = tracker.update_with_detections(detections) annotated_frame = process_frame(image, stream_index=i) # Pass stream_index to process_frame resized_image = cv2.resize(annotated_frame, (1024, 768)) _, frame = cv2.imencode('.jpg', resized_image) frame = frame.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') return StreamingHttpResponse(generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame') I just recently started learning Django and have not yet fully understood the processing logic. My html template: {% for stream_name in stream_names %} <h2>{{ stream_name }}</h2> <img src="{% url … -
Request data Modifiy in django
I have a class with APIView, which accept request. from there, I pass the request to 2 different methods, but when I print data from 2nd function, it is modified by first method. Sample class events(APIView): def post(self, request): data = request.data self.tinybird(data) self.events(data) I was expecting to have same copy of data in both method, but tinyBird method changes one line as del product['options'] and due to this I am not able to get product['options'] in events() method. As I am passing data separately to both functions, how data modification of 1st function affect data of 2nd function. Tried I tried to send copy of request to each function or one function but still same issue. data1 = request.copy() data2 = request.copy() self.tinybird(data1) self.events(data2) still data2 throw keyerror on data2['options'] -
Django tables2: Table reverts to previous value
I have a view where i display 2 tables and I have a form to create a new filter in my template. Using my code I would expect that the filter table to update and stay that way. However, after creating a new filter, it displays in the table but if i refresh the page or create a new filter, it reverts to the "original" table i.e. if i have 1 filter and I create one but i refresh the page or create a new filter afterwards, the table displayed will show just one filter. To illustrate in a more concrete way: original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] 172.19.0.3 - - [10/Nov/2023:10:33:00 +0000] "POST /trendyqc/dashboard/ HTTP/1.0" 302 0 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d45670>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d45bb0>] 172.19.0.3 - - [10/Nov/2023:10:33:01 +0000] "GET /trendyqc/dashboard/ HTTP/1.0" 200 233735 "http://localhost:8000/trendyqc/dashboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/106.0.0.0 (Edition developer)" original: [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at 0x7f01e4d3bc70>] [<trend_monitoring.tables.ReportTable object at 0x7f01e4d3b700>, <trend_monitoring.tables.FilterTable object at … -
Use Absolute URLs for wagtail richtext
I have the following field defined on my model: email_body = RichTextField( verbose_name=_("Email Body"), help_text=_("Body of the email to send when you are out of office."), features=[ "bold", "italic", "ol", "ul", "hr", "h2", "h3", "h4", "h5", "h6", "code", "superscript", "subscript", ], max_length=2048, blank=True, null=True, ) However; when including links, images or documents in the features; the urls generated are all relative: <p data-block-key="e0dv1"><a href="/documents/14/Kunststof_Catalogus_F1204.pdf">Kunststof Catalogus (F1204)</a></p> <img alt="" class="richtext-image right" height="498" src="/media/images/aluminium-catalogus-f2204-page4_1.width-500.jpg" width="500"> <p data-block-key="5nssj"><a href="/nl/producten/">Producten</a></p> <p data-block-key="aa12u">Het <a href="/nl/"><b><i>(REDACTED)</i></b></a> team, 2023</p> As implied by the field name; this is used in emails; thus I cannot use relative URLs. The HTML is generated like so: (It is designed for template injection. Only to be used by admins.) template = util.template_from("from_string", self.email_body) body = richtext(template.render(context, request=request)) context["body"] = body context["email_body"] = body is_file = True as_html = True template_name = "office/emails/closed_email.html" How can I make the richtext editor always generate full (absolute) URLs? -
`channel_layer.group_send` won't call method in `AsyncWebsocketConsumer`
I wrote a WebSocket connection in a Django app, using Django Channels and I'm testing in my local environment with Daphne (I will use uvicorn for production) Here's a function that will be called in the save method of UserNotification model, to send title and message of notification, through user WebSocket connection. from typing import Type from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from django.conf import settings def send_user_notification( user_id: int | Type[int], title: str, message: str ): channel_layer = get_channel_layer() channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format(user_id=user_id) group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format(channel_name=channel_name) async_to_sync(channel_layer.group_send)( group_name, { "type": "user_notify", "message": { "title": title, "message": message }, }, ) class UserNotification(models.Model): user = models.ForeignKey("users.User", on_delete=models.CASCADE) notification = models.ForeignKey( to="notification.Notification", on_delete=models.CASCADE ) def save(self, **kwargs): send_user_notification( user_id=self.user_id, title=self.notification.title, message=self.notification.message, message_type=self.notification.message_type, ) super().save(**kwargs) And here's my AsyncWebsocketConsumer: import json import logging from channels.generic.websocket import AsyncWebsocketConsumer from channels.layers import get_channel_layer from django.conf import settings class UserNotificationConsumer(AsyncWebsocketConsumer): async def connect(self): if self.scope["user"].is_anonymous: await self.close() self.channel_name = settings.NOTIFICATION_WEBSOCKET_CHANNEL_NAME.format( user_id=self.scope["user"].pk ) self.group_name = settings.NOTIFICATION_WEBSOCKET_GROUP_NAME.format( channel_name=self.channel_name ) self.channel_layer = get_channel_layer() await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def user_notify(self, event): print("Event: ", event) data = event["message"] await self.send(text_data=json.dumps(data)) And here's the asgi.py file: import os from channels.routing import … -
Change Model data after form submission in Django
Im writing a Booking System in Django with ModelForms, I Want to change value of a Boolean field in a ForeginKey model when form saves. models.py class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates, null=True, blank=True,on_delete=models.CASCADE) free_hours_from = models.CharField(max_length=10,null=True, blank=True) free_hours_to = models.CharField(max_length=10,null=True, blank=True) status = models.BooleanField(null=True,default=True) class Bookings(models.Model): ... booked_time = models.ForeignKey(AvailableHours, on_delete=models.CASCADE,related_name='booked_time') views.py @login_required() def booking_form(request): form = forms.BookingForm() if request.method == 'POST': form = forms.BookingForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.user = request.user form.save() return HttpResponseRedirect(reverse('creator:login')) return render(request, 'account/book.html', {'form': form}) forms.py class BookingForm(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) Since I want each AvailableHours be able to get booked only once , I need the form to change value of AvailableHours status to False so I can filter it in templates. Can anyone suggest an approach to this issue ? I Tried something like form.booked_time.status = False in my views but it didnt work -
How can i work AJAX update JSON with Datatable (Datatable.JS) - Django?
I have tried to work ajax update from Django to Datatable templates like this code template [shipment.html] <table id="example"> <thead> <tr> <th>User</th> <th>Author</th> </tr> </thead> <tbody> </tbody> </table> i'm use this to got a json data and then now show this already. views.py def getlist(request): if request.method == "GET": data = serializers.serialize("json", Editors.objects.all()) respon = json.loads(data) return HttpResponse(json.dumps(respon, ensure_ascii=False), content_type="application/json") json (getlist) [{"model": "tracking.editors", "pk": 1, "fields": {"editor_name": "This AA", "num_users": 10}}, {"model": "tracking.editors", "pk": 2, "fields": {"editor_name": "This BB", "num_users": 20}}, {"model": "tracking.editors", "pk": 3, "fields": {"editor_name": "This CC", "num_users": 30}}, {"model": "tracking.editors", "pk": 4, "fields": {"editor_name": "This DD", "num_users": 40}}] Javascript <script type="text/javascript" language="javascript" class="init"> $(document).ready(function () { $('#example').DataTable({ ajax: { url: "{% url 'getlist' %}", type: 'GET', dataSrc: "", }, columns: [ {data: "fields.editor_name"}, {data: "fields.num_users"}, ], }); }); </script> Now it's data is already show on my Table but not Real-time update. How can i do it's to Real-time update when have a new record in my Database? i need someone to help for clear of this can be used like my method or need use by our method, Thanks -
dlopen symbol not found in flat namespace '_ffi_prep_closure'
I am getting the following error with the traceback. I have tried install reinstalling cryptography. Went through this as well https://github.com/ffi/ffi/issues/946 as well with no solution and a few other solution but nothing worked. ImportError: dlopen(/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/_cffi_backend.cpython-37m-darwin.so, 0x0002): symbol not found in flat namespace '_ffi_prep_closure' thread '<unnamed>' panicked at /Users/runner/.cargo/registry/src/index.crates.io-6f17d22bba15001f/pyo3-0.18.3/src/err/mod.rs:790:5: Python API call failed note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Traceback (most recent call last): File "./manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/rj/vogo/consumer-api/venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/Users/rj/.pyenv/versions/3.7.17/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/rj/vogo/consumer-api/api/accounts/models.py", line 2, in <module> from .users.models import ( File "/Users/rj/vogo/consumer-api/api/accounts/users/models.py", line 23, in <module> from libs.clients import paytm_client, redis_consumer_client, ola_client, amazonpay_client File "/Users/rj/vogo/consumer-api/api/libs/clients/__init__.py", line 35, in … -
Django Migration Error - Error comes that account_user model should have prior migration before admin migration
first migration was done before creation of the accounts application and then after creation of accounts model it starts throwing error when doing the migration on global level i.e running python manage.py makemigrations and python manage.py migrate. error like - django.db.utils.ProgrammingError: relation "accounts_user" does not exist 2. django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. 3.File "/home/dell/Desktop/foodOnline_main/env/lib/python3.10/site-packages/django/db/migrations/loader.py", line 327, in check_consistent_history raise InconsistentMigrationHistory( django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial on database 'default'. -
django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'usermanager.CustomUser.full_name'
I am creating a custom user model as follows: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) full_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) phone_number = models.CharField(max_length=10) institution = models.CharField( max_length=100, blank=True, null=True ) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [full_name, phone_number] def __str__(self): return self.email It works correctly but when I create superuser, I get the following error django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'usermanager.CustomUser.full_name' -
DJANGO JWT "Authentication credentials were not provided."
i was trying to auth all my api with jwt i am getting this error when i try access api . i dont know how to resolve it .can you please help. i have tried all possible solution shown on internet but still i an unable to resolve it. the error that is display on termianl: Unauthorized: /action_items/ [10/Nov/2023 12:21:50] "POST /action_items/ HTTP/1.1" 401 58 enter image description here SETTINGS.PY type herefrom pathlib import Path from dotenv import load_dotenv import datetime from datetime import timedelta import os load_dotenv() BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.getenv('SECRET_KEY', None) DEBUG = True ALLOWED_HOSTS = ['*'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', #'rest_framework.permissions.AllowAny' ] } INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'rest_framework.authtoken' ] 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', ] ROOT_URLCONF = 'expenses.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'expenses.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.getenv("DB_NAME", None), 'HOST': os.getenv("DB_HOST", 'localhost'), 'PORT': os.getenv("DB_PORT", 3306), 'USER': os.getenv("DB_USERNAME", None), 'PASSWORD': os.getenv("DB_PASSWORD", None), } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators … -
Django template error after parenthesis added by autoformat
I use VSCode and the Django Template Support extension for autoformatting templates. It adds parentheses to my code making it not work. before: {% elif n > page_obj.number|add:'-5' and n < page_obj.number|add:'5' %} after: {% elif n > (page_obj.number|add:'-5' and n < (page_obj.number|add:'5')) %} Template error: In template N:\Coding Projects\poc\templates\poc\product_list_grid.html, error at line 133 Could not parse some characters: |(page_obj.number||add:'-5' 123 : <a class="page-link" href="?page=1" aria-label="First"> 124 : <span aria-hidden="true">&laquo;</span> 125 : <span class="sr-only">First</span> 126 : </a> 127 : </li> 128 : {% endif %} 129 : 130 : <!-- with filter and pages in between --> 131 : {% for n in page_obj.paginator.page_range %} 132 : {% if request.GET.item_code or request.GET.brand__brand_name or request.GET.description %} 133 : {% if n == page_obj.number%} 134 : <li class="page-item active"> 135 : <span class="page-link"><b>{{ n }}</b><span class="sr-only"></span></span> 136 : </li> 137 : {% elif n > (page_obj.number|add:'-5' and n < (page_obj.number|add:'5')) %} 138 : <li class="page-item"> 139 : <a class="page-link" href="{% update_url n 'page' request.GET.urlencode %}">{{ n }}</a> 140 : </li> 141 : {% endif %} 142 : 143 : <!-- without filter and pages in between --> Is this a formatter issue? How can I solve this? Removing the parenthesis worked but … -
AttributeError: 'EmailMessage' object has no attribute 'get_all' when trying to send email with smtplib in django app
I use celery in my django web application to send mails. Here is the code: @shared_task def envoi_email(subject,body,to): smtp_host = os.environ.get('EMAIL_HOST') smtp_port = os.environ.get('EMAIL_PORT') email_from = os.environ.get('EMAIL_USER') pwd = os.environ.get('EMAIL_PASSWORD') msg = EmailMessage(subject,body,email_from,[to]) msg.content_subtype = "html" server = smtplib.SMTP(smtp_host) server.connect(smtp_host,smtp_port) server.ehlo() server.login(email_from, pwd) server.send_message(msg) server.quit() logging.info(f"Mail envoyé vers {to}") The message I get: [2023-11-10 07:07:58,508: ERROR/ForkPoolWorker-8] Task tasks.tasks.envoi_email[62cf0d90-ef4e-4f85-b7aa-bebd023289ae] raised unexpected: AttributeError("'EmailMessage' object has no attribute 'get_all'") celery-worker | Traceback (most recent call last): celery-worker | File "/py/lib/python3.9/site-packages/celery/app/trace.py", line 477, in trace_task celery-worker | R = retval = fun(*args, **kwargs) celery-worker | File "/py/lib/python3.9/site-packages/celery/app/trace.py", line 760, in __protected_call__ celery-worker | return self.run(*args, **kwargs) celery-worker | File "/electron/tasks/tasks.py", line 216, in envoi_email celery-worker | server.send_message(msg) celery-worker | File "/usr/local/lib/python3.9/smtplib.py", line 944, in send_message celery-worker | resent = msg.get_all('Resent-Date') celery-worker | AttributeError: 'EmailMessage' object has no attribute 'get_all' Need help please -
Django + daphne + StreamingHttpResponse return chunked data not streaming data
I am currently developing API using StreamingHttpResponse in Django. As far as I know, StreamingHttpResponse is supposed to output results in yield units, but in reality, it outputs yield value's' For example, I used generator below. def iterator(): for i in range(100000): yield {"iteration ":str(i)} Then, the result value is expected to have one yield value each time. {"iteration" : "1"} {"iteration" : "2"} ... However, in reality, it returns a certain buffer size(maybe 4000chars), waits, and then returns again. {"iteration" : "1"} {"iteration" : "2"} ~~ {"iteration" : "100"} In order to actually return a value every time without a buffer like above, which settings among django, daphne, and streaminghttpresponse should I add or remove? actual log : 2023-11-10 05:29:58,361 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,376 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,398 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,412 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] --- [7f6f53f9c0a393a547dccbdde2c59065] [24a60a12badf08b6] [user:6549c3c2c8fd4d4d6099d6d1] 2023-11-10 05:29:58,432 DEBUG 8 --- [MainThread] daphne.http_protocol:283 HTTP response chunk for ['192.168.192.1', 0] …