Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix LNK1104: cannot open file 'MSVCRT.lib' outside c++
I want to install django-admin in my project in virtualenv. After pip install django-admin I receive: fatal error LNK1104: cannot open file 'MSVCRT.lib' Microsoft Visual Studio 10.0\\VC\\Bin\\link.exe' failed with exit status 1104 I found solutions to fix this for all projects in c++, but can't find any solutions for django. Tried to create c++ project - works. For other non virtualenv c++ required libraries (ex. numpy) : Broken toolchain: cannot link a simple C program. -
Django staticfiles not loading in Production
I have created one Django project. It has several static files like CSS, JS, images etc. Below is file structure mysite |- mysite |- myapp |-- static |-- CSS |-- JS |- staticfiles settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) In developer mode, I'm able to serve the static files. But to serve static files in Production mode I run below command python manage.py collectstatic And it collected all the static files to staticfiles directory at the root of the project. But with some warnings like one below Found another file with the destination path 'admin/css/vendor/select2/LICENSE-SELECT2.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. But when I visit my website css and js were missing. It didn't find the static files. I'm using Django 2.2. I've 'django.contrib.staticfiles' in my installed apps. But it's not serving files. Please don't mark it as duplicate. I've tried all possible ways but I didn't get success with it, that's why I've created a new question. -
Get data of previous months data in python django
Hi I am using django and my model look like this class SignupMonthlyPoint(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='SignupMonthlyPoints') timestamp = models.DateTimeField(auto_now_add=True) value = models.FloatField() And I am getting last 30 days data like this def get_signupfromlinkmonthlypoints(): total_for_last_month =request.user.profile.SignupMonthlyPoint.filter( timestamp__gt=datetime.datetime.now() - relativedelta(months=1) ).aggregate( total=Sum('value') )['total'] print(total_for_last_month) but When I analyzed its last 30 days data not last month data. I want to make this like data of whole august month as it's last month of September, then data of whole july month and so on. -
Need to have url like /stories/<id>/episodes/1
When I create a new episode, id automatically increments. What I need? Imagine, I have 10 episodes for a different stories, so if I create an episode for story(for example, with id=5), it will assign id for new episode as 11. Url will be like /stories/5/episodes/11, but I need something like /stories/5/episodes/1. It would be good to store episodes id according to story, not all number episodes from all stories. How to do that? class Story(models.Model): title = models.CharField(max_length=255) description = models.TextField(max_length=255) cover = models.ImageField(upload_to=upload_location) created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Episode(models.Model): title = models.CharField(max_length=255) description = models.TextField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) story = models.ForeignKey(Story, on_delete=models.CASCADE) -
Calling a python function from bootstrap button in django web frame work
I am building a web interface using Django and want to run some code of python on button click event of bootstrap button. I want to know in which python file should I write that code and how to call that function. The code I am trying to run is using subProcess module of python to run a command on terminal and get error and output streams. The code it self is working fine in python 3.7 but I don't know how to call that code on button click. I am using django for the first time. <button type="button" class="btn btn-primary" name="sra" onclick="myFunction()">Primary</button> <script> function myFunction(){ #this is the part where I am stuck } </script> -
Django select2 chained dropdown with elasticsearch
I would like to have a chained dropdown with elasticsearch as back end using Django. I have two indices in ES and I will use index A for the chained dropdown and index B for the search given contraints selected in index A using common fields. Like below where after selecting Lv0, Lv1 and clicking submit form(I hope this can pass the selected variables to index B for query), query can be made over index B. I have successfully searched over index B alone many days ago but I have been stuck in adding index A and having it work with index B for a week. I have below using django-select2. models.py class Lv0(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __str__(self): return self.name class Lv1(models.Model): name = models.CharField(max_length=255) lv0 = models.ForeignKey('Lv0', related_name="lv1", related_query_name="lv1",on_delete=models.CASCADE) class Meta: ordering = ('name',) def __str__(self): return self.name forms.py from esearch import models from esearch.models import Lv0, Lv1 #select2 dependent searchable fields class CateChainedSelect2WidgetForm(forms.Form): lv0 = forms.ModelChoiceField( queryset=Lv0.objects.all(), label='Lv0', widget=ModelSelect2Widget( search_fields=['name__icontains'], max_results=500, #dependent_fields={'vertical': 'verticals'}, attrs={'data-minimum-input-length': 0}, ) ) lv1 = forms.ModelChoiceField( queryset=Lv1.objects.all(), label='Lv1', widget=ModelSelect2Widget( search_fields=['name__icontains'], dependent_fields={'lv0': 'lv0'}, max_results=500, attrs={'data-minimum-input-length': 0}, ) ) views.py class TemplateFormView(FormView): template_name = 'esearch/base.html' Above only creates two dependent … -
How do I make it go to the home page?
I'm using Django and after login, I redirect to the main page. If there are still tokens in the session, I don't want to go to the login page. How can I do that ? class LoginPageView(TemplateView): template_name = 'login.html' def get(self, request, *args, **kwargs): if request.session['token']: return redirect('login') else: return redirect('home') My Urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.HomePageView.as_view(), name='home'), path('login/', views.LoginPageView.as_view(), name='login'), url(r'^sign-in/$', views.sign_in, name='sign-in') ] I wrote code like this, but it doesn't work. KeyError at /login/ 'token' -
docker-compose up fails when docker-compose run is successful
I am trying to dockerize my Django-postgres app and run 2 commands using docker-compose My Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My docker-compose.yml is: version: '3' services: web: build: . command: bash -c "python app/manage.py migrate && python app/manage.py runserver 0.0.0.0:8000" volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres ports: - "5432:5432" environment: POSTGRES_PASSWORD: password and my settings .py has the following database code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', } } My db and web containers are up when I run: docker-compose run web python app/manage.py migrate docker-compose run web python app/manage.py runserver 0.0.0.0:8000 But when I run docker-compose up it fails with the error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "db" (172.23.0.2) and accepting web_1 | TCP/IP connections on port 5432? Can anyone please help me find where I am going wrong? -
How to retrieve Django model id from admin page via javascript
Suppose I have a Django model like this one. class Car(models.Model): speed = models.IntegerField() color = models.CharField(max_length=120) I registered it in admin via admin.site.register(Car) I want to add custom JS button for admin site object view, which will alert value of a color of an instance of a Car model. So when I press it I get something like "The car with id 13 is red" How can I get id of an object and value of a color field via JavaScript? -
How to query data in order to show in chart
How to show specific data on html page using chart.js and django i am trying this method i can see data api view but cannot see on chart. i am able to see data except my query set. Is there any doc for this. Please help me i am beginner in django, Here is my Views.py class secondapi(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): qs = Add.objects.all().aggregate(Sum('budget')) # here is problem labels = ["sum", "Blue", "Yellow", "Green", "Purple", "Orange"] default_items = [qs, 23, 2, 3, 12, 2] data = { "newlabels": labels, "newdata": default_items, } return Response(data) html page <script> var endpoint = '/api/chart/data/' var labels = [] // var defaultData = []; // $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata console.log(labels) var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, // CHANGED datasets: [{ label: '# of Votes', data: defaultData, // CHANGED }] } }) }, error: function(error_data){ console.log("error") console.log(error_data) } }) </script> <div class='col-sm-6'> <canvas id="myChart"></canvas> </div> </body> </html> -
How to get the information of a specific object that is retrived from a django model using for loop
I have a boostrap slider which is populating using for loop and django model objects now I want that if I click on any of the slider object then it show me the information related to that specific object which I clicked the Information must be retrived from the django model. Thanks In Advance please help me to get out of this situation .. Here is my code which is populating the slider. I want when I clicked on any object in the loop it should only show me the information related to that object. {% for product in products %} <div class="services-block-two"> <div class="inner-box"> <div class="image"> <a href="building-construction.html"><img src="/{{ product.prd_logo }}" alt="" /></a> </div> <div class="lower-content"> <h3><a href="building-construction.html">{{ product.prd_name }}</a></h3> <div class="text">{{ product.prd_des }}</div> <a href="building-construction.html" class="read-more">Read More <span class="arrow flaticon-next"></span></a> </div> </div> </div> {% endfor %} -
why am getting error by running python manage.py runserver command?
when am trying to run python manage.py runserver am getting this error why ? its when i done cd haddygirl and the command python manage.py runserver plese help me !!!? DLL load failed means ? C:\Users\Lazxy\haddygirl>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Lazxy\Anaconda3\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Lazxy\Anaconda3\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Lazxy\Anaconda3\lib\importlib__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1006, in _gcd_import File "", line 983, in _find_and_load File "", line 967, in _find_and_load_unlocked File "", line 677, in _load_unlocked File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\contrib\auth\models.py", line 2, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\contrib\auth\base_user.py", line 47, in class AbstractBaseUser(models.Model): File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\base.py", line 117, in new new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\models\options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Users\Lazxy\Anaconda3\lib\site-packages\django\db\utils.py", … -
Django logs colors depending on error level, without module
I use the standard Django logging based on Python’s builtin logging module. My logging configuration in settings.py in is close to the following: import logging logger = logging.getLogger(__name__) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '\x1b[33;21m{levelname} {asctime} {module} {process:d} {thread:d}\x1b[0m: {message}', 'style': '{', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'sentry': { 'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler', 'tags': {'custom-tag': 'x'}, }, }, 'loggers': { '': { 'handlers': ['console', 'sentry'], 'level': 'DEBUG' if DEBUG else 'WARNING', 'propagate': True, }, }, } I would like to know if it is possible to have ansi color (in this example, \x1b[33;21m) depending on levelname in the format, without installing additional modules like colorlog. -
Django - can't start server
I am getting the following error when I try to start the server locally (./manage.py runserver). Posting the question after spending 5 hours of searching solution. Attached the error stack. I am using Django 2.2.2. Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "./manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 60, in execute super().execute(*args, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 95, in handle self.run(**options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 102, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 585, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 570, in start_django reloader.run(django_main_thread) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 288, in run self.run_loop() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 294, in run_loop next(ticker) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 334, in tick for filepath, mtime in self.snapshot_files(): File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 350, in snapshot_files for file in self.watched_files(): File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 249, in watched_files yield from iter_all_python_module_files() File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 103, in iter_all_python_module_files return iter_modules_and_files(modules, frozenset(_error_files)) File "/home/santhosh/Desktop/working_dir/piccolo/venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 116, in iter_modules_and_files if module.__name__ == '__main__': File "/usr/lib/python3/dist-packages/py/_apipkg.py", line 171, in __getattribute__ return getattr(getmod(), name) … -
How to store user files in django that are internally downloaded
So i am making a website where people can download and visualize some data that is downloaded from another website, and I can't figure out how to store this data in Django .Also the data should be stored separately for every user. And is in a folder format. Maybe i may have to make a model for it or something else. Pls help me I havent tried to use the file system because i dont know how to store data that is internally downloaded from another website(isnt uploaded by the user). from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UserManager from django.db import models from django.contrib.auth import get_user_model User_auth = get_user_model() ............ class GoogleFile(models.Model): user = models.ForeignKey(User_auth, on_delete=models.CASCADE, null=True) data = models.FileField(upload_to='user_google_data') class FacebookFile(models.Model): user = models.ForeignKey(User_auth, on_delete=models.CASCADE, null=True) data = models.FileField(upload_to='user_facebook_data') -
how to deploy Web server & API server in 1 heroku app? Heroku + Docker (deployed with heroku.yml)
I want to deploy Vue app whose script has a couple of ajax request to django API server like follows: getRecordList: function(){ this.records = []; this.$axios .get('http://[ip address for API server]') .then(response => {}) .catch(err => {}) }) I am thinking to deploy this app to heroku with the following heroku.yml. But both web and api container has to accept http request. The container with the name: 'web' only accepts Http request. (According to heroku website) Should I create multiple heroku app? Or is there any workaround? Any suggestions are appreciated. Thank you for your time. what I do for deploying git add heroku.yml git push heroku master and this will push the whole images to the heroku repository, in running process, CMD lines will be executed. heroku.yml build: docker: web: bootstrapdebug/Dockerfile api: apis/Dockerfile apis/Dockerfile FROM python:3.6 ENV PYTHONBUFFERED 1 WORKDIR /app COPY . /app/apis WORKDIR /app/apis RUN python3 -m pip install -r requirements.txt --no-cache-dir CMD ["python", "manage.py", "runserver", "0.0.0.0"] bootstrapdebug/Dockerfile FROM node:12.10.0-alpine WORKDIR /app COPY . /app/bootstrapdebug WORKDIR /app/bootstrapdebug RUN apk update && \ npm install && \ CMD ["npm", "run", "serve", "--", "--port", "$PORT"] -
Error: Cannot resolve keyword 'id' into field
class Profile(models.Model): name=models.CharField(max_length=20, primary_key=True ) age=models.IntegerField() def __str__(self): return self.name class Like(models.Model): user=models.ForeignKey(Profile,on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) like=models.IntegerField(default=0) def __str__(self): return self.choice_text in python manage.py shell command: from database.models import Profile, Like p=Profile(name='test', age=66) p.save() p.id AttributeError Traceback (most recent call last) <ipython-input-35-25ec00f2e4bf> in <module> ----> 1 p.id But if you follow the example on www.djangoproject.com , you will get to see result of p.id is 1. Any help will be appreciated to understand the databases as I never worked on the databases. -
Django: pre-fetch custom model field (django-simple-history)--performance optimization
I am trying to optimize my querysets. I extensively make use of django-simple-history I have models as follows wherein I have a method with which I want to track changes to the fields: class TrackHistoryMixin(models.Model): history = HistoricalRecords(inherit=True, cascade_delete_history=True) has_history = models.BooleanField(blank=True, default=False) class Meta: abstract = True @property def changed_fields(self): first_record = self.history.last() latest_record = self.history.latest() delta = first_record.diff_against(latest_record).changed_fields no_history_fields = ['from_portal', 'has_history', 'document'] for field in no_history_fields: try: delta.remove(field) except ValueError: pass return delta @property def old_portal_values(self): if self.changed_fields: old_object = self.history.last().__dict__ old_portal_values = dict() for field in self.changed_fields: old_portal_values.update({field: old_object[field]}) return old_portal_values The problem with performance is that I cannot use select_related, or prefetch_related with the history field above. Thus, when I load an instance of a model which inherits from the TrackHistoryMixin, and I need to interact with the history field, it hits the database. The best thing I could do so farin my templates is that for each record I put the history field in a variable with {% with variable=object.history %}. But given that I have numerous records, performance still suffers. How can I prefetch such field such that when I get a queryset, all the history related data are loaded as well? I … -
Docker- django throws error while connecting to postgres: psycopg2.OperationalError: could not connect to server: Connection refused
I am trying to dockerize my Django-postgres app. My Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My docker-compose.yml is: version: '3' services: web: build: . command: python vessel_locator/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres ports: - "5432:5432" environment: POSTGRES_PASSWORD: password and my settings .py has the following database code: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '0.0.0.0', 'PORT': '5432', } } My db and web containers are up but when I run: docker-compose run web python manage.py migrate I am getting the error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? How can I make my containers communicate? -
Django rest framework : need to map two different functionalities on same view
I want a common view(class),that returns just a json sort of response on POST and on GET it should return the json response but to a page(html template) because I have a single url upon which get and post requests have this kind of behaviour. If I use "APIView" I cannot return a new page and if I use a "TemplateView" the api response doesn't work as expected. Any help? I do not want to use function based views. -
Django change to class based view
I would like to add a function based view to a class based view but always get error TabError: inconsistent use of tabs and spaces in indentation. Function based view: def search_index(request): results = [] search_term = "" if request.GET.get('query'): search_term = request.GET['query'] results = esearch(query=search_term) print(results) context = {'results': results, 'count': len(results), 'search_term': search_term} return render(request, 'esearch/base.html', context) base.html <form class="form-inline"> <input class="form-control mr-sm-2" type="query" placeholder="query" aria-label="query" name = 'query' value = ""> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Class based view that is not working class TemplateFormView(FormView): template_name = 'esearch/base.html' form_class = CateChainedSelect2WidgetForm def search_index(self, request,*args,**kwargs): search_term = request.GET.get('query') results = esearch(query=search_term) //this is where the taberror shows. print(results) context = {'results': results, 'count': len(results), 'search_term': search_term} return context What's missing here? -
ImageField upload_to doesn't work with django update statements
models.py class Movies_list(models.Model): movies_thumbnail=models.ImageField(default='thumbnail.jpg',upload_to='movies_pics') def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.movies_thumbnail.path) if img.height > 100 or img.width > 100: output_size = (200,300) image_movies=img.resize(output_size,resample=Image.ANTIALIAS) image_movies.save(self.movies_thumbnail.path) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' views.py form=Update_Movies_form( data=(request.POST or None), files=(request.FILES or None), # instance=obj ) form.fields["movies_thumbnail"].initial = obj.movies_thumbnail movies_detail=Movies_list.objects.filter(movies_id=movies_id) print(movies_detail) url=url_filter(request,movies_id) if form.is_valid(): if request.user.is_staff: obj_movies_update=Movies_list.objects.filter(movies_id=movies_id).update( movies_thumbnail=request.FILES["movies_thumbnail"], forms.py class Create_Movies_form(forms.Form): movies_thumbnail=forms.ImageField(widget=forms.ClearableFileInput(attrs={'placeholder': 'thumbnail'})) on update form submition it save movies_thumbnail in media folder not in media/movies_pics so i try to forcefully save it in movies_pics by replacing movies_thumbnail=request.FILES["movies_thumbnail"], to movies_thumbnail="movies_pics/"+str(request.FILES["movies_thumbnail"]), It save image in movies_pic and work just fine but didn't crop image as specified in models.py def save(self,*args,**kwargs): super().save(*args,**kwargs) img=Image.open(self.movies_thumbnail.path) if img.height > 100 or img.width > 100: output_size = (200,300) image_movies=img.resize(output_size,resample=Image.ANTIALIAS) image_movies.save(self.movies_thumbnail.path) -
Django: Update Page Information Without Redirecting
I have this code: html <form method="post" id="idForm" name="frm1" action = "/myproject/save/" enctype="multipart/form-data"> {% csrf_token %} .... <input type="submit" name="save" id="save" value="Save"> </form> <span class="status">Value: &nbsp;{{ request.mylist}} </span> js code $(document).on('submit', '#idForm',function(e){ $.ajax({ type: 'POST', url: '{% url "myproject:save_form" %}', data: {}, success:function(json){ $('.status').contents()[0].textContent = data.mylist }, error : function(xhr,errmsg,err) { alert("ajax error") } }); }); views if request.method == 'POST' and 'save' in request.POST: print("runs save form") mylist= [5] return JsonResponse({'mylist':mylist}) Question: When I click on Save button, It is redirected to a page with {"mylist": [5]} How can I make it update only the status part, Value? -
Django urls with UUID issue
I am trying to redirect to the view based on the CustomerID but its not working for UUIDs. It was previously working fine with integers. Please suggest. url.py: from django.urls import path, include from . import views urlpatterns = [ path('create/', views.create, name='create'), path('<uuid:customer_id>', views.detail, name='detail'), path('search/customers/<uuid:customer_id>', views.detail, name='detail'), path('customers/<uuid:customer_id>', views.detail, name='detail'), path('edit/<uuid:customer_id>', views.edit, name='edit'), path('modify/<uuid:customer_id>', views.modify, name='modify'), ] views.py @login_required def detail(request, customer_id): customer = get_object_or_404(CustomerMaster, pk=customer_id) return render(request, 'customers/detail.html',{'customer':customer}) -
Is there a way that to "docker-compose build" utilize existing dependencies wheels?
To make a change in the dependencies of a docker container, i'm runing docker-compose build. I want to update a dependency listed on requirements.txt to be more specific. But everytime that I execute this, it redownload all the requirements again instead of use existing wheels. Am I missing something or is this the behavior by default? Is there a way change this behavior to make use of wheels created before? The project was created with Django-Cookiecutter: docker=yes This is my local.yml: version: '3' volumes: local_postgres_data: {} local_postgres_data_backups: {} services: django: build: context: . dockerfile: ./compose/local/django/Dockerfile image: cctest_local_django depends_on: - postgres volumes: - .:/app env_file: - ./.envs/.local/.django - ./.envs/.local/.postgres ports: - "8000:8000" command: /start postgres: build: context: . dockerfile: ./compose/production/postgres/Dockerfile image: cctest_production_postgres volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres Dockerfile: FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI dependencies && apk add libffi-dev py-cffi \ # Translations dependencies && apk add gettext \ # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell && apk add postgresql-client # Requirements are installed here to …