Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Websocket disconnecting again and again in django
I am trying to build a one on one chat application using django channels and websockets.I am following this tutorial https://youtu.be/RVH05S1qab8.I am getting this error when I try http://127.0.0.1:8000/raunak2/ in the url : [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'raunak2/'. C:\Users\lenovo\Envs\lend\lib\site-packages\autobahn\websocket\protocol.py:2841:processHandshake C:\Users\lenovo\Envs\lend\lib\site-packages\txaio\tx.py:366:as_future C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- C:\Users\lenovo\Envs\lend\lib\site-packages\twisted\internet\defer.py:191:maybeDeferred C:\Users\lenovo\Envs\lend\lib\site-packages\daphne\server.py:200:create_application C:\Users\lenovo\Envs\lend\lib\site-packages\channels\staticfiles.py:41:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:54:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\security\websocket.py:37:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:47:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:145:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\sessions.py:169:__init__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\middleware.py:31:__call__ C:\Users\lenovo\Envs\lend\lib\site-packages\channels\routing.py:150:__call__ ] WebSocket DISCONNECT /raunak2/ [127.0.0.1:65338] I didn't get a perfect solution for this problem but I have solutions like removing '$' from the URL from routing.py but this is not working. My routing.py: application= ProtocolTypeRouter({ 'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ re_path(r"^messages/(?P<username>[\w.@+-]+)", ChatConsumer), ] ) ) ) }) My app urls.py: urlpatterns=[ path("inbox",InboxView.as_view()), re_path(r"^(?P<username>[\w.@+-]+)/", ThreadView.as_view()), ] JS code: <script src="https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js" integrity="sha512-B4skI5FiLurS86aioJx9VfozI1wjqrn6aTdJH+YQUmCZum/ZibPBTX55k5d9XM6EsKePDInkLVrN7vPmJxc1qA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script> var loc=window.location var formData=$("#form") var msgInput=$("#id_message") var chatHolder=$("#chat-items") var me=$("#myUsername").val() var wsStart='ws://' if(loc.protocol=='https:'){ wsStart='wss://' } var endpoint =wsStart + loc.host + loc.pathname var socket= new ReconnectingWebSocket(endpoint) socket.onmessage=function(e){ console.log("message",e) var chatDataMsg=JSON.parse(e.data) chatHolder.append("<li>"+ chatDataMsg.message +"via"+ chatDataMsg.username +"</li>") } socket.onopen=function(e){ console.log("open",e) formData.submit(function(event){ event.preventDefault() var msgText=msgInput.val() // chatHolder.append("<li>"+ msgText + " via "+me + "</li>") // var formDataSerialized=formData.serialize() var finalData={ 'message': msgText } socket.send(JSON.stringify(finalData)) // msgInput.val('') formData[0].reset() }) } socket.onerror=function(e){ console.log("error",e) } socket.onclose=function(e){ console.log("close",e) } </script> pip freeze: aioredis==1.3.1 asgi-redis==1.4.3 … -
How to update user password and store inside the database using django
I am trying to allow the admin to update the staff password, email address and username but the new password, email address and username is not updated into my database, did I do anything wrong in the code? The images below is how the main page looks like: This images show the next page which is the page that the staff password, username and email address will be updated: views.py def update(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.save() return redirect("/allstaff") return render(request, 'allstaff.html', context) urls.py from django.urls import path from . import views urlpatterns = [ #path('', views.index, name='index'), #path('login/', views.login_view, name='login_view'), path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('delete/<int:id>/', views.delete, name='delete'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] updatestaff.html <!doctype html> {% extends "home.html" %} {% block content %} {% load static %} <html lang="en"> <head> <style> .button { background-color: #38d39f; border-color: #38d39f; color: white; padding: 10px 20px; text-align: center; display: inline-block; margin: 4px 2px; cursor: pointer; … -
Update key value in JSONField()
I'm trying to bulk update lots of records (3.2 million). This is my model: class MyModel(models.Model): stats = JSONField() Where stats is typically saved as: { "my_old_key": [{"hey": "Hello World"}] } I want to update it so that only the key changes it's value and final stats look like this (though there are records with "my_new_key" already so preferably skip those somehow): { "my_new_key": [{"hey": "Hello World"}] } I can do it in Python but it works really slowly.. I've tried on ~10k records with batching approach from this link so that the queryset is not fetched entirely into the memory. Final solution looked like this: def update_queryset(queryset) -> None: for stat in queryset: dictionary = stat.stats if "my_old_key" in dictionary: dictionary["my_new_key"] = dictionary.pop("my_old_key") stat.save() It does work but unfortunately it works too slowly :(. I thought about not fetching it to python at all and working purely on database somewhat like this answer suggested but didn't manage to make it work. Any suggestions on how I can speed it up / write RawSQL / make the jsonb_set approach work? -
You are trying to add a non-nullable field 'agent' to lead without a default; we can't do that (the database needs something to populate existing row
i'm making crm when i type python manage.py makemigrations i got this error: You are trying to add a non-nullable field 'agent' to lead without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option: Here's my models.py: from django.db import models from django.contrib.auth.models import User, AbstractUser class User(AbstractUser): pass class Lead(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BooleanField(default=False) agent = models.ForeignKey("Agent",on_delete=models.CASCADE) class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Here's my settings.py: """ Django settings for crm project. Generated by 'django-admin startproject' using Django 3.1.4. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#zi%h*+ya0z(xi6j&^3uxvv$ak3=lj5wl5&q$zh3pwv9gwk03x' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
how i get primary key in string format in django rest framework
i'm currently working on django rest framework project and the requirement of output of the response is described below. if any one have an idea about this, it will be very helpful for me. currently i'm getting output like this: { "status": true, "message": "User Details", "Detail": { "id": 1, "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": 32, "email": "crish@gmail.com", } } But i want to get output like this: { "status": true, "message": "User Details", "Detail": { "id": "1", #in string formate "phone": "9874563120", "first_name": "Crish", "birthdate": "1989-09-16", "age": "32", #in string formate "email": "crish@gmail.com", } } what change should i make to gat this type of output! -
Contrib-auth-validate give None even when input is correct
Here is my Code: class LoginSerializer(serializers.Serializer): isd = serializers.IntegerField(write_only=True, required=False) email = serializers.CharField(required=False, source='username') phone = serializers.CharField(required=False) username = serializers.CharField(required=False) password = PasswordField(required=True) def create(self, validated_data: dict): if not validated_data.__contains__('username'): print("validated_data",validated_data) validated_data['username'] = validated_data['phone'] print("validated_data",validated_data) user: AppUser = authenticate(**validated_data) print("user",user) if not user or not user.is_active: raise AuthenticationFailed('Username or password is incorrect.') print("user",user) return user and Here is output: validated_data {'isd': 91, 'phone': '123', 'password': '123'} validated_data {'isd': 91, 'phone': '123', 'password': '123', 'username': '123'} user None Forbidden: /auth/user/login/ Even though im using same username and password From django admin user: AppUser = authenticate(**validated_data) print("user",user) is giving me None Value -
django order by aggregate value from non-related table
I have two models, Accrual and Member, and the common field of these two models is register_no, but this field is not a foreign key class Accrual(models.Model): register_no = models.PositiveIntegerField(verbose_name=_('Register No')) amount=models.DecimalField(decimal_places=2, max_digits=17, verbose_name=_('Total Amount')) class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) I want to list the debt each member has. It can be done with @property; class Member(models.Model): register_no = models.PositiveIntegerField(unique=True, verbose_name=_('Register No')) @property def debt(self): ret_val = Accrual.objects.filter(register_no=self.register_no).aggregate( debt=Sum('amount')) debt = ret_val.get('debt', 0) return debt if debt else 0 but I can't use order_by this way. I want to sort each member by debt. How can I solve this problem? -
Reading HTML form name in Django views
I want to define a view that should display from which page the request is coming. for example: 'Request is coming from index page' 'Request is coming from home page' ................... ................ so on views.py def practice(request): return HttpResponse(request.POST) it is displaying all the form fields but I am not able to get the form name. Html: {% extends 'base.html' %} <html> <head> <meta charset="UTF-8"> </head> <body> {% block content %} <h1>Creating Incident</h1> <form name = "index" action = 'practice' method = "post"> {% csrf_token %} <center> <table> <tr><td>Support portal username</td><td>:</td><td><input type = 'text' name = USERNAME size="50"></td></tr> <tr><td>Your Email</td><td>:</td><td><input type = 'text' name = EMAIL size="50"></td></tr> <tr><td>Password</td><td>:</td><td><input type = 'password' name = PASSWORD size="50"></td></tr> <tr><td>Xtreme ID</td><td>:</td><td><input type = 'text' name = COMPANYID size="50"></td></tr> <tr><td>Customer email </td><td>:</td><td><input type = 'text' name = CUSTOMEREMAIL size="50"></td></tr> <tr><td>Event Note </td><td>:</td><td><textarea id="eventnote" name= EVENTNOTE rows="8" cols="48"></textarea></td></tr> </table><br> <input type = 'submit' value = 'submit'> <a href="Home"><input type="button" value="Home"></a> </center> </form> {% endblock %} </body> </html> -
assigning role for different users in Django Rest Framework
I have used AbstractUser defined in Django for user model and have a UserProfile model which is one to one relation with the User. Now I have to implement a role-based authorization for the CRM project that I am writing. What will be the best approach to assign a role? Should I use add fields inside the user model or inside the UserProfile model? Or I should use the already defined superuser,is_staff or active status inside User model. My models: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self,first_name,last_name,email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) #user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self.db) return user def create_superuser(self, first_name,last_name,email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(first_name,last_name,email, password, **extra_fields) class CustomUser(AbstractUser): … -
DRF nested router serializer source fields from url
I have an author and books model. An author has many books with him class Author(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) email = CharField(max_length=50) class Book(Model): id = UUIDField(primary_key=True, default=uuid4, editable=False) name = CharField(max_length=50) author = ForeignKey(Author, on_delete=models.CASCADE) In my urls.py author_router = SimpleRouter() author_router.register( r"author", AuthorViewSet, basename=author" ) nested_author_router = NestedSimpleRouter(author_router, r"author", lookup="author") nested_author_router.register(r"book", BookViewSet) In my searlizers.py class BookSerializer(ModelSerializer): class Meta: model = Book fields = ( "id", "name", "author", ) extra_kwargs = { "id": {"required": False}, "author": {"required": False}, } class AuthorSerialzer(ModelSerializer): class Meta: model = Author fields = ( "id", "name", "email", ) extra_kwargs = { "id": {"required": False}, } In views.py class BookViewSet(GenericViewSet): queryset = Book.objects.all() serializer_class = BookSerializer def create(self, request, author_pk): data = request.data data["author"] = author_pk serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) Since books are related to the author and I am using nested routers the curl call would look like curl --location --request POST 'localhost:8000/author/1/book' --data '{"name": "Book Name"}' In my BookViewSet I end up manually adding the author_pk to the data object before calling serializer is_valid method. Is there a way to specify the source from URL route or any better way of doing this? -
Heroku: "No default language could be detected for this app" error thrown for node app
Heroku: "No default language could be detected for this app" error thrown for node app ... enter image description here -
how can i call all the emails in or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git
i am trying to know how can i call all the emails in it? or i want to add more fields to it it this is my git repo https://github.com/rahullabroo0/django-react-auth-main.git and is there any standard method to use login registration code. plz send me the links and also tell me to how to work on multiple table in django. in dashboard i want to show all the emails from table. this is the code -
Is it possible to determine routes to a location along with its distance using GeoDjango?
We have a food delivery project and we use GeoDjango for storing the locations of vendors and for determining the nearby vendors by calculating the distance of customers and vendors. Now, we want to filter the nearby vendors based on the distance of routes. Like for example, get the vendors that have 10km distance based on routes to the location of customer. Is it possible in GeoDjango? Can you recommend libraries that have that functionality? -
How to manipulate/compress uploaded image and save it to AWS S3 using boto3
I want to manipulate/compress the uploaded image and then save it on the S3 bucket. Here is what I have tried so far: S3 = boto3.client("s3", aws_access_key_id=settings.ACCESS_KEY_ID,aws_secret_access_key=settings.SECRET_ACCESS_KEY) image = Image.open(img) outputIoStream = BytesIO() temp_image = image.resize((1020, 573)) temp_image.save(outputIoStream, format='PNG', quality=60) outputIoStream.seek(0) img = InMemoryUploadedFile(outputIoStream, 'ImageField', " {}.png".format(img.name.split('.')[0]), 'text/plain', sys.getsizeof(image), None) key = f"post/" + str(request.user.id) + "/" + str(img) S3.put_object(Bucket="zappa- legends", Body=img, Key=key) I am getting the following error: An error occurred (BadDigest) when calling the PutObject operation (reached max retries: 4): The Content-MD5 you specified did not match what we received. What should I do to avoid such errors? -
Is there a way to subscribe and send personal messages to slack users in a workspace with python
I have a to create a webapp that sends messages to specific users asking them if they want to see a daily report of their progress. I have to develop this in django and celery. This is the requirement that got me in trouble: The employees should not be able to see other's reports. The slack reminders must contain an URL to today's report with the following pattern https://domain_of_my_app/report/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (an UUID), this page must not require authentication of any kind. I think that link must be unique to the users but I have no idea how to deal with this in slack Any ideas? -
How to get data from url in django?
I want to send contid and cid to the function through the url . I included the path in the urls.py path('contracts/ctinfo/<int:contid>/<int:cid>',contract.ctinfo), # when contid and cid both present path('contracts/ctinfo/<int:cid>',contract.ctinfo), # when only cid is present contract.py def ctinfo(request,cid=None,contid=None): print(cid,contid) return render(some.html) When I am accessing http://localhost:8000/contracts/ctinfo/15000/99 I am getting cid=99 but contid=0 Why I am getting 0? Is there any other way to do this? -
Django - Django not returning all entities from table on GET call
I have this get function def get(self, request): items = Post.objects.order_by('created').annotate( creator_name=F('creator_id__username'), goal_description=F('goal_id__description'), replies=Count('replypost', distinct=True), cheers=Count('cheerpost', distinct=True), ).prefetch_related( Prefetch('photo_set', Photo.objects.order_by('created')) ) serializer = FullPostDataSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_200_OK) It should ideally be returning all the posts ordered by time, but for some reason when I debug and return serializer.data all I get on the front-end is: But when I use PGAdmin to look at the table You can clearly see there are more recent posts than september 13th. What's going on? -
How to allow admin to update staff password and username django
I have created the page where admin is able to update user password and username when the admin click on the update button, it is supposed to redirect the admin to the update page when he click on the update button where he will fill in a new username and password for the staff but there is an error shown below. Image below is a part on how the admin side will looks like: views.py def update(request, id): context = {} user = get_object_or_404(User, id=id) if request.method == "POST": user.save() return HttpResponseRedirect("/update") return render(request, 'allstaff.html', context) urls.py urlpatterns = [ path('register/', views.register, name='register'), path('adminpage/', views.admin, name='adminpage'), path('customer/', views.customer, name='customer'), path('logistic/', views.logistic, name='logistic'), path('forget/', views.forget, name='forget'), path('newblock/', views.newblock, name='newblock'), path('quote/', views.quote, name='quote'), path('profile/', views.profile, name='profile'), path('adminprofile/', views.adminprofile, name='adminprofile'), path('', views.login_user, name='login'), path('home/', views.home, name='home'), path('allstaff/', views.allstaff, name='allstaff'), path('delete/<int:id>/', views.delete, name='delete'), path('update/<int:id>/', views.update, name='update'), path('logout/', views.logout_view, name='logout'), path('register/', views.register_view, name='register'), path('edit-register/', views.edit_register_view, name='edit_register'), ] allstaff.html {% extends "home.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } </style> <div style="padding-left:16px"> <br> <div class="form-block"> <table> <tr> … -
Whice configuration is better ? configure FastCGI module on IIS for a django web app using wfastcgi.exe or python.exe with an argument wfastcgi.py
So I have been learning to deploy a django web application on IIS Web Server. I had successfully deployed it. However, when configuring FastCgiModule on handler mapping, I noticed that the requested executable optional are .dll or .exe file. capture of the requested file for FastCgiModule But, I have read some tutorials and all of them are not using .dll or .exe file on their FastCgiModule, instead they use 'path to python.exe'|'path to wfastcgi.py' this way works. Then I tried another way to configure this using 'path to wfastcgi.py' and it also works. So I have surfed on internet a few days but I couldn't find the answer which way is better. -
Django Application and Apache Server with ERR_CONNECTION_RESET on AWS
I have a Django application running on two AWS EC2 instances with a load balancer. I am using Apache as a web application server. As you can see below, if I run logistic regression on MagicStat using those 8 parameters and the banking.csv file, everything runs fine after clicking the Analyze button. If I use one more parameter, i.e. 9 parameters, I end up with ERR_CONNECTION_RESET error. Even when I run the application directly inside the server using the same Apache (http://localhost), it doesn't work either. Note that I make AJAX calls in each request such as selecting the model and clicking the Analyze button. Interestingly, that doesn't happen, i.e. it works with those 9 parameters, if I run my Django application from local Apache server (http://localhost). . I don't know what is happening? Any suggestions? Note: Running 9 parameters with the banking.csv file crashes my apache server, so that's the reason why I didn't share the data file here. -
ImproperlyConfigured at /admin/auth/group/
I am trying to set multiple Databases in Django and use Djoser for user authentication. I was able to create a super user and log in to the admin site. However, when I try to go to http://127.0.0.1:8000/admin/auth/group/ I get the following error: "ImproperlyConfigured at /admin/auth/group/" It also happens when I use postman to test my Djoser User Create endpoint: ImproperlyConfigured at /auth/users/ settings.DATABASES is improperly configured. Please supply the ENGINE value This is my settings.py: DATABASES = { 'default': {}, 'users': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sapienslevel_users', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': get_secret('DB_PASSWORD') }, 'questions': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'sapienslevel_questions', 'USER': 'postgres', 'HOST': 'localhost', 'PASSWORD': get_secret('DB_PASSWORD') } } DATABASE_ROUTERS = ['users.router.AuthRouter', 'questions.router.QuestionRouter'] This is my AuthRouter: class AuthRouter: route_app_labels = {'users', 'admin', 'contenttypes', 'sessions', } def db_for_read(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users' return None def db_for_write(self, model, **hints): if model._meta.app_label in self.route_app_labels: return 'users' return None def allow_relation(self, obj1, obj2, **hints): if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label in self.route_app_labels: return db == 'users' return None And my custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class … -
Add authentication to django rest framework openapi
I want to add authentication to swagger ui as declared here : https://www.django-rest-framework.org/topics/documenting-your-api/ I already know that drf-yasg and drf_spectacular support that but I wanna know how to do it by just using django rest framework code : <!DOCTYPE html> <html> <head> <title>Swagger</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist@3/swagger-ui.css" /> </head> <body> <div id="swagger-ui"></div> <script src="//unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script> <script> const ui = SwaggerUIBundle({ url: "{% url schema_url %}", dom_id: '#swagger-ui', presets: [ SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset ], layout: "BaseLayout", requestInterceptor: (request) => { request.headers['X-CSRFToken'] = "{{ csrf_token }}" return request; } }) </script> </body> </html> -
How to solve "Could not import 'todo.schema.schema' for Graphene setting 'SCHEMA'. ModuleNotFoundError: No module named 'typing_extensions'."?
I create the Django graphene project. Suddenly I get an error Could not import 'todo.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: module 'graphene' has no attribute 'string'. But I don't find how to solve it. My schema structure is: todo/schema/schema seting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party app 'graphene_django', 'django_filters', ] GRAPHENE = { 'SCHEMA': 'todo.schema.schema' } main urls.py: urlpatterns = [ path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))), ] schema.py: class Query(TodoQuery, graphene.ObjectType): pass class Mutation(Mutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) What I have missed? Or maybe I do something wrong? -
How to display an image inside Django Admin's detail view of a model?
I want to display an image inside a detail view of a model, when browsing through Django Admin. I have seen other posts about displaying images in the list view of all instances of a model in Django Admin. But I'm interested in seeing the image on the page where you can edit the data. models.py class Label(models.Model): label = models.TextField() fragment = models.ForeignKey('Fragment', models.DO_NOTHING, null=True) in_english = models.BooleanField(default=True) validated = models.BooleanField(default=False) def __str__(self): return str(self.fragment) admin.py @admin.register(Label) class LabelsAdmin(admin.ModelAdmin): fields = ("label", "in_english", "validated", ) # What I tried. This is not working even after adding 'image' to the fields. I get an error. # def image(self, obj): # return format_html('<img src="{0}" />'.format(f"/static/fragments/{obj}.png")) -
django, creating qrcode.png file for a new instance in signals.py
I will like to create a qrcode.png file and store it in my S3 bucket once a instance gets created in models.Model (using signals.py). With my code below I managed to create the qrcode__png file in my local base directory but it does not upload to my external S3 bucket or save in my models.Model class. HELP! Thanks. Signals.py @receiver(post_save,sender=inventory) def create__url_qr(sender, instance, created, **kwargs): if created == True: qr = qrcode.QRCode( version=1, box_size=10, border=5) qr.add_data('/MyProperty/item/'+str(instance.id)) qr.make(fit=True) im=qr.make_image(fill_color="black", back_color="white") im.save('qrcode___'+str(instance.id)+'.png', format="png") print('XXXX') print(im) print('XXXX') inst1 = inventory.objects.get(pk=instance.pk) inst1.qr_code = im inst1.save()