Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pytesseract - using .traineddata file on hosted server (Heroku)
I have a Vue, Django integrated project. I hosted the Vue project on Netlify and the Django project on Heroku. A python script (integrated into Heroku) is called on certain buttons which extract data and posts this to the Django API to be viewed on the frontend. I have trained a font type for my pytesseract OCR script. However, when i run it on Heroku, it seems like i can only use the 'eng' (normal font) as 'language' for my pytesseract image_to_string function. If I have the .traineddata file of the font type that I want to use, how can I use this file within the pytesseract functions? I can call the individual file, but I need the right TESSDATA_PREFIX as well. Does someone know how to deal with this? Thanks! -
Vue development version works but production doesn't (Vue CLI + Django)
I have build a site using Django and Vue+Vuetify, with Django running the backend and Vue the front end. I have been using Vue CLI to compile by .vue files. However, now that I am preparing to move the code to production version, I have run into following issue: Vue app created by vue-cli-service build does not work. When run in development mode with vue-cli-service build --mode development it all works fine, but the build version doesn't work. The JavaScript console doesn't give any errors. Almost nothing renders and what little renders doesn't seem to have styling included. However, I can see that axios calls do work, and using inspector shows that various elements are added to the body, they simply do not render. However, looking at my package.json I can't see any obvious errors. { "name": "vueapp", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "build-dev": "vue-cli-service build --mode development", "lint": "vue-cli-service lint" }, "dependencies": { "axios": "^0.21.1", "core-js": "^3.6.5", "vue": "^2.6.11", "vue-router": "^3.2.0", "vuetify": "^2.4.0" }, "devDependencies": { "@mdi/font": "^5.9.55", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-router": "~4.5.0", "@vue/cli-service": "~4.5.0", "babel-eslint": "^10.1.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^6.2.2", "material-design-icons-iconfont": "^6.1.0", "sass": "~1.32.0", "sass-loader": "^10.0.0", "vue-cli-plugin-vuetify": "~2.4.1", "vue-template-compiler": "^2.6.11", … -
Tooltip ignores bootstrap5 css
I am having problems using bootstrap 5 tooltips in my webapp. My django template works as follows: {% block css %} <!-- Bootstrap CSS --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <!-- Bootstrap CSS for Tabulator --> <link rel="stylesheet" href="{% static 'css/tabulator_bootstrap4.min.css' %}"> {% endblock %} ... {% block javascript %} <!-- jQuery --> <script src="{% static 'js/jquery-3.6.0.min.js' %}"></script> <!-- tabulator --> <script src="{% static 'js/tabulator.min.js' %}"></script> <!-- Bootstrap JavaScript --> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> <!-- bootstrap select picker --> <script src="{% static 'js/bootstrap-select.js' %}"></script> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css' %}"></script> <!-- font awesome --> <script src="{% static 'fontawesome_free/js/all.min.js' %}"></script> {% endblock javascript %} In my html I use this code: var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')) var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) { console.log("added a tooltip"); return new bootstrap.Tooltip(tooltipTriggerEl) for this button, which shows just an ordinary tooltip: `<button type = button class="btn btn-sm btn-primary" data-bs-toggle="tooltip" data-bs-placement="top" title="${row.tooltip}"> <i class="fas fa-print"></i> </button>`; I can see the added a tooltip message never shows ... why? -
what is happening on os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
while iam creating a bot using botframework within a django application, i am not able to call the models of that appliction from the bot.i got the solution as put """os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = Ture""" in the settings.py file.its works fine for me.But iam curious to know what is happening while i making this step.is it safe? -
Print entire HTML table to .pdf Doc || Python Django
I currently have an app that prints a trial balance in a table format from a MySQL database. The code is shown below and so is the end result of the code. I am trying to find a way to print that exact data in that exact format to a pdf by the push of a button. If anyone has code to do this, please assist. Views.py: def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] '\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Credit"] = row[2] rdict["Debit"] = row[3] xAll_l.append(rdict) return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l}) Kyletrb.html: <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous"> {% extends "main/base.html"%} {% block content%} <h1 class = 'center'>Kyle Database Trial Balance</h1> <br> <style> .img-container { text-align: center; width: 150px; height: 100px; } </style> <style> .center{ text-align: center; } </style> <style> .table-container{ border-spacing: 10px; padding-left: 300px; text-align: center; border-bottom: 1px solid #ddd; border-top: 1px solid #ddd; } </style> </div> <br> <br> <div class="table-container"> <table style="width:80%"> … -
Troubles with downloading and saving a document in django
I have a few problems, cannot figure it out, maybe there are connected. Problem 1.1: file is exported in django documentation and it works, but when I try to rename it, it has some error. I want to be like this with pd.ExcelWriter(newdoc + 'output.xlsx') as writer: in order to every file has a "new" name. I got this error, TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str' Problem 1.2: How to add path where to save? Problem 2: I get to download file but it is empty, and name of document is Donwload.xlsx. I want to be like this, but this got many errors... filename = newdoc + '_calculated.xlsx' response = HttpResponse(output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response When I do this, I got this... in terminal UserWarning: Calling close() on already closed file. and this in browser TypeError at / unsupported operand type(s) for +: 'InMemoryUploadedFile' and 'str' This is views.py, and if code is like this, there are no errors but I got to download empty document. def my_view(request): if request.method == "POST": form = DocumentForm(request.POST, request.FILES) if form.is_valid(): output = io.BytesIO() newdoc = request.FILES['docfile'] dfs = pd.read_excel(newdoc, sheet_name=None, index_col=[0]) with … -
Django Logging Emails not Arriving while other Emails do
I'm currently using this configuration to receive logging emails from my development as well as my production servers. ADMINS = [('Test1', 'somename@example.com'), ('Test2', 'someothername@example.com')] SERVER_EMAIL = "correctsender@example.com" LOGGING = { 'version': 1, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'include_html': True, }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, } } The email is then sent with the following configuration for SMTP. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'correctsender@example.com' EMAIL_HOST_PASSWORD = 'thepassword' # normally loaded from environment EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'correctsender@example.com' I have enabled "Less secure Apps" in Gmail. For a few days now, we suspected that error logging was broken. Today we confirmed that the Mails sent via AdminEmailHandler were not arriving, while all other Mails send via the ordinary mail pipeline (no matter if from celery workers or directly from the server) were. Test with other backends showed that the Mail was sent by django. A quick test with smtplib showed that login was not blocked. How can it be that certain mails are accepted by Gmail while others, only differing in content, are not? Also, is there a place where rejected Emails are kept … -
'OnlineClassSerializer' object has no attribute 'onlineClassItems_set'
Hi I am using django and django-restframework for my website can you help me with this problem the problem is when I am trying to get all the data from the other serializer it can not find the attribute of the data how can I get the whole serialized data from another model ? the models.py class OnlineClass(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name= models.CharField(max_length=255 ,null=True , blank=True) subject= models.ForeignKey(Subject, on_delete=models.SET_NULL, null=True, blank=True) price=models.DecimalField(max_digits=7, decimal_places=0, null=True,blank=True) image= models.ImageField(null=True,blank=True) createdAt= models.DateTimeField(auto_now_add=True) category= models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) numReviews= models.IntegerField(null=True, blank=True, default=0) isAvailable = models.BooleanField(default=False,null=True,blank=True) hasOff = models.CharField(max_length=200,null=True,blank=True) rating= models.DecimalField(max_digits=7, decimal_places=2, null=True,blank=True) students= models.IntegerField() def __str__(self): return self.name class OnlineClassItems(models.Model): onlineClass= models.ForeignKey(OnlineClass, on_delete=models.CASCADE, null=True, blank=True) id= models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) title= models.CharField(max_length=255 ,null=True , blank=True) description= models.TextField(null=True , blank=True) file= models.FileField(null=True,blank=True) image= models.ImageField(null=True,blank=True) def __str__(self): return self.title here is the code the problem is in serializer.py class OnlineClassItemsSerializer(serializers.ModelSerializer): comments = serializers.SerializerMethodField(read_only=True) class Meta: model=OnlineClassItems fields="__all__" def get_comments(obj,self): comments = obj.comments_set.all().order_by("-createdAt") serializer = CommentsSerializer(comments , many=True) return serializer.data class OnlineClassSerializer(serializers.ModelSerializer): onlineclassitems= serializers.SerializerMethodField(read_only=True) reviews= serializers.SerializerMethodField(read_only=True) teacher= serializers.SerializerMethodField(read_only=True) class Meta: model =OnlineClass fields ="__all__" def get_onlineclassitems(obj,self): onlineclassitems= obj.onlineClassItems_set.all().order_by("-createdAt") #error is here serializer = OnlineClassItemsSerializer(onlineclassitems , many=True) return serializer.data def … -
can't set attribute in django
There are 2 fields id and video_id in model,but i don't know how to assign the id value to request.data view def post(self, request, *args, **kwargs): try: if 'id' in kwargs: id = self.kwargs.get('id') else: id = request.learner request.data.id = id print(request.data) serializer = Serializer(data=request.data) serializer def create(self, validated_data): print('v', validated_data) recommended_courses = RecentlyViewedVideos.objects.create(**validated_data) return recommended_courses And the error is "Id- This field is required." I chose different methods to find the solution, but it did not work. Give me a solution to overcome this problem -
Django Docker deployment
Having never made a website or used Docker before, I've built a Django application with MySQL inside Docker and am finally ready for deployment, but completely overlooked that a web server was necessary. I've been quite stuck getting it to work and was wondering what approach others used. Is Apache or Nginx easier to set up, and does it need to be set up inside the Dockerfile and docker-compose.yml file, or can it be set up externally? I haven't been able to find much relevant information for this, so any advice or links would be appreciated. -
adding links to data table rows in javascript or jquery
I'm using django. Here is my code: <div class="card-body"> <div class="table-responsive"> <table id="datatables" class="table table-striped table-bordered text-nowrap w-100"> <thead> <tr> <th class="wd-15p">devEUI</th> <th class="wd-15p">appID</th> <th class="wd-20p">Type machine</th> <th class="wd-20p">Date création</th> </tr> </thead> <tbody> {% for machine in machines %} <tr> <a href="{% url 'details_of_element' %}"> <td>{{machine.devEUI}}</td> <td>{{machine.appID}}</td> <td>{{machine.type_machine}}</td> <td>{{machine.date_creation}}</td> </a> </tr> {% endfor %} </tbody> </table> </div> </div> It does not work. I want to add a link to each line to see the details of each item. How can I do this with django, jquery or javascript? -
FileNotFoundError: [Errno 2] No such file or directory in react with docker | python manage.py collectstatic is not working inside docker container
This is my django backend Dockerfile: FROM python:3.9.5-slim ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update && apt-get install build-essential python-dev -y COPY requirements.txt /var/www/html/requirements.txt RUN pip install -r /var/www/html/requirements.txt && pip install uwsgi WORKDIR /var/www/html COPY . . EXPOSE 8000 CMD ["uwsgi", "--http", ":9090", "--wsgi-file", "IMS/wsgi.py", "--master", "--processes", "4", "--threads", "2"] And this is my react Docker file: FROM node:13.12.0-alpine WORKDIR /var/www/html COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 And here is my docker-compose.yml file version: "3.3" services: backend: build: context: ./backend command: gunicorn IMS.wsgi --bind 0.0.0.0:8000 ports: - "8000:8000" frontend: build: context: ./frontend/ims volumes: - react_build:/frontend/ims/build/static nginx: image: nginx:latest ports: - "8089:8080" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build/frontend/ims/build/static depends_on: - backend - frontend volumes: react_build: -
can I call a function to set my USERNAME_FIELD = ''?
can I call a function in USERNAME_FIELD = '' to create an optional choice for login, using email or phone number? if yes how? -
Linking cart model to stripe checkout
How can I link price and items from cart Model to the Stripe checkout in Django Web Framework? I get and ValueError at /create_checkout_session when I changed default settings to the code below. When I leave it unchanged as default from the Stripe page it worked but of course it was a test example of checkout.. views.py @csrf_exempt def create_checkout_session(request): MY_DOMAIN = 'localhost:8000' cart = Cart.objects.get(order_user=request.user) try: session = stripe.checkout.Session.create( line_items=[ { 'price_data': { 'currency': 'usd', 'unit_amount': cart.total, 'product_data': { 'name': cart.order_items.title } }, 'quantity': 1, }, ], payment_method_types=[ 'card', 'p24', ], mode='payment', success_url= request.build_absolute_uri(reverse('success-page')) + '?session_id={CHECKOUT_SESSION_ID}', cancel_url= request.build_absolute_uri(reverse('cancel-page')), ) except Exception as e: return print(e) return redirect(session.url, code=303) models.py class OrderItem(models.Model): order_item = models.ForeignKey(Item, on_delete=CASCADE, null=True) quantity = models.IntegerField(default=1) class Cart(models.Model): order_user = models.OneToOneField(User, on_delete=CASCADE) order_items = models.ManyToManyField(OrderItem) ordered = models.BooleanField(default=False) total = MoneyField( default=0.00, decimal_places=2, max_digits=11, default_currency='USD') class Item(Visits, models.Model): title = models.CharField(max_length=150) price = MoneyField( decimal_places=2, default=0, default_currency='USD', max_digits=11, ) image = models.ImageField(upload_to='pictures', default='static/images/man.png') description = models.TextField(default="Item") visits = models.IntegerField(default=0) urls.py urlpatterns = [ path('create_checkout_session', views.create_checkout_session, name='checkout-page'), path('success', views.success, name='success-page'), path('cancel', views.cancel, name='cancel-page') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML form to get into the checkout: <form action="{% url 'checkout-page' %}" method="GET"> <button type="submit">Checkout</button> </form> -
Why oauth2 url is not opened on my client side?
I have a problem about my google drive oauth2. I have this code : def getService(creds): service = build('drive', 'v3', credentials=creds) return service def getCredentials(): # If modifying these scopes, delete the file token.json. SCOPES = ['https://www.googleapis.com/auth/drive'] """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'code_clientXXX.json', SCOPES) creds = flow.run_local_server(port=0) print(creds) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) return creds When I run in localhost, i works very well, this url is automatically opened on my browser: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=XXXX&[..............] But, when I deploy my front (angular app) and my back (django app) on a distant server, using docker. There is a problem. 1 - If my token.json is already generated : It works … -
Is editable=False required?
I am developing a model, the only actions that can be performed on an instance of it are view and delete. Moreover, all these actions must take place in the StackedInline, which is bound to the ModelAdmin class of another model. Model example: class IncludingModel(models.Model): ... class ReadAndDeleteOnlyModel(models.Model): field1 = models.TextField(verbose_name="First field", editable=False) field2 = models.TextField(verbose_name="Second field", editable=False) including_model_instance = models.ForeignKey(IncludingModel, related_name="read_and_delete_only_instances") Admin example class ReadAndDeleteOnlyModelInline(admin.StackedInline): model = ReadAndDeleteOnlyModel readonly_fields = ("field1", "field2") def has_add_permission(self, request, obj): return False @admin.register(IncludingModel) class IncludingModelAdmin(admin.ModelAdmin) inlines = (ReadAndDeleteOnlyModelInline,) Interaction with ReadAndDeleteOnlyModel instances occurs only in IncludingModelAdmin. After removing editable = False, my fields are still read-only due to the fact that I specified them in readonly_fields. This begs the question, is editable = False needed in my case? -
Conversion failed when converting from a character string to uniqueidentifier in react-redux
I am using Django and GraphQl for backend and React-redux for front end. I have implemented a save button but I get an error whenever the save action is triggered. I am trying to pick two foreign keys using their UUid's. This is the error ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting from a character string to uniqueidentifier. (8169) (SQLExecDirectW)') -
Override Wagtail delete confirmation message
I would like to override the delete message (to make it more informative, like “if you delete, you will lose 5 items belong to your account”). My idea is whenever someone deletes my “Member”, it will also delete all the items belong to that member, and the confirmation message should provide more information. I find that the confirmation message comes from a function named “confirmation_message” in wagtail.contrib.modeladmin.views, at DeleteView class. This function will provide the message for Wagtail delete's template. This is my Member class: class Member(ClusterableModel): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) phone = PhoneNumberField(blank=True) phone_2 = PhoneNumberField(blank=True) inside_scoop = models.TextField(blank=True) lifetime_member = models.BooleanField(default=False) activation_date = models.DateField(null=True, blank=True, default=timezone.now) deactivation_date = models.DateField(null=True, blank=True) points_balance = models.IntegerField(default=0) favorite_properties = models.ManyToManyField( PropertyPage, blank=True, related_name="favorite_properties" ) base_form_class = MemberFormAdmin def delete(self: object, *args: list, **kwargs: dict) -> None: PropertyPage.objects.filter(owner=self.user).delete() self.user.delete() return super(self.__class__, self).delete(*args, **kwargs) This is the default confirmation message that comes from Wagtail: this lies in wagtail -> contrib -> modeladmin -> views.py And this is the delete template: this lies in wagtail -> contrib -> modeladmin -> templates → modeladmin → delete.html This is the message for staff in admin portal: Please help me with this case, thank you. -
RelatedObjectDoesNotExist error in save method in Django
I was writing a save method in OrderCompleteStatus model. I want to make , in any order , if the order's OrderCompleteStatus.pickup is True then , for the items of that same order , and for OrderItemCompleteStatus of that item , i want to make OrderItemCompleteStatus.pickup = True. I have tried but i get RelatedObjectDoesNotExists error in line 458 . My models are : class OrderCompleteStatus(models.Model): order = models.OneToOneField('Order', on_delete=models.SET_NULL , null=True) warehouse =models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) def __str__(self): return "Order" + " " + str(self.order) class Meta: verbose_name_plural = 'Order Complete Status' def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.warehouse and self.pickup and self.delivered : self.order.complete = True self.order.save(update_fields=['complete']) if self.pickup : order = self.order orderitems = order.orderitem_set.all() for item in orderitems: item.orderitemcompletestatus.pickup = True item.orderitemcompletestatus.save(update_fields=['pickup']) class OrderItemCompleteStatus(models.Model): order_item = models.OneToOneField('OrderItem', on_delete=models.SET_NULL , null=True) seller = models.BooleanField(default=False) warehouse = models.BooleanField(default=False) pickup = models.BooleanField(default=False) delivered = models.BooleanField(default=False) received_by_customer = models.BooleanField(default=False) def __str__(self): return "Order Item " + " " + str(self.order_item) class Meta: verbose_name_plural = 'Order Item Complete Status' def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.seller and self.warehouse and self.pickup and self.delivered : self.order_item.complete = True self.order_item.save(update_fields=['complete']) class OrderItem(models.Model): product = models.ForeignKey('Product' , … -
TypeError: serve() got an unexpected keyword argument 'ducoment_root'
Internal Server Error: /media/productimg/1.png Traceback (most recent call last): File "C:\Users\sajja\Envs\fyp\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\sajja\Envs\fyp\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: serve() got an unexpected keyword argument 'ducoment_root' [01/Sep/2021 03:39:53] "GET /static/app/webfonts/fa-solid-900.woff2 HTTP/1.1" 404 1852 [01/Sep/2021 03:39:53] "GET /media/productimg/1.png HTTP/1.1" 500 60242 -
Django Serializer def validate validation error
In def validate i have unauthorized request error. When i check these conditions separately, they are okay. But when i try to use them both, it raises ValidationError. Am i doing something wrong? class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) public_profile = models.BooleanField(default=True) class UserFollowSerializer(serializers.ModelSerializer): class Meta: model = UserFollow fields = ('id',"author","profile") def validate(self, attrs): attrs = super().validate(attrs) if (attrs['author'].id == self.context['request'].user) and (attrs['profile'].public_profile == False): return attrs raise ValidationError('Unauthorized Request') -
ImportError: No module named 'django'
I am using django to make my site on server. But, I get the error. I have checked out if Django was installed. I try to add some code in wsgi.py, but I still can't fix it. import os, sys sys.path.append('<PATH_TO_MY_DJANGO_PROJECT>/ueuuop8591_project') sys.path.append('<PATH_TO_VIRTUALENV>/Lib/site-packages') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ueuuop8591.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() Here is the error log [Wed Sep 01 18:28:26.950872 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] mod_wsgi (pid=21176): Target WSGI script '/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py' cannot be loaded as Python module. [Wed Sep 01 18:28:26.950969 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] mod_wsgi (pid=21176): Exception occurred processing WSGI script '/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py'. [Wed Sep 01 18:28:26.951114 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] Traceback (most recent call last): [Wed Sep 01 18:28:26.951180 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] File "/home/ueuuop8591/Django/ueuuop8591_project/ueuuop8591_project/wsgi.py", line 18, in <module> [Wed Sep 01 18:28:26.951190 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] from django.core.wsgi import get_wsgi_application [Wed Sep 01 18:28:26.951224 2021] [wsgi:error] [pid 21176] [remote 223.141.158.212:57146] ImportError: No module named 'django' -
django pillow loading multiple images is slow
I am fetching images from an api and rendering in django app. Loading images this way is really slow. template tag def url(id): url = f'http://api.com/image?id={id}' response = requests.get(url) img = Image.open(BytesIO(response.content)) data = BytesIO() img.save(data, "PNG") data.seek(0) encoded_img_data = base64.b64encode(data.getvalue()) return encoded_img_data.decode('utf-8') html <img src="data:image/png;base64,{{row.image_md5|url}}" /> it works, but it's 1 second for loading an image. Is there a way to load all images faster this way? -
django orm filter datetime by integer of days
I have a model called with AccessDuration with two important fields are duration (int), and lab_start_date (datetime). bassed on both fields, I want to check whether the access duration is expired or yet. It's done by using model functions. class AccessDuration(models.Model): .... duration = models.PositiveIntegerField(default=30, help_text=_('In days')) lab_start_date = models.DateTimeField(verbose_name=('Start Date'), null=True) @property def expiration_date(self) -> Union[timezone.datetime, None]: if self.lab_start_date: return self.lab_start_date + timezone.timedelta(days=self.duration) return None @property def is_expired(self) -> bool: """ to check whether duration already expired or yet """ if self.expiration_date: return timezone.now() > self.expiration_date return False But, I need this filter to can be use in my django admin page. I have tried with this, but seems still doesn't working: from django.db import models from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from .models import AccessDuration class AccessListFilter(admin.SimpleListFilter): title = _('Is Expired') parameter_name = 'is_expired' def lookups(self, request, model_admin): return [ ('true', _('True')), ('false', _('False')) ] def queryset(self, request, queryset): value = self.value() expiration_date = models.ExpressionWrapper( models.F('lab_start_date') + (timezone.timedelta(days=1) * models.F('duration')), output_field=models.DateTimeField() ) if value == 'true': return queryset.annotate(expiration_date=expiration_date)\ .filter(expiration_date__lt=timezone.now()) elif value == 'false': return queryset.annotate(expiration_date=expiration_date)\ .filter(expiration_date__gte=timezone.now()) return queryset class AccessAdmin(admin.ModelAdmin): list_filter = (AccessListFilter, 'lab_start_date') admin.site.register(AccessDuration, AccessAdmin) The error I found; -
How to apply user specific permission?
I am new in Python Django.I have a question in one situation.As you see in the photos,I have an application.Firstly Users can login system and they can add new item to list.Problem is that when all users login,they are adding items to the same database.For example when 2 users login,they will see same items.I want apply specific list for each user.When each user login,they should see their own list.I know that I have to apply one to many relationship but I don't know how can I do this.I am adding screenshots of related codes. note: my item's model name is Student Application view Item database registered user for authentication from django.db import models class Student(models.Model): sid=models.CharField(max_length=7) sname=models.CharField(max_length=255) scontact=models.CharField(max_length=15) def __str__(self): return self.sname