Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I Access _id field on djongo model it returns None
This code creates a User document class UserManager(BaseUserManager): def create_user(self, name, email, password, mobile_number, alias=None): user = self.model(email=self.normalize_email(email)) user.name = name user.mobile_number = mobile_number user.set_password(password) user.save() return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff() user.is_superuser = True user.save() return user This is the User Model it uses the djongo models classes class User(AbstractBaseUser): _id: ObjectIdField(primary_key=True) email = EmailField(null=False, unique=True) name = CharField(max_length=30) mobile_number = CharField(max_length=10, unique=True) is_active = BooleanField(default=True) is_staff = BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" class Meta: db_table = "login" user = User() user.email = 'test@mail.com user.name = 'name' user_mobile_number = '7894561236' user.save() print(user._id) ->None accessing user id this way returns None user.name = 'newname' user.save() #this creates a new instance of document -
django apiview form not showing up
models.py from django.db import models from datetime import datetime class Song(models.Model): title = models.CharField(max_length=64) audio_file = models.FileField() genre = models.CharField(max_length=64) created_at = models.DateTimeField(default=datetime.utcnow) serializers.py from rest_framework import serializers from . import models class SongSerializer(serializers.ModelSerializer): class Meta: model = models.Song fields = '__all__' views.py from . import models, serializers from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.views import APIView class SongView(APIView): def get(self, request, format=None): serializer = serializers.SongSerializer(models.Song.objects.all(), many=True) return Response(serializer.data) class PostSong(APIView): # The issue <---------------- def post(self, request, format=None): song = request.data.get('song') serializer = serializers.SongSerializer(data=song) if song.is_valid(): serializer.save() return Response({'OK':'Song Uploaded'}, status=status.HTTP_200_OK) return Response({'Bad Request': 'Invalid Data'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('songs/', views.SongView.as_view(), name='songs'), path('add-song/', views.PostSong.as_view(), name='add-song') ] The SongView works perfectly fine and PostSong works too but the form is not showing up, I can only post data via json so I am not able to upload the audio file, how can I fix this? -
Django ORM and Azure SQL
Student programmer here! so go easy... My team and I are building a web app with Django that centres around creating a structured database, inserting data that has been extracted from PDF's, and enabling users to view records in the database. Its for an archeology department for their paper based archive that needs to be digitized. First time Django and Azure user, so I don't fully understand how/if they fit together. I've begun coding the models.py file to create the models. Do we also need to set up Azure SQL to store the db? Or is it completely managed by Django, seeing as it has its on backend interface? Basically, is ORM just used to initialise the database and for accessing the objects, but something still needs to be set up on Azure specifically for the database? Thanks in advance -
Connecting MongoDB database with django by djongo
My app was using PostgreSQL then I tried to connect with MongoDB Database but the collections didn't appear in it after migration?! DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'NoSQL_Blog', } } -
Cloudflare GraphQL API With Python Authentication Error
I am trying to build a website statistics app with Cloudflare APIs and Python Django. def website_metrics(request): cf_graphql = CloudFlare.CloudFlare( email=settings.CLOUDFLARE_EMAIL, token=settings.CLOUDFLARE_API_TOKEN ) query = """ { viewer { zones(filter: {zoneTag: "zone_id_placeholder"}) { firewallEventsAdaptive(limit: 10000, filter: {date: "2021-07-22"}) { action clientCountryName clientAsn clientASNDescription clientIP clientRequestScheme clientRequestHTTPHost datetime userAgent } httpRequests1dGroups(limit: 10000, filter:{date: "2021-07-22"}) { sum { threats } dimensions { date } } } } } """ try: r = cf_graphql.graphql.post(data={'query':query}) except CloudFlare.exceptions.CloudFlareAPIError as e: exit('/graphql.post %d %s - api call failed' % (e, e)) return HttpResponse(template.render(context, request)) The code I've got above is mostly taken from the example_graphql.py script from the python-cloudflare package repository, here. This code is returning an authentication error: SystemExit: /graphql.post 10000 Authentication error - api call failed. I can confirm that the Zone ID, Cloudflare Email address and API keys are correct. Running the same GraphQL query in GraphiQL succeeds and returns the actual metrics. What am I doing wrong here? -
Is it a good to make an industrial project in IoT using Django on the server side
I'm attempting to make an industrial project in IoT which contains thousands of devices and I'm thinking of using Django on the server side of it. Does anyone think it's a good idea? (1)I am looking at (IOT and DJANGO) and also (IOT and node.js). (2)For me I may used DJANGO, because I use python a lot. But looking at node.js plugins, its hard to not select this package. -
how to serialize properly in perticular format
Please help me improve my code.. im newly placed and learning things i want to display separately product field in my code just like category and sub-category in my code but i don't know how to. Also please point out if there anything that i can improve in my code Here is my output: [ { "Category": { "c_id": 1, "parent_id": 15 }, "Sub_category": { "sc_id": 1, "is_active2": 1 }, "p_id": 2, "group_id": "", "product_name": "Fruit", "is_prescription_needed": 1, }] Whereas my expected format is: [ { "Category": { "c_id": 1, "parent_id": 15 }, "Sub_category": { "sc_id": 1, "is_active2": 1 }, "Product": { # How do i separate this "Product" key and value "p_id": 2, "group_id": "", "product_name": "Fruit", "is_prescription_needed": 1 }] here is my code: Serialziers.py class ProductCategorySerializer(serializers.ModelSerializer): c_id = serializers.SerializerMethodField() category_image = serializers.SerializerMethodField() class Meta: fields = ["c_id","parent_id","category","category_image","is_active"] model = Category def get_c_id(self,obj): return obj.id def get_category_image(self,obj): return obj.image class ProductSubCategorySerializer(serializers.ModelSerializer): sc_id = serializers.SerializerMethodField() is_active2 = serializers.SerializerMethodField() class Meta: fields = ["sc_id","sub_category","is_active2"] model = ProductSubCategory def get_sc_id(self,obj): return obj.id def get_is_active2(self,obj): return obj.is_active class ProductSerializer(serializers.ModelSerializer): Category = ProductCategorySerializer(source='category', read_only=True) Sub_category = ProductSubCategorySerializer(source='sub_category', read_only=True) product_image = serializers.SerializerMethodField() p_id = serializers.SerializerMethodField() class Meta: fields = ["Category","Sub_category", "p_id", "group_id", "product_name", "is_prescription_needed", "product_description", … -
Django Send Selenium Exception Message in Template
Hello All I am pretty new to Django Web Framework. I tried creating bot to fill form and the website sometimes changed I want to handle NoSuchElementException and send my custom Error message in django template I dont know how to do it def upload(request): if request.method == "POST": uploaded_file = request.FILES['csv_document'] fs = FileSystemStorage() read = csv.reader(codecs.iterdecode(uploaded_file, 'utf-8')) for row in read: try: time.sleep(3) select = Select(driver.find_element_by_xpath("//select[@formcontrolname='clientDealerType']")) select.select_by_visible_text(row[0]) except NoSuchElementException as e: print('Could not locate element with visible text {}'.format(e)) return render(request, 'upload_csv.html') I want to send exception message in template. I don't have much thing in my template here is my template <!DOCTYPE html> {#{ % load#} <html lang="en"> <head> <meta charset="UTF-8"> <form></form> <title>Title</title> </head> <body> <h1>upload</h1> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="csv_document" /> <button type="submit">Upload a file</button> </form> </body> </html> Any hint will be helpful. Thank you. -
Django Rest Framework - Is it possible to edit the required POST request JSON structure and still use the ViewSet w/ Mixins?
First off, please excuse my mediocrity as I have very recently started working with Django and DRF and I'm still getting the hang of it. I have created a REST API and I've got 2 models, Chat and Conversation. class Conversation(models.Model): def __str__(self): return str(self.id) class Chat(models.Model): payload = models.TextField() userId = models.CharField(null=True, max_length=10) utc_time = models.DateTimeField(default=now) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE, related_name='chats', null=True) def __str__(self): return self.payload My goal is to be able to create a new chat inside a conversation using a POST request at myapi/chat/, like so: { "conversationId": 1, "chat": { "payload": "Payload test", "userId": 3 } } So if you POST this JSON, a new chat with the corresponding payload would be created inside the existing conversation with the id = 1, and the id of the newly created chat would be returned as a response. My issue is, despite looking inside the DRF documentation, I am still very confused about how to choose what fields should be passed inside the JSON in order to respect the JSON structure above. I am currently using the following GenericViewSet with the following Mixin(s?) for the Conversation and Chat, as I have found it much easier and cleaner to … -
How can I make a field in Django models that concatenates a specific string to each record's id?
I have made a field facility_id in Django models that should concatenate a specific string "ACCTS-" on the left with each record's id on the right, My model class is below: class Facility(models.Model): ... id = models.BigAutoField(primary_key=True) facility_id = models.CharField(max_length=50, default=print(f'{"ACCTS-"}{id}'), editable=False) ... I want to the facility_id field to be storing special and readable human friendly facility_id's of the form: ACCTS-1, ACCTS-2, ACCTS-3, ... corresponding to each individual id. The migrations didn't throw any errors, however When I try to create the records for this table in the Django Admin, am getting an IntegrityError of: IntegrityError at /admin/ACCTS_CLYCAS/facility/add/ NOT NULL constraint failed: ACCTS_CLYCAS_facility.facility_id How do I fix this problem, or what could be the easiest way to implement my problem. -
append data in list in django template
I want to create a list and append data within for loop in django template. How can i do this I try this but not working @register.simple_tag def appendDataInList(list_data, add_data): print(list_data, add_data) if list_data is not None: return list_data.append(add_data) return list_data In my view i have set a list like this return render(request, self.template_name, {'list_data' : [] } ) And in template {% for value in data %} {% appendDataInList list_data value.order_id as list_data %} {% endfor %} When i want to print this list out of loop {{ list_data }} #it give me only one result in list why? -
Django Form request.POST.get() returns none value
Here is my Django if request.method == 'GET': term = request.POST.get('term') grade = request.POST.get('grade') year = request.POST.get('year') Here is my HTML code <form method="GET"> <label><b>Term</b></label> <input type="text" name='term' id='term' placeholder="Ex:Term3"> <label><b>Grade</b></label> <input type="text" name='grade' id='grade' placeholder="Ex:Grade 11A"> <label><b>Year</b></label> <input type="number" name='year' id="year" placeholder="Ex:2021"> <button type="submit" class="btn btn-primary"><a href="{% url 'prediction'%} ">Search</a></button> </form> but term year and grade always show empty Any one cam help me -
Django UpdateView AttributeError 'UserPostUpdateView' object has no attribute 'publish'
I get the error when I try to save the form after editing. If I override get_context_date(currently commented out), I get the error when loading the form. I've looked at the documentation and previous questions with this problem. Those who ran into this had overridden post() which I have not. So I have no idea why this is happening and how to solve it. Would appreciate any help. Traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/create/my_collideas/2021/7/28/title-2-by-user2/edit/ Django Version: 3.2.4 Python Version: 3.8.2 Installed Applications: ['home', 'search', 'userauth', 'blog', 'menus', 'contact', 'create', 'wagtail.contrib.forms', 'wagtail.contrib.modeladmin', 'wagtail.contrib.redirects', 'wagtail.contrib.table_block', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'allauth', 'allauth.account', 'allauth.socialaccount', 'ckeditor', 'widget_tweaks', 'dbbackup', 'django_extensions', 'captcha', 'wagtailcaptcha', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar'] Installed Middleware: ['debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/mixins.py", line 71, in dispatch return super().dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/edit.py", line 194, in post return super().post(request, *args, **kwargs) File … -
How to allow sqlite3 databate take duplicate values in different rows providing the primary keys are different?
I'm trying to import a .csv file into my Django db.sqlite3 and I followed exactly as the the instructions from a Youtube video. However, there are a couple of rows in my .csv file that have the same latitude and longtitude values and sqlite3 fails to import some rows as the latitute and longtitude already appear in the table. sqlite> .import venues.csv myapi_venue venues.csv:17: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:44: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:49: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:60: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:66: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:73: INSERT failed: UNIQUE constraint failed: myapi_venue.name venues.csv:80: INSERT failed: UNIQUE constraint failed: myapi_venue.name I tried to force the model to have unique as False, but it doesn't help. class venue(models.Model): name = models.CharField(_("name"), primary_key=True, max_length=300) address = models.CharField(_("address"), max_length=300, unique=False) categories = models.CharField(_("category"), null=True, max_length=300, unique=False) latitude = models.FloatField(_("latitude"), max_length=150, unique=False) longitude = models.FloatField(_("longitude"), max_length=150, unique=False) When I try migrate the changes, it shows this: $ python manage.py makemigrations No changes detected How do I import all the rows into the database? -
Cannot resolve keyword '_cart_id' into field. Choices are: cart_id, cartitem, date_added, id
views.py def allProdCat(request, c_slug=None): c_page = None products_list = None if c_slug != None: c_page = get_object_or_404(Category, slug=c_slug) products_list = Product.objects.all().filter(category=c_page, available=True) else: products_list = Product.objects.all().filter(available=True) paginator = Paginator(products_list, 6) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except (EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'products': products}) category.html {% extends 'base.html' %} {% load static %} {% block metadescription %} {% if category %} {{category.description|truncatewords:155 }} {% else %} Welcome to ABC store where you can buy different items... {% endif %} {% endblock %} {% block title %} {% if category %} {{category.name }} - ABC Store {% else %} See our New Collections -ABC Store {% endif %} {% endblock %} {% block content %} {% if category %} {% endif %} {% if category %} {{category.name}} {{category.description}} {% else%} Our products Collections What is Lorem Ipsum Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book it has? {% endif %} {% for products in … -
Sum values from child models using nested Subquery and annotaions in Django Viewset
I'm trying to calculate the total price of a Recipe. To optimize DB queries I'm trying to use Django's ORM capabilities to perform the fewest requests. My models.py is like this: class BaseRecipe(models.Model): title = models.CharField(_('Base recipe title'), max_length=255, user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_base_recipes') class Meta: ordering = ['title'] def __str__(self): return self.title class IngredientBaseRecipe(models.Model): base_recipe = models.ForeignKey(BaseRecipe, on_delete=models.CASCADE, related_name='ingredients') name = models.CharField(_('Name'), max_length=255) products = models.ManyToManyField(Product) quantity = models.FloatField(_('Quantity'), default=0.0) class Meta: ordering = ['-id'] def __str__(self): return self.name class Product(models.Model): name = models.CharField(_('Name'), max_length=255, help_text=_('Product name')) price = models.FloatField(_('Sale price'), default=0) class Meta: ordering = ['name', ] indexes = [models.Index(fields=['name',]), ] Then in my Viewset I'm trying to get the BaseRecipes queryset with an annotated field that shows the sum of the ingredients prices. I get to the point to obtain the ingredients price, but I'm stucked trying to sum them in the BaseRecipe query set: min_price = ( Product.objects.filter(name=OuterRef('name')) .annotate(min_price=Min('price')) .values('min_price') ) ingredients_price = ( IngredientBaseRecipe.objects .filter(base_recipe=OuterRef('id')) .annotate(price=Subquery(min_price)) .order_by() .annotate(total=Sum(F('price') * F('quantity'))) .values('total') ) queryset = BaseRecipe.objects.filter(user=self.request.user) \ .annotate(cost=Sum(ingredients_price)) return queryset Thanks a lot for your help! -
How does Django map the urls when there is ambiguity
I have the url patterns in my project urls.py url(r'^', include('app.urls')), url(r'^api/app/', include('app.url.router_urls')), and in the app.urls i have something like url(r'^api/app/user$', views.user_validator), and in the app.url.router_urls i have something like url('^v1/', include('app.url.app_v1.urls')) I have a question around these. so when the request is BASE_URL/api/app/{user} which url will be mapped to this? and how about BASE_URL/api/app/v1/ which url will be mapped. this will map first with ^ right and will use the app.urls for both? thanks -
Warnings in command prompt about notepad after installation Of python package
Why its showing this warning "(process:14700): GLib-GIO-WARNING **: 12:08:05.830: Unexpectedly, UWP app HaukeGtze.NotepadEditor_1.811.1.0_x64__6bk20wvc8rfx2' (AUMId HaukeGtze.NotepadEditor_6bk20wvc8rfx2!notepad') supports 182 extensions but has no verbs" I just installed weasyprint in python and GTK for 64 bit from there on its showing this error? Can anyone help me out of this? Thanks in advance.. -
While testing my Websocket Consumer a model object is not created (Django Channels)
I'm new in Django Channels and I'm trying to build a simple chat app. But when I'm trying to test my async Websocket Consumer I run into the following exception: chat.models.RoomModel.DoesNotExist: RoomModel matching query does not exist. It seems like the test room is not created. test.py file is the following: class ChatTest(TestCase): @sync_to_async def set_data(self): room = RoomModel.objects.create_room('Room1', 'room_password_123') room_slug = room.slug user = User.objects.create_user(username='User1', password='user_password_123') print(RoomModel.objects.all()) # querySet here contains the created room return room_slug, user async def test_my_consumer(self): room_slug, user = await self.set_data() application = URLRouter([ re_path(r'ws/chat/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()), ]) communicator = WebsocketCommunicator(application, f'/ws/chat/{room_slug}/') communicator.scope['user'] = user connected, subprotocol = await communicator.connect() self.assertTrue(connected) await communicator.send_json_to({'message': 'hello'}) response = await communicator.receive_json_from() self.assertEqual('hello', response) await communicator.disconnect() My consumer.py file is the following: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): self.message = json.loads(text_data).get('message') data = {'type': 'chat_message'} data.update(await self.create_message()) await self.channel_layer.group_send(self.room_group_name, data) async def chat_message(self, event): await self.send(text_data=json.dumps({ 'message': event['message'], 'user': event['user'], 'timestamp': event['timestamp'] })) @database_sync_to_async def create_message(self): print(RoomModel.objects.all()) # qyerySet turns out to be empty here room = RoomModel.objects.get(slug=self.room_name) msg = room.messagemodel_set.create(text=self.message, user_name=self.scope['user']) return { 'message': msg.text, 'user': self.scope['user'].username, 'timestamp': … -
Update data with image in Django through Axios
I am trying to update the data with a field image. I followed this link https://stackoverflow.com/a/28036805/15320798 to successfully upload an image. But when I try to update the data without changing the image field, it throws the error Upload a valid image. The file you uploaded was either not an image or a corrupted image. The scenario is that I have to change other fields and keep the image field the same. Example Request Payload: { "name":"John" "age":18, "image:""http://localhost:8000/media/9154fb95-0f1.jpg" } and this is how I send the data from vue axios .put(url, data) .then((response) => { console.log("success") }) serializers.py class UserSerializer(serializers.ModelSerializer): image = Base64ImageField(max_length=None,use_url=True,) # this is from the link above class Meta: model = User fields = ( "name", "age", "image" ) Is there any way I can execute this? -
{ "detail": "CSRF Failed: CSRF token missing or incorrect." }
hello guys . I try to register a new Product in my app using DRF and Postman. when I send a request I get this error. the problem is just about my csrf_token. I'll be thankfull if you help me..... this is my view class ProductViewSet(viewsets.ModelViewSet): authentication_classes = (SessionAuthentication,TokenAuthentication) permission_classes = [IsAdminUser] queryset = ProductInfo.objects.all().order_by('-id') serializer_class = ProductSerializer filter_backends = (filters.SearchFilter,) search_fields = ['title','code','owner__username'] I don't have any problem for GET request. -
What's the reason of my drop down class doesn't iterate?
this is base html codes. I sent categories, products in views.py to base.html. they are defined in models.py as Category, Product as OnetoOne Relationship. <div class="btn-group"> {% for category in categories %} <button type="button" class="btn" id="BASE_SECOND_ADAPTERS"> <a href="{{category.get_absolute_url}}" class="btn" id="C_TITLE">{{category.title}}</a> </button> <button type="button"> <span class="sr-only">Toggle Dropdown</span> <div> {% for product in category.product_set.all %} <div class="button"> <a href="{{product.get_absolute_url}}">{{product.name}}</a> </div> {% endfor %} </div> </button> {% endfor %} </div> this is the problem. first, the href in products iteration doesn't work. When i delete the data-toggle="dropdown" it works. 1Cat - 1-2Pro, 1-1Pro 2Cat - 2Pro 3Cat - 3Pro But Iteration ended before 2Category. If i delete the drop down class, It work. How can i solve it? -
connection error between two devices: ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory
I have two devices that I use as MySql server and Django server. My system, which works on my development device, becomes inoperable when it switches to other devices. Settings on 192.168.3.60: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bildirdi_hurmalar', 'USER': 'gungelir_tirmalar', 'PASSWORD': 'EhuEhu_1793', 'HOST': '192.168.3.65', 'PORT': '3306', } } Apache2 and wsgi on mainside. Error when I run Migrate or runserver: (env) pi@raspberrypi:~/bilidrdi.com $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libmariadb.so.3: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/pi/bilidrdi.com/env/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.7/importlib/__init__.py", line 127, … -
Django don't login after change password use Abstractuser
i custom user use abstractuser class User(AbstractUser): create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) name=models.CharField(max_length=50) phone=models.CharField(max_length=15) position=models.CharField(max_length=30) but when i change password user in adminpage i can't login with login function class LoginClass(View): def get(self,request): if not request.user.is_authenticated: return render(request, 'new_template/signin.html') else: return redirect('user:view_camera') def post(self,request): username1 = request.POST.get('username1') password1= request.POST.get('password1') my_user = authenticate(username=username1,password=password1) if my_user is None: return redirect('/') login(request, my_user) next_url = request.GET.get('next') if next_url is None: return redirect('user:view_camera') else: return redirect(next_url) -
Django data getting issue
Django giving different data to browser and swagger(or postman) it's in swagger(in postman too): But in browser getting wrong data: please any ideas