Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get transaction information from etherscan site from a specific address using Django rest framework?
I want to know that how can I connect models views and templates to show the transaction information like "from","to","timestamp","hashaddress" Just want the implementation idea. -
401 error drf django when enable withCredentials in axios
I use NextJs and Axios to request after login, I save the cookie in NextJs : export default function handler( req: CustomeNextApiRequest, res: NextApiResponse<Data> ) { res.setHeader( "Set-Cookie", cookie.serialize("Token", req.body?.access_token, { httpOnly: true, maxAge: 60 * 60 * 24, sameSite: "lax", path: "/" // domain : '.' // secure : }) ) res.status(200).json({ status: 'success' }) } When I enable "withCredentials" in Axios: export const callApi = (url?: string) => { const instanse = axios.create({ baseURL: url || "/api/v1/", timeout: 20000, withCredentials:true }); return instanse; } After, When I request something API on another page, I receive 401 from drf Django. My Config Django: SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'JWT_AUTH_HEADER_PREFIX': 'Token', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=60), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAdminUser', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ], 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=60), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 2, 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } CORS_ALLOW_ALL_ORIGINS = … -
RTSP on Django using OpenCV
I need to stream a surveillance camera onto a Django based website. I found a tutorial on Youtube but it is very simple. Down below is my code: from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 # Create your views here. @gzip.gzip_page def Home(request): try: cam = videoCamera() return StreamingHttpResponse(gen(cam), content_type="multipart/x-mixed-replace;boundary=frame") except: pass return render(request, 'index.html') # Video Capture class videoCamera(object): video = cv2.VideoCapture("[user]:[password]@rtsp://[ip-address]:554/sub") while True: _, frame = video.read() cv2.imshow("RTSP", frame) k = cv2.waitKey(10) if k == ord('q'): break video.release() cv2.destroyAllWindows() However, I encounter an error: cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:967: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow' Can somebody help me out? -
How to "save and continue editing" a task in django-viewflow
I'm building an approval workflow using django-viewflow and django-material. A key component of the workflow is for the end user to fill in a lengthy form and eventually submit it for review and approval. What I want My users will expect to be able to save and continue editing, so that they can fill in the form half way, save their progress, and come back later to complete the form filling. Only then they'll want to submit the form. This is a standard feature in the Django admin. What I've found In the default task.html template, django-viewflow offers two submit buttons (source): <button type="submit" name="_continue" class="btn btn-flat">{% trans 'Done and continue on this process' %}</button> <button type="submit" name="_done" class="btn primary white-text">{% trans 'Done' %}</button> The official docs are pretty slim on the difference between these two tasks. "Done and continue" marks the current task as done and activates the next task (which as a user I want to do by default, other than "save and continue editing"). "Done" seems to mark the current task as done, but doesn't proceed to the next task, which requires some awkward self-assigning to proceed. I can see how a user can get confused here. … -
Python Django Livereload Module
Whenever I start the Django development server, I would get this issue LiveReload exception: <urlopen error [Errno 61] Connection refused> The server would still run and render my site but I cannot use the livereload module. I tried uninstalling and reinstalling django-livereload but it does not help. In addition, when I try to run this command: python3 manage.py livereload. It said unknown command:'livereload' -
How to setup nginx config .well-known/acme-challenge with a proxy to Django?
I am very confused with the Nginx .well-known/acme-challenge configuration and how it works with a proxy for Django. Here is my frontend config with is working: server { listen 80; server_name myserve.com; root /var/www/html/myapp_frontend/myapp/; index index.html; location / { try_files $uri$args $uri$args/ /index.html; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://myserver.com$request_uri; } server { listen 443 ssl; server_name myserver.com; location / { root /var/www/html/myapp_frontend/myapp/; index index.html index.htm; try_files $uri$args $uri$args/ /index.html; } ssl_certificate /root/.acme.sh/myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/myserver.com/privkey.pem; } So, on the frontend I have no problem to define: root /var/www/html/myapp_frontend/myapp/; Now I can run the acme script like this: /root/.acme.sh/acme.sh --issue -d myserver.com -w /var/www/html/myapp_frontend/myapp/ It is working fine. But I have issues with my Django backend because the nginx config uses a proxy: upstream myapp { server backend:8000; } server { listen 80; server_name api.myserver.com; location / { proxy_pass http://myapp; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /.well-known/acme-challenge { allow all; root /root/.acme.sh/; } return 301 https://api.myserver.com$request_uri; } server { listen 443 ssl; server_name api.myserver.com; location / { proxy_pass http://myapp; } ssl_certificate /root/.acme.sh/api.myserver.com/fullchain.pem; ssl_certificate_key /root/.acme.sh/api.myserver.com/privkey.pem; } Notice that I do not have a configuration for the folder "/var/www/html/myapp_backend/myapp/" as I have on the … -
whats wrong with capturing username in url? Like: mysite.com/username [closed]
I want to create directory something like mysite.com/user models.py class TwitterUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) urls.py urlpatterns = [ path('<str:user>/', views.user_profile, name='user_profile'), ] views.py for that user_profile def user_profile(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/user_home.html', {'user':user}) -
How many create FCM topics in a server
My team was in trouble in push alarm with FCM token in IOS, So we decided to push alarm to each user with topics. I know that "One app instance can be subscribed to no more than 2000 topics." Firebase But i confused about "One app instance". Is that mean each android or ios application user can subscribe 2000 topics? or Each FCM Server can create up to 2000 topics? I wonder about One app instance's meaning in "One app instance can be subscribed to no more than 2000 topics" -
Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is
Writing a Django app which has a post table that has a recursive relationship to itself. This means that post CAN have a parent post (allows for replies). I want to ensure that a post can have a null for the parent post attribute - this would denote the "root" post. However, when I implement the views, model and serializer for the posts, I get the following error (stack trace): Got a `TypeError` when calling `Post.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Post.objects.create()`. You may need to make the field read-only, or override the PostSerializer.create() method to handle this correctly. Original exception was: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/rest_framework/serializers.py", line 962, in create instance = ModelClass._default_manager.create(**validated_data) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/query.py", line 669, in create obj = self.model(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 564, in __init__ _setattr(self, field.attname, val) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 606, in __set__ raise TypeError( TypeError: Direct assignment to the reverse side of a related set is prohibited. Use parent_post_id.set() instead. Here's my model: class PostObjects(models.Manager): """ Return the Post object and all children posts """ def get_queryset(self): … -
Override django setting only if present in os.environ
I want to define a function that will create a variable under certain circumstances at the scope of where the function was invoked. Something like this: def hook_env(new_var_name, env_var_name): if env_var_name in os.environ: "define new_var_name at the scope in which this function was defined and set it equal to os.environ[env_var_name]" My use case is so I can override Django settings from environment variables, but only present in the environment. Something like this is invalid # only create the variable if some criteria is met def hook_env(new_var, env_name): if env_name in os.environ: global()[new_var] = os.environ[env_name] In C/C++ I might use a macro. I don't know what to do in python. Would it be safe to modify the default variable wherever django creates it in the first place (django/conf/global_settings.py) from inside my settings file? -
whats wrong with capturing user in url?
I want something like mysite.com/user app/urls.py urlpatterns = [ path('', views.index, name='index'), path('twitter_login/', views.twitter_login, name='twitter_login'), path('twitter_callback/', views.twitter_callback, name='twitter_callback'), path('<str:user>/', views.user_profile, name='user_profile'), path('twitter_logout/', views.twitter_logout, name='twitter_logout'), ] views.py for that user_profile @login_required @twitter_login_required def user_profile(request, user): user = TwitterUser.objects.get(user=user) return render(request, 'authorization/user_home.html', {'user':user}) models.py class TwitterUser(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null = True) -
django create auto increment custom id
I want to generate a custom id everytime I insert something like { "office": "DORM", "sem": "2", "sy": "2021-2022", "remarks": "TEST", "resolution": "TEST", "studid": "2019-0069" } it will save something like CL-DORM20212022200 (CL-officesysem00) this is my models.py with a default function def get_default_id(): last_cl_itemid = ClearanceItem.objects.all().order_by('cl_itemid').last() if not last_cl_itemid: return 'CL-' + ('DORM') + ('2021-2022') + ('2') + '00' item_id = last_cl_itemid.cl_itemid item_int = item_id[13:17] new_item_int = int(item_int) + 1 new_item_id = 'CL-' + ('DORM') + ('2021-2022') + ('2') + str(new_item_int).zfill(2) return new_item_id for now it's still hardcoded class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=20, default=get_default_id) studid = models.CharField(max_length=9, blank=True, null=True) office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) remarks = models.TextField(blank=True, null=True) resolution = models.TextField(blank=True, null=True) resolve = models.BooleanField(blank=True, null=True) resolve_date = models.DateField(blank=True, null=True) resolve_by = models.CharField(max_length=8, blank=True, null=True) recorded_by = models.CharField(max_length=8, blank=True, null=True) record_date = models.DateField(default=datetime.now, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' Any idea how can I do this? -
Multi-Table Django Join
Relatively new to Django. I'm building a light CRM in Django. The MYSQL database I built uses associative entities to help deal with many-to-many relationships. I'm trying to use the associative entity "contactdeal" to connect "deals" with "contacts". See models and views below. class Account1(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) biztype = models.CharField(max_length=255, blank=True, null=True) notes = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'account' class Contact1(models.Model): contact_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) account_id = models.ForeignKey(Account1, models.DO_NOTHING, db_column='account_id', blank=False, null=False) contact_notes = models.TextField(blank=True, null=True) contact_email = models.CharField(max_length=255, blank=True, null=True) contact_phone = models.CharField(max_length=255, blank=True, null=True) contact_status = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'contact' class Contactdeal(models.Model): contactdeal_id = models.AutoField(primary_key=True) contactdeal_deal_fk = models.ForeignKey('Deal', models.DO_NOTHING, db_column='contactdeal_deal_fk', blank=True, null=True) contactdeal_contact_fk = models.ForeignKey(Contact1, models.DO_NOTHING, related_name='contactdeal_contact_fk', db_column='contactdeal_contact_fk', blank=True, null=True) class Meta: managed = False db_table = 'contactdeal' class Deal(models.Model): deal_id = models.AutoField(primary_key=True) deal_name = models.CharField(max_length=255, blank=True, null=True) est_value = models.DecimalField(max_digits=13, decimal_places=2, blank=True, null=True) deal_notes … -
How to combine and load data in django like this?
this is my models class model1(models.Model): name = models.charField() class model2(models.Model): model1 = models.Foriegnkey(model1) id = models.IntegerField(primarykey=True) title = models.charFiled() I wanted some thing like this {"model_name1":[{"id":1,"title":"title1"},{"id":2,"title":"title2"}], "model_name2":[{"id":3,"title":"title1"},{"id":4,"title":"title2"}],} how to achieve this in django, the effiecient way -
unable to resolv didn't return an HttpResponse object. It returned None instead
If no input in search bar it returns me the folowing The view wish.views.create_wish didn't return an HttpResponse object. It returned None instead. def create_wish(request): if request.method == 'POST': form = WishForm(request.POST) if form.is_valid(): wish = form.save(commit=False) wish.author = request.user wish.save() my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) messages.success(request, ( "Your location that you want to " "visit has been added to List !")) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) else: my_items = Wish.objects.filter(author=request.user) all_items = Wish.objects.filter(~Q(author=request.user)) return render(request, "wish/wish.html", {'all_items': all_items, 'my_items': my_items}) I just want to go back to the page with a message " please enter a place" -
Django Api url conflicting whenever i apply the url of the app into the urlpatterns and i don't know the way forword here
So, whenever i add this path('api/', include('api.urls')) into the parent urls i get a bunch of errors in the terminal and if i remove it from the urlpatterns i get page not found wheni reload the localhost on my browser, and on the terminal page it shows "Broken pipe from ('127.0.0.1', 8441)" and i'm really really confused right now. Api urls from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register('users', views.UserViewSet, basename='user') urlpatterns = router.urls Parent Urls from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('api/', include('api.urls')) ] Errors C:\Users\Administrator\Desktop\CRUD\songcrud\api\views.py changed, reloading. Performing system checks... System check identified no issues (0 silenced). November 07, 2022 - 01:32:32 Django version 4.1.3, using settings 'songcrud.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [07/Nov/2022 01:32:47] "GET / HTTP/1.1" 404 2170 Not Found: /favicon.ico [07/Nov/2022 01:32:47,092] - Broken pipe from ('127.0.0.1', 8441) C:\Users\Administrator\Desktop\CRUD\songcrud\songcrud\urls.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Administrator\Desktop\CRUD\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, … -
CrateDB as timeseries database for Django
I am trying to use CrateDB as timeseries database for Django. I am deploying both services on docker for development. I started by deploying the following versions: Django: 4.1.3 CrateDB: 5.1.0 However, I was getting compatibility error: django.db.utils.NotSupportedError: PostgreSQL 11 or later is required (found 10.5). I have downgraded the Django version to 3.0 where I don't get that error, however now I get this one: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.InternalError_: Unknown function: pg_catalog.pg_table_is_visible(c.oid) CONTEXT: io.crate.exceptions.SQLExceptions.esToCrateException(SQLExceptions.java:164) io.crate.exceptions.SQLExceptions.prepareForClientTransmission(SQLExceptions.java:151) io.crate.protocols.postgres.Messages.sendErrorResponse(Messages.java:190) io.crate.protocols.postgres.PostgresWireProtocol.handleSingleQuery(PostgresWireProtocol.java:795) io.crate.protocols.postgres.PostgresWireProtocol.lambda$handleSimpleQuery$3(PostgresWireProtocol.java:748) java.base/java.util.concurrent.CompletableFuture.uniComposeStage(CompletableFuture.java:1187) java.base/java.util.concurrent.CompletableFuture.thenCompose(CompletableFuture.java:2309) io.crate.protocols.postgres.PostgresWireProtocol.handleSimpleQuery(PostgresWireProtocol.java:748) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchMessage(PostgresWireProtocol.java:335) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.dispatchState(PostgresWireProtocol.java:325) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:293) io.crate.protocols.postgres.PostgresWireProtocol$MessageHandler.channelRead0(PostgresWireProtocol.java:277) io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:336) io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:308) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/usr/local/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check_migrations() File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 486, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 220, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in … -
Dajngo Channels - synchronousonlyoperation is thrown when using SessionMiddlewareStack
I am trying to implement anonymous chat using Django Channels for websocket connection. However, i keep getting the SynchronousOnlyOperation exception when using SessionMiddlewareStack for authentication. Python version: 3.8 Django Version: 4.1 Channels version: 3.0.5 Consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import * class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def add_user_to_room_pool(self): former = Pool(username=self.user, room_name=self.get_room()) former.save() @database_sync_to_async def remove_user_from_room_pool(self): former = Pool.objects.filter(username=self.user, room_name=self.get_room()) former.delete() async def connect(self): self.room_id = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_id self.user = self.scope['session']['Anonymous-Name'] await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.add_user_to_room_pool() await self.accept() async def disconnect(self, close_code): await self.remove_user_from_room_pool() await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.create_message(message) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, } ) @database_sync_to_async def get_room(self): return Room.objects.get(name=self.room_id) @database_sync_to_async def get_user(self): return Hikka.objects.get(user=self.scope['user'].id) @database_sync_to_async def create_message(self, text): former = Message(message_author=self.user, message_room=self.get_room(), message_text=text) former.save() async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) I've tried removing all cached session data from both Django and web-browser, but that didn't help. I've seen custom implementation of the Middleware, that uses token authentication, but that's not what i need. What i need is to be able to use self.scope['session'] in order … -
File upload button
I would like to have a file upload button for a models.ImageField. However, I don't want it to render with choose file:no file chosen. Instead, I would like a file upload button that pops up a select file button. Is this possible? -
Hi need a solution
I have deployed to post g res p g admin4 and deleted db. s q lite from Django. and set my allowed host =['*'] Am getting server [500]. if any help will be appreciated need a solution after deleting s q .lite d b from Django project and used allowed host to * . am getting 500 server request. LOOKING FOR SOLUTION AM NEW TO DJANGO -
How to add field variables from the HomePage to a stream StructBlock
Hi i have a doubt around how can i show info from the model page onto a block, specifically, a structblock. On my homepage model i have multiple charfields, where i store the link of the social media of the website, and i wish to know how can i print these links inside the template of a structblock on my streams, additionally i wish to know if this is possible too for an img, this is what i've tried so far: home/models.py class HomePage(Page): template = "home/home_page.html" landing_page_template = "home/home_page.html" social_media_display = BooleanField(blank=True, default=True) facebook_link = CharField(max_length=200, default="#") instagram_link = CharField(max_length=200, default="#") twitter_link = CharField(max_length=200, default="#") youtube_link = CharField(max_length=200, default="#") logo_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=False, on_delete=models.SET_NULL, related_name="+" ) Streams/blocks.py class FooterPlus(blocks.StructBlock): tlf = blocks.CharBlock(required=True, max_length=20, label="Tlf", default="+58") email = blocks.CharBlock(required=True, max_length=20, label="Email", default="") class Meta: template = "streams/parts/footer_plus.html" icon = "plus" label = "Footer plus" footer_plus.html <a href="{{self.facebook_link}}" class="list-group-item list-group-item-action"></a> -
how to get the foreignkey attribute value
I'm trying to print out the email related to a specific OrderItem for a Customer, even tho the email exists, it returns "None" instead, what part of my logic is wrong? #Models class Customer(models.Model): email = models.EmailField(max_length=150) class Order(models.Model): customer = models.ForeignKey(Customer) class OrderItem(models.Model): #View def test(): try: customer_email = OrderItem.objects.get(order__customer__email=['email']) except OrderItem.DoesNotExist: customer_email = None print(customer_email) -
Use Django Rest API to verify emails for new users in Flutter
We have made the email verification API thru Django, how do I implement it in Flutter? There are many tutorials using Firebase, but not many using Django. Thanks! I am expecting to use Django to send a verification email when a new user register an account -
Is it possible to send data from one form to multiple models in django using a normal form instead of multiple ModelForm?
I know it sounds weird, but I'm struggling a lot to show multiple tables with an inline, which populates three models with foreign keys, so I'm trying to find easier solutions than creating a script with JavaScript (which I don't know how to do) or a very complicated solution. My idea is to create a normal form with all of the fields and use it to fill all the models. class Order(models.Model): customer = models.ForeignKey("Customer", on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ("-created",) def get_absolute_url(self): return reverse("sales:order-update", kwargs={"pk": self.pk}) def __str__(self): return "Order {}".format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name="items", on_delete=models.CASCADE) product = models.ForeignKey( Product, related_name="order_items", on_delete=models.CASCADE ) quantity = models.PositiveIntegerField(default=1) def __str__(self): return "{}".format(self.id) def get_cost(self): return self.price * self.quantity class Customer(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=15, null=True) email = models.EmailField() address_line_1 = models.CharField(max_length=250) address_line_2 = models.CharField(max_length=60, null=True) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) state = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, default="Mexico") def __str__(self): return f"{self.first_name} {self.last_name}" def get_absolute_url(self): return reverse("sales:modalcustomercreation") I only tried the first solution in [this stackoverflow question](https://stackoverflow.com/questions/5720287/django-how-to-make-a-form-for-a-models-foreign-keys) but It doesn't worked. -
ReactNative, Apollo and Django: upload files
I decided to learn such a technology as GraphQL. For this, I came up with an application (I develop it on ReactNative), a python backend (django-graphene). How the client chose Apollo. I set everything up, everything works, I even did a part already. And here I needed to upload a profile photo. The problem is that I haven't found a way to do this. I used to use the REST API and the client was axios. So I just took the FormData and passed it. Accordingly, the backend accepted and saved as usual. And here I don't even know where to start. I found the apollo-upload-client package, but I didn't find how to integrate it into ReactNative (more precisely, there is a description there, but I didn't understand how to use it correctly). I do it like this: const fileSubstitute = { uri: uriFromCameraRoll, name: "a.jpg", type: "image/jpeg", }; I found graphene-file-upload for the backend, it seems to see my files, but I don't know how to save them (by the way, I can transfer the file without apollo-upload-client). I really like GraphQL, but uploading files is a big deal. If I don't solve it, I will be forced abandon …