Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HOW I CAN STORED MY MEDIA FILES OUT OF DEVELPMENT MECHINE IN DJANGO?
how i can store MIDEA_ROOT in out of development server in django. i have huge collection of images that's why I wand to store my images in other server or drive. -
Class 'Horario' is not defined / Class 'Horario' has no 'objects' member
I keep getting this error and I can't seem to find the proper answer to it. I have created a model in models.py class Horario(models.Model): dia = models.CharField(max_length=20) mañana = models.CharField(max_length=20) tarde = models.CharField(max_length=20) and now I am creating a view in views.py to render this in a html file that I have called horario.html def horario(request): context = {'horario' : Horario.objects.all()} return render(request, "horario.html", context) The thing is that I keep getting this error. I have read other threads and the correction to this error seems to be pasting this code in settings.json {"python.linting.pylintArgs": [ "--load-plugins=pylint_django" ],} I don't know how to do this since as I do it I get random errors. Anyone knows a proper way to get this done? -
django don't show form in template
django dont show my form in my template where is the problem? forms.py from django import forms class QuestionForm(forms.Form): massage = forms.CharField(widget=forms.TextInput) views.py from cheatexam_question.forms import QuestionForm def newquestion(request): if request.method == 'POST': form = QuestionForm(request.POST) context = { 'form': form } return render(request, 'homepage.html', context) template <form method="post"> {% csrf_token %} {{ form }} <input class="btn btn-warning form-control" type="submit" value="ثبت سوال"> </form> -
Conditional Execution in Same View
I want my declarations to be user-specific. I chose to do this by making my variable declarations in the view conditional based on user-type. Here's a sample. def order_detail(request, order_id): order = get_object_or_404(Order, id=order_id) if request.user.is_supervisor: user_location = request.user.supervisor.town deliverer = User.objects.filter(deliverer__town=user_location) context={ 'order': order, 'all_delivery_guys_in_town': deliverer } template = 'orders/order_mgt/detail.html' return render(request, template, context) For context, I need supervisors to be able to view a list of available delivery guys within the order detail page. In the code sample, I'm getting an error: local variable 'user_location' referenced before assignment 1. How can I correct this error? 2. Is there a better way of making conditional declarations within the same view? -
Select multiple rows from list to perform action
I have a Table-List which is getting their values from the Database, where each row is a representation of a model in the DB. For now, I can edit or delete row for row. <div class="table-responsive"> <table class="table table-bordered"> <thead class="thead-dark"> <tr> <th scope="col">Select Multiple</th> <th scope="col">Col 1</th> <th scope="col">Col 2</th> <th scope="col">Col 3</th> <th scope="col">Col 4</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> <tr> <td>{{ object.selectedOrNot }}</td> <-- BooleanField? <td>{{ object.value1 }}</td> <td>{{ object.value2 }}</td> <td>{{ object.function1 }}</td> <td>{{ object.function2 }}</td> <td><a href="{% url 'edit' object.id %}">Edit this row</a></td> <td><a href="{% url 'delete' object.id %}">Delete this row</a></td> </tr> </tbody> </table> </div> My Question is: How can I make them selectable (checkbox), to multiple delete or edit desired entries. -
Django, how to get total sum of methods with agregate sum
how to get total sum of methods in django using agregate ? I used this for fields and it work fine but for method it doesn t return anything. class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) def total(self): total = self.invoiceitem_set.aggregate(sum=Sum('subtotal')) return round(total[("sum")] or 0, 2) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) def subtotal(self): return self.price * self.quantity -
Django testing database in a restricted environment
as the title says, I'm restricted in my development environment. I cannot create extra databases for testing purposes and only create local files. Using the environ package for django, the configuration of the database is DATABASES = { 'default': env.db('DATABASE_URL', default='postgres://name@localhost'), } As found in this thread, all I need is a "TEST" key in this configuration. It doesn't have one per default so I've bypassed this by writing db = env.db('DATABASE_URL', default='postgres://name@localhost') db["TEST"] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } This doesn't work however. python manage.py test gives me the following output: Creating test database for alias 'default'... /usr/lib/python2.7/dist-packages/django/db/backends/postgresql/base.py:267: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead. RuntimeWarning Got an error creating the test database: permission denied to create database Type 'yes' if you would like to try deleting the test database '/home/<closed environment>/<project>/config/db.sqlite3', or 'no' to cancel: It still tries to create a database inside an environment in which I do not have the power to alter my … -
How do we display the elements in the dictionary passed as a context object to Django and remove them as user selects it?
I want to display the elements passed through the context object and allow users to unselect or remove items they don't want and submit the form with the remaining items. I am new to Django, I know this could have been done in React using state variable. I tried the following- <select id="mySelect" size="{{mems|length}}"> {% for mem in mems %} <option> {{mem.user}} </option> {% endfor %} </select> <button onclick="myFunction()">remove</button> <script> function myFunction() { var x = document.getElementById("mySelect"); x.remove(x.selectedIndex); } </script> It updates the UI for a second and then again reverts back to the starting state because I guess the mem object is not getting modified in this case and hence again renders the complete list. Is there a better option to display these details and manipulate the DOM based on the requirements in Django? ->mems here is the result of a DB query and has objects with reference to the user model. What I want to return to the server-side is these users, which the admin selects. -
POST request giving KeyError Django DRF
I am trying to make a rest api which takes a POST request and saves the data in my model.But as soon I give the post request it gives me key error. My model is this : class ProductInfo(models.Model): title = models.CharField(max_length=15) image = models.TextField() price = models.CharField(max_length=5) def __str__(self): return self.title class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(ProductInfo, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) proceed = models.BooleanField(default=True) def __str__(self): return self.item.title + ' | ' + self.user.username My serializer which is required in this view: class OrderItemUpdateSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['item_id', 'quantity', 'user_id','proceed'] This is my view.The problem is in the 'update_order_quantity' function.This function is quite similar to 'set_order_item' function which is above 'update_order_quantity' .The error is occuring in the area where I am accessing the validated_data (all of the variables)> I am including the 'set_order_item' because it is similar to 'update_order_quantity' view. Then why 'update_order_quantity' is not working? @api_view(['POST']) @permission_classes([permissions.IsAuthenticated]) def set_order_item(request): serializer = OrderItemSerializer(data=request.data) if serializer.is_valid(): item = serializer.validated_data['item'] quantity = serializer.validated_data['quantity'] queryset = OrderItem.objects.filter(item=item) if queryset.exists(): info = queryset[0] info.quantity += quantity info.save(update_fields=['quantity']) return Response("Succesfully created", status=status.HTTP_201_CREATED) else: serializer.save() return Response("Succesfully created", status=status.HTTP_201_CREATED) return Response("Not created", status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def … -
Group by and Aggregate with nested Field
I want to group by with nested serializer field and compute some aggregate function on other fields. My Models Classes: class Country(models.Model): code = models.CharField(max_length=5, unique=True) name = models.CharField(max_length=50) class Trade(models.Model): country = models.ForeignKey( Country, null=True, blank=True, on_delete=models.SET_NULL) date = models.DateField(auto_now=False, auto_now_add=False) exports = models.DecimalField(max_digits=15, decimal_places=2, default=0) imports = models.DecimalField(max_digits=15, decimal_places=2, default=0) My Serializer Classes: class TradeAggregateSerializers(serializers.ModelSerializer): country = CountrySerializers(read_only=True) value = serializers.DecimalField(max_digits=10, decimal_places=2) class Meta: model = Trade fields = ('country','value') I want to send import or export as query parameters and apply aggregate (avg) over it shown by distinct countries My View Class: class TradeAggragateViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() serializer_class = TradeAggregateSerializers def get_queryset(self): import_or_export = self.request.GET.get('data_type') queryset = self.queryset.value('country').annotate(value = models.Avg(import_or_export)) return queryset I want to get the data in format like: [ { country:{ id: ..., code: ..., name: ..., }, value:... }, ... ] But having an error on country serializer AttributeError: Got AttributeError when attempting to get a value for field `code` on serializer `CountrySerializers`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'code'. -
wagtail: Locale_ID cannot be null
I'm trying to deploy a website with wagtail 2.11 on pythonanywhere. However, I'm unable to save any page models in the frontend. The cause seems to be that in my 'home'-app, migration 0002_create_homepage.py cannot be not applied. Trying so gives me this error (IntegrityError: (1048, "Column 'locale_id' cannot be null")): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 243, in handle post_migrate_state = executor.migrate( File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/migration.py", line 121, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards self.code(from_state.apps, schema_editor) File "/home/yogagarten/yogagarten.pythonanywhere.com/home/migrations/0002_create_homepage.py", line 21, in create_homepage homepage = HomePage.objects.create( File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/query.py", line 447, in create obj.save(force_insert=True, using=self.db) File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/home/yogagarten/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/db/models/base.py", line 789, … -
Import "rest_framework" could not be resolved. But I have installed djangorestframework, I don't know what is going wrong
Here's my settings.py INSTALLED_APPS = [ 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api.apps.ApiConfig' ] -
django is_active does not disable the user
I have a Django project that is like a blog and only a few people are using its panel. There was a user that about 5 people where using and we decided to disable this user and create separate accounts for them. In order to prevent errors in the future we decided just to disable this user and not to delete it. I did it manually using the Django's admin panel. I changed is_active to false but the user still is active and can login to the blog panel. Can you please help me find what is the reason? -
How to update a django moodel value from a button click in a class view
i currently have a model that looks like: Model class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) is_best_answer = models.BooleanField(default=False) def set_best_answer(self): self.is_best_answer = True self.save() def get_absolute_url(self): return reverse('question-detail', kwargs={'pk': self.question.pk}) def __str__(self): return f"Answer by {self.author} with text: {self.content}" I have a Class based Listview which lists all of the answers above. I want to add a button in the template that would update the value in the model of is_best_answer to True e.g. html <a class="btn btn-outline-dark " href="{% url 'select' answer.id %}">Set Best Answer</a> view def set_best_(request, pk): answer = Answer.objects.filter(pk=pk).first() answer.set_best_answer() return redirect('/') url path('answer/<int:pk>/best-answer/', set_best, name='select'), The above works for me, but i have had to call a function rather than anything to do with the class based views. Is there a better way? Dango version 3.1 -
JSONFIeld(null=True): Is allowing null bad practice?
It's my first time working with Django's JSON fields. When going through examples I usually see the field implementations that set the default to an empty object. However, for my purposes, I'd prefer to allow the field to be None as well. Since all the examples set a default, I'm not sure if allowing null will yield any negative consequences I'm unaware of currently. -
this error apears when i try to run this command django-admin.py makemessage -l ar [closed]
this error appears when I try to run this commanddjango-admin.py makemessage -l ar and it opens django-admin.py file and here is what is in it any ideas? -
DoesNotExist at /cafelist/1
I'm making website using Python Framework of 'Django'. I have some problems with Django about post number. when I visit the website https://tutorialproject-ggurf.run.goorm.io/cafelist/1, I receive this message: DoesNotExist at /cafelist/1 Cafe matching query does not exist. settings.py contains: """ Django settings for tutorialdjango 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 import os # 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 = 'si#o7ysrm956&&)&*q0t6uqr^tx$6(_uj85zzhm*rqy4wyzvd5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tutorialdjango.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'tutorialdjango.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / … -
Issue with POST email, returning to same page, templates and httpresponse
First of all, I only started using Django a week ago... so pretty new :). I have a one page website. At the bottom there is a contact form. I am using different components for the website, so for the contact form I have 'contact.html' which is loaded into index.html via {& include ... &}. When someone sends a message via contact form, after click send, the user returns to the same page but with a thank you message instead of the contact form (see screenshot). The issue is that I need to 'kill' the process going on underneath because if I reload the page a message pops and if I resubmit, email gets resend again (see screenshot). I have had a look at httpresponse but I am unsure how to replicate the same process. Anyone could help? This is a screenshot of contact.html and views.py -
unable to access models in Django Application
When i try to run following query in the shell i gets following error from flights.models import * Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'flights How should I access my models inside flights app. why I get error No module flights when i have clearly flights app -
Django TestCase: duplicate database on fixture loading
Context I just arrived on someone's Django project and I encounter a behavior I never experienced before. It has been a one man project for a year and a half now and the app became both quite complexe; like, a lot of dependencies and custom modules Usually, I create a FIXTURE_DIRS in settings.py and it allows me to simply load fixtures while I run my tests: class OnboardedViewTest(TestCase): fixtures = ["users.yaml", "surveys.yaml", "users_survey.yaml"] cbv = OnboardedView() def test_non_onboarded_users_fail_test_func(self): some_testing In the context of this application, it raises the following exception AssertionError: Problem installing fixture '/app/tests/fixtures/users.yaml': Database queries to 'userdata' are not allowed in this test. Add 'userdata' to tests.test_some_app.OnboardedViewTest.databases to ensure proper test isolation and silence this failure. Ok then, what if I explicitly add this userdata database (and the other named default) to this test class ? class OnboardedViewTest(TestCase): fixtures = ["users.yaml", "surveys.yaml", "users_survey.yaml"] cbv = OnboardedView() databases = ["default", "userdata"] def test_non_onboarded_users_fail_test_func(self): some_testing Error I'm then getting a psycopg2.errors.DuplicateDatabase Creating test database for alias 'userdata'... Got an error creating the test database: database "test_some_app" already exists Type 'yes' if you would like to try deleting the test database 'test_some_app', or 'no' to cancel: Traceback (most recent call last): … -
Popup does not open when clicking on marker safari
I am showing position from django model like marker with popup: my view file <script> const MAP_KEY = "{{ MAP_KEY }}"; const added_place_json = JSON.parse('{{ added_place_json | escapejs}}'); </script> my js file for (const place of added_place_json){ L.marker([place.fields.lat, place.fields.long]).bindPopup( `<div class="card" style="width: 15rem;">\n` + ` <h6 class="card-header">Name place:<br>${place.fields.name}</h6>\n` + ` <div class="card-body">\n` + ` <p class="card-text" style="overflow: scroll">Place comment:<br>${place.fields.comment}</p>\n` + ` </div>\n` + `</div>` ).addTo(map) }; This works well on google chrome, but it doesn't work on safari. When I click on the marker in safari nothing happens -
In my Django app, no pictures display on screen
Hi, there. I created CRUD posting app which can upload multiple pictures optionally before. And I tried enter post detail page, text contents, but no pictures have been shown on a display. Here are some parts of my python code which are related with this issue. models.py class Post(models.Model) : title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) text = models.TextField() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Picture(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, default="", null=True) picture = models.BinaryField(null=True, editable=True) content_type = models.CharField(max_length=256, null=True, help_text='The MIMEType of the file') owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post_detail.html <style> .picture_wrap{ display: flex; flex-direction: column; } </style> <h1>{{ post.title }}</h1> {% if picture.content_type %} {% for picture in picture_list %} <div id="picture_wrap" class="picture_wrap"> <img style="max-width:50%;" src="{% url 'posts:post_picture' picture.id %}" onclick="document.getElementById('overlay').style.display = 'block';"> </div> {% endfor %} {% endif %} <p> {{ post.text|linebreaks }} </p> views.py class PostDetailView(OwnerDetailView): model = Post template_name = 'posts/post_detail.html' def get(self, request, pk): x = Post.objects.get(id=pk) pl = Picture.objects.filter(post=x) context = { 'post' : x, 'picture_list' : pl } return render(request, self.template_name, context) Somebody...Please do me some guides on this issue... -
CORS Problem with Caddy Spring and Django Websocket
Hi i have a CORS Problem with my Production environment all dockerized Caddyfile starfinder.domain.com { encode gzip zstd root * /var/www @notStatic { not path /static/* /media/* } reverse_proxy @notStatic starfinder-web:8000 file_server } messages.domain.com { reverse_proxy starfinder-messages:8080 header Access-Control-Allow-Credentials "true" header Access-Control-Allow-Origin https://starfinder.domain.com header Access-Control-Allow-Headers "Authorization" } Javascript var socket = new SockJS('https://messages.domain.com/chat'); Spring @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/chat").setAllowedOrigins("https://starfinder.domain.com").withSockJS(); } } Relevant docker-compose.yml version: "3.7" services: caddy: image: caddy:2.2.1 restart: unless-stopped ports: - "80:80" - "443:443" volumes: - /home/dennis/caddy/Caddyfile:/etc/caddy/Caddyfile - /home/dennis/caddy/caddy_config:/config - caddy_data:/data - /var/www:/var/www starfinder-web: build: ./starfinder command: gunicorn penandpaper.wsgi -b 0.0.0.0:8000 volumes: - ./starfinder/:/usr/src/app/ ports: - 8001:8000 volumes: - /var/www:/var/www starfinder-websocket: build: ./websocket ports: - 8080:8080 entrypoint: java -jar /var/www/starfinder-websocket-1.0-SNAPSHOT.jar When I tried the following: replacing urls (Dockerlike) with starfinder-web:8000 replacing urls with domain.com replacing urls with starfinder.domain.com All resulted in a Access to XMLHttpRequest at 'https://messages.domain.com/chat/info?t=1608371877132' from origin 'https://starfinder.domain.com' has been blocked by CORS policy With the current setup i don't get an explicit error but websocket loses connection immediately and has a 502 Status Code. Chrome Console: Opening Web Socket... abstract-xhr.js:132 GET https://messages.domain.com/chat/info?t=1608373262623 502 Whoops! Lost connection … -
Django save multiple versions of a Image within a class
I have the following function where the avatar the user has uploaded get's converted in two versions (smaller and larger version). Instead of writing this function multiple times for multiple fields of multiple models I would like to reimplement this as a class that I can reuse This is my function: def avatar_tamper(self): if self.avatar: if not (self.avatar_tn and os.path.exists(self.avatar_tn.path)): image = Image.open(self.avatar) outputIoStream = BytesIO() outputIoStream_tn = BytesIO() baseheight = 500 baseheight_tn = 175 hpercent = baseheight / image.size[1] hpercent_tn = baseheight_tn / image.size[1] wsize = int(image.size[0] * hpercent) wsize_tn = int(image.size[0] * hpercent_tn) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized_tn = image.resize((wsize_tn, baseheight_tn)) imageTemproaryResized.save(outputIoStream, format='PNG') imageTemproaryResized_tn.save(outputIoStream_tn, format='PNG') outputIoStream.seek(0) self.avatar = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.avatar.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) outputIoStream.seek(0) self.avatar_tn = InMemoryUploadedFile(outputIoStream_tn, 'ImageField', "%s.png" % self.avatar.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream_tn), None) elif self.avatar_tn: self.avatar_tn.delete() This is how I call the function at models.py save call: def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) avatar_tamper(self) super(User, self).save(*args, **kwargs) return self.user Can smb help? Kind regards -
Django CSS files are missing while deploying using IIS
I need your assistance. I am deploying Django app on Windows Server 2019. And This went perfectly but CSS files are missing. This the path of my application: C:\inetpub\wwwroot\myapp. And the static folder is under myapp. I added virtual directory in IIS manager and it is set as below: in Alias: static in Physical path: C:\inetpub\wwwroot\myapp\static please any assist?