Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change the default style in django cms?
Here I want to change the default style generated by the <li> tag so I tried like this. <ul class="section--list"> <li class="section--text"> {% placeholder "Members" or %}abcd {% endplaceholder %}</li> </ul> It is giving the result as below generating extra <li>.How can remove this and keep the same style ? -
How to run the view when radio button is clicked in Django
I want to know how to execute the view when the radio button is clicked. I created a radio button with old and new address values in the form. class MyForm(forms.ModelForm): CHOICES = [('old', 'old address'), ('new', 'new address')] choice_address = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) And I showed the radio button in the template. <form action="" method="post" class=""> {% csrf_token %} {% for choice in form.choice_address %} {{ choice.choice_label }} <span class="radio">{{ choice.tag }}</span> {% endfor %} </form> I want to display the last five addresses in the pop-up window when the old button is clicked. view.py AddressInfo.objects.filter(user=user)[:5] Otherwise I want to show an empty form when the new button is clicked. view.py form = MyForm() How do I run a view when the radio button is clicked? -
Referrer-Policy header is always no-referrer-when-downgrade
I have encountered an issue with setting Referrer-Policy header in Django. I want it always be same-origin but it stays no-referrer-when-downgrade on the response anyway. What I have done: started fresh django 3.0 project no MAC added 'django.middleware.security.SecurityMiddleware' to MIDDLEWARE django setting set SECURE_REFERRER_POLICY = 'same-origin' in django settings started dev server python manage.py runserver visited page http://127.0.0.1:8000 Actual result: http://127.0.0.1:8000 returns Referrer Policy: no-referrer-when-downgrade header Expected result: http://127.0.0.1:8000 returns Referrer Policy: same-origin header Can someone explain me, why there is a wrong header? -
Django how to use separate database for default authentication
I have a database created from non-django app and have defined the database connection info like below DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PORT': os.environ.get('POSTGRES_PORT'), } } Unfortunately, when I migrate the django admin related tables, they all go into the default database. I know that it is possible to declare multiple databases and separate read and write actions to different databases; however, what I would like to do is to have all the default django admin related tables to be created into another database. Say I declare a second database like below, how do I make sure that django admin related datas get migrated to the second database and also read from that when I login to django admin? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_DB'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': os.environ.get('POSTGRES_HOST'), 'PORT': os.environ.get('POSTGRES_PORT'), }, 'admin':{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('ADMIN_POSTGRES_DB'), 'USER': os.environ.get('ADMIN_POSTGRES_USER'), 'PASSWORD': os.environ.get('ADMIN_POSTGRES_PASSWORD'), 'HOST': os.environ.get('ADMIN_POSTGRES_HOST'), 'PORT': os.environ.get('ADMIN_POSTGRES_PORT'), } } -
ModelMultipleChoiceFilter - Field 'id' expected a number but got 'Diner'
So I have a simple Ad model and a FilterView showing all the ads. The ads can be filtered by different tags stored in a separate model joined by a ManyToManyField. I'm using django-filter to set up a small ModelMultipleChoiceFilter and let users select different tags to filter the Ads. This is working however it uses the tag__id. I would like it to use the tag__slug field. Therefore I've added the attribute "to_field_name='slug'" but I get the following; Field 'id' expected a number but got 'diner'. The following code does work but only filters by tag__id like: /?tags=6 and I would rather see something like this; ?tags=diner models.py class Ad(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) description = RichTextField() tags = models.ManyToManyField('Tag') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, null=True) class Meta: ordering = ['-title'] def __str__(self): return self.title class Tag(models.Model): name = models.CharField(max_length=200, help_text='Titel van de tag') slug = models.SlugField(max_length=200, null=True) def __str__(self): return self.name filters.py from django import forms from discovery.grid.models import Ad, Tag import django_filters class AdFilter(django_filters.FilterSet): tags = django_filters.ModelMultipleChoiceFilter( # to_field_name='slug', queryset=Tag.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Ad fields = [ 'tags' ] How can I achieve filtering based on the model name or slug instead of the … -
How to use github flavored markdown for my Django blog?
I am using https://github.com/pylixm/django-mdeditor as my markdown editor in Django admin. I want to display it in html but could not find any solution. -
Django: How to get form (or request) objects on TemplateView
I’ve built a web application with Django. On the way, a question raised, which is how does the requests getting from Formview (and Form) are passed to other vIew such as TemplateView. Following are the process steps. User enter values (requests) on the page. The request value are NOT saved on any model. The request values are calculated with the prediction algorithm (sort of machine learning) coding in app.py TemplateView receive the calculated values and display it And, following are my scripts form.py class ValueForm(forms.Form): value1=forms.Integer(label='value1', widget=forms.TextInput( attrs={'placeholder':'value1','required':True})) value2=forms.IntegerField(label='value2', widget=forms.TextInput( attrs={'placeholder':'value2','required':True})) value3=forms.Integerield(label='value3', widget=forms.TextInput( attrs={'placeholder':'value3','required':True})) def clean(self): v1=self.cleaned_data.get('value1') v2=self.cleaned_data.get('value2') v3=self.cleaned_data.get('value3') if v1==None or v2==None or v3==None: raise form.ValidationError('Sure the enter of Value') view.py for inputing the value class ValueEnterView(FormView): template_name='mysite/value_enter.html' form_class=ValueForm success_url=reverse_lazy('mysite:Prediction') #transfer to PredictionDisplayView def form_valid (self, form): form.clean() return super().form_valid(form) apps.py def Prediction(v1,v2,v3): .... .... return predicted_value view.py for displaying the prediction result import app class PredictionDisplayView (TemplateVIew): template_name='mysite/prediction.html' def post(self, request): # I want to get the requests entered in the ValueEnterView. #But the following script does not work form=ValueForm(request.POST) if form.is_valid(): v1=form.cleaned_data['value1'] v2=form.cleaned_data['value2'] v3=form.cleaned_data['value3'] return v1,v2,v3 def calculation(self): v1,v2,v3=self.post() return Prediction(v1,v2,v3) #function of apps.py def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) prediction_value=self.calculation() context['prediction']=prediction_value return context I think it might be better … -
Drop Down menu not creating Javascript
I am creating a website using Django in which it requires drop down menu. obs_index.html: {% block termscondobs %} <li> <a href="{% url 'terms-conditions' %}" class="waves-effect"> <i class="fa fa-file-text-o"></i> <span>Terms & Conditions</span> <i class="fa fa-angle-left float-right"></i> </a> <ul class="sidebar-submenu"> <li><a href="{% url 'terms-conditions' %}"><i class="zmdi zmdi-star-outline"></i> OBS T&C</a></li> <li><a href="{% url 'terms-febs' %}"><i class="zmdi zmdi-star-outline"></i> Febs T&C</a></li> <li><a href="{% url 'terms-febs-events' %}"><i class="zmdi zmdi-star-outline"></i> Febs Events T&C</a></li> </ul> </li> {% endblock %} But it is not creating a drop-dwon-menu.The error is Not Found: /terms/assets/js/popper.min.js Why is it? -
get object of foreign key django drf
i want to get image url of projectimage foreign key in project category table. models.py: class ProjectCategory(MPTTModel): name = models.CharField(max_length = 100) slug = models.SlugField() banner = models.ImageField(upload_to='Project_banner', default = 'demo/demo.png') first_image = models.ForeignKey('ProjectImage',on_delete=models.SET_NULL,null=True) parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True) class ProjectImage(models.Model): title = models.CharField(max_length = 100) image = models.ImageField(upload_to='projectimage', default = 'demo/demo.png') watermark_thumb = models.ImageField(upload_to='thumbs', blank=True, null=True) thumbnail = models.ImageField(upload_to='thumbs', blank=True, null=True) category = models.ForeignKey('ProjectCategory', null=True, blank=True, on_delete=models.CASCADE,) description = models.TextField(max_length=1000) created_at = models.DateTimeField(default=now, editable=True) def __str__(self): return self.title serializers.py: class ProjectImageSerializer(serializers.ModelSerializer): class Meta: model = ProjectImage fields = ('id','title','image','watermark_thumb','thumbnail','category','description','created_at') -
TypeError: Unicode-objects must be encoded before hashing, creating a hash Key for email activation
I am trying to create as hash_key for email activation but am getting the type error above. Any ideas how i can enforce encoding. Below is my code: def user_created(sender, instance, created, *args, **Kwargs): user = instance if created: get_create_stripe(user) email_confirmed, email_is_created = EmailConfirmed.objects.get_or_create(user=user) if email_is_created: short_hash = hashlib.sha1(str(random.random()).hexdigest())[:5] base, domain = str(user.email).split('@') activation_key = hashlib.sha1(short_hash+base).hexdigest() email_confirmed.activation_key = activation_key email_confirmed.save() email_confirmed.activate_user_email() post_save.connect(user_created, sender=User) -
Show the value of the fields of a model as it's stored in the database in Django
I have a Django view that exports a model into a CSV file, but I need to show the values of the fields as they are stored in the database (postgresql), for example, 't' instead of 'True', the dates the correspondent format, etc. So, as far as I see it, I have 3 options: Somehow showing the values in the way they're stored (what I'm asking here) Converting each field that has differences (I hope I don't have to do this) Making the queries directly in psql, save the result to a CSV, and return that. I wouldn't now how to do this in Django without the ORM converting the values. Please don't ask why I'm doing this. Thanks! -
Cannot connect to mysql and Django when using docker compose because of different socket location
When run docker-compose up, django container says django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)”) And db container says Version: '5.7.29' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server (GPL) It seems like they cannot connect to each other because of different socket location. I want to know if I can change socket file location. -
django.contrib.sessions.models.Session.DoesNotExist: Session matching query does not exist
this is my models. I have to use Session so that I can get a session id of the user from django.conf import settings from django.db import models from django.contrib.sessions.models import Session # Create your models here. class UserSession(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) session = models.OneToOneField(Session,on_delete=models.CASCADE) def __str__(self): return self.user.username my authentication.py file so that I can let only one user at a time to login .I got the error at line session=Session.objects.get(pk=request.session.session_key). from django.contrib.auth.backends import ModelBackend from .models import UserSession from django.contrib.sessions.models import Session from django.contrib.auth.backends import ModelBackend class MyBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): if Session.objects.filter(usersession__user__username=username).exists(): return None else: user = super().authenticate(request,username=username,password=password,**kwargs) if user: UserSession.objects.get_or_create( user=user, session=Session.objects.get(pk=request.session.session_key) ) return user This is my settings . Lab is the name of app and authentication.py is the file in which I have included my filter code. AUTHENTICATION_BACKENDS = ['lab.authentication.MyBackend'] -
How to make realtime commenting system?
hope you all are doing well.I had to make a commenting system and with reply on it and it had to be ajax supported also with pagination so you could click on more to see more comments.So I made it from scratch but as I move I am deciding to make it realtime so every guys who is on a post can see the comment that the other guy made.But I am continuiously stuck on this part.The old commenting system was like this. WHEN A USER MAKES A COMMENT. THE AJAX FETCHS THE FIRST PAGE COMMENTING API AGAIN AND THEN REDISPLAY IT BY JQUERY HANDLING THE DATA. So it worked fine but in realtime commenting it will break because suppose there are two different user's interacting with a same post and one guy is clicked the more and is seeing the next comments.But suddenly the first user comments so if the channels will be a post that means the comments will refreshed and fetched on all the user's listening to it. This is the best way I could possibly explain it.Now my question is how can I make a realtime communication like Facebook where people interact and one change that … -
Django unable to load media files from aws S3 in development server
media files are getting uploaded aws s3 bucket properly but it is not able to render to the html page. Can anyone help me with this please I couldn't able to find what's went wrong. settings.py variables settings are shown below. MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRECT_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Data not displaying in django admin - using chart.js (no errors)
I have created a changelist_view for displaying a chart.js visual in the Django admin. I am not getting any errors, the chart outline is visible, but the data is not. Not sure what I'm missing. Info below: admin.py model: class MachineFaultAdmin(admin.ModelAdmin): readonly_fields = [ 'event_id', 'fault_type_id', 'position', ] list_display = [ 'event_id', 'fault_type_id', 'position', ] def changelist_view(self, request, extra_context=None): # Aggregate Faults chart_data = ( MachineFault.objects.all() .values('position') .annotate(total=Count('fault_type_id')) .order_by('total') .filter(position__gte=10) ) #Serialize and attach the chart data to the template context as_json = json.dumps(list(chart_data), cls=DjangoJSONEncoder) extra_context = extra_context or {"chart_data": as_json} #Call the superclass changelist_view to render the page return super().changelist_view(request, extra_context=extra_context) def has_add_permission(self, request): # Nobody is allowed to add return False def has_delete_permission(self, request, obj=None): # nobody is allowed to delete return False # suit_classes = 'suit-tab suit-tab-faults' empty_value_display = '' list_filter = ('fault_type',) search_fields = ('position',) changelist_view html (admin override file) <!--# machines/templates/admin/machines/machinefault/change_list.html--> {% extends "admin/change_list.html" %} {% load static %} <!-- Override extrahead to add Chart.js --> {% block extrahead %} {{ block.super }} <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script> <script> document.addEventListener('DOMContentLoaded', () => { const ctx = document.getElementById('myChart').getContext('2d'); // Sample data const chartData = {{ chart_data | safe }}; // Parse the dates to JS … -
django form failed to get values from request
this is views.py def registerItem(request): print(request) try: print("====111", request.method) if request.method == 'POST': print("=========222", request.POST) form = ItemForm(request.POST) print("====333", form.is_bound) print("====444", form) print("====555", form.cleaned_data['mart_id']()) print("====666", form.is_valid()) if form.is_valid(): mart = MartModel.objects.get(id__exact=form.cleaned_data['mart_id']) print("====666", mart) seq = ItemModel.objects.filter(mart_id__exact=mart).values('seq').order_by('-seq')[:1] if seq: seq = seq[0]['seq']+1 else: seq = 1 # form.save() item = ItemModel(mart_id=mart, seq=seq, name=form.cleaned_data['name'], price=form.cleaned_data['price'], expirationDate=form.cleaned_data['expirationDate'], stockYn=form.cleaned_data['stockYn']) item.save() form = ItemForm() return render(request, 'mobileWeb/admin/register_item.html', {'form':form}) else: form = ItemForm() return render(request, 'mobileWeb/admin/register_item.html', {'form':form}) except Exception as ex: print('====777 : Error occured : ', ex) request.POST value is correct. you can confirm it by log No.2. form is bound correctly. you can confirm it by log No.3. but the form failed to receive values. you can confirm it by log No.4. this is forms.py class MartForm(forms.ModelForm): class Meta: model = MartModel fields = ['name', 'address', 'tell', 'phone', 'xPosition', 'yPosition'] class ItemForm(forms.ModelForm): choicesQueryset = MartModel.objects.all().values('id', 'name') choicesDic = [] for choice in choicesQueryset: choicesDic.append((choice['id'], choice['name'])) mart_id = forms.CharField(label='mart', widget=forms.Select(choices=choicesDic)) class Meta: model = ItemModel fields = ['mart_id', 'name', 'price', 'expirationDate', 'stockYn'] this is models.py class MartModel(models.Model): name = models.CharField(max_length=20, blank=False) address = models.TextField(blank=False) tell = models.CharField(blank=True, max_length=12) phone = models.CharField(blank=True, max_length=11) imageFileNo = models.CharField(blank=True, max_length=3) xPosition = models.FloatField(blank=False) yPosition = models.FloatField(blank=False) delete_yn = models.CharField(blank=False, … -
Adding dynamic rows based on user input the number using javascript
I want to add dynamic rows based on user input the no of conditions in text box..I am using javascript for that...how to achieve these condition..for eg If user enter 3 in text box then 3 condtions rows along with (Condition1 ,conditon2 ..) like should be prepared dynamically -
how can fixed this problem: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
after install django when will start browsing at http://127.0.0.1:8000/ then this massage will show in powershell. Exception happened during processing of request from ('127.0.0.1', 3575) [06/Feb/2020 09:48:03] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [06/Feb/2020 09:48:03] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [06/Feb/2020 09:48:03] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 Traceback (most recent call last): File "c:\users\fuel\appdata\local\programs\python\python38\Lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "c:\users\fuel\appdata\local\programs\python\python38\Lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "c:\users\fuel\appdata\local\programs\python\python38\Lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Fuel\.virtualenvs\sample-DQH4k00R\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Fuel\.virtualenvs\sample-DQH4k00R\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "c:\users\fuel\appdata\local\programs\python\python38\Lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine this is the photo: ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine how can i fixed it? -
Django Formset returns INAVLID despite having valid data
I have a Django form set that is pre-populated through a model and then rendered on a web page. The web page appears as Django Form set display. A change is made on the last field shown on the screenshot. After the form is submitted via POST and a statement print (line #2 in post method) is issued, the data posted is clearly displayed on the console. (Console output shown below) But the form set validity test statement always returns FALSE. The code is as follows ------Code------- class LeaveTransactionLog(models.Model): empno = models.ForeignKey(Employee,related_name='ltl_empno',on_delete=models.PROTECT) approver_mgrno = models.IntegerField(default=0) applied_year = models.IntegerField(default=2019) applied_date = models.DateTimeField() leave_type = models.CharField(max_length=2,choices=leave_choices,default='PL') leave_start_date = models.DateField() leave_end_date = models.DateField() leave_days = models.IntegerField(default=0) leave_decision = models.CharField(max_length=2,choices=decision_choices,default='ES') class ApproveRejectEscalateForm(forms.ModelForm): def clean(self): self.cleaned_data = super(ApproveRejectEscalateForm, self).clean() return self.cleaned_data class Meta: model = LeaveTransactionLog fields = ['empno','applied_year','applied_date','approver_mgrno','leave_type', 'leave_start_date', 'leave_end_date', 'leave_days','leave_decision'] class ApproveRejectEscalateFormView(View): def get(self,request): ARE_formset = modelformset_factory(LeaveTransactionLog, fields=( 'empno','applied_year','applied_date','approver_mgrno','leave_type', 'leave_start_date', 'leave_end_date', 'leave_days', 'leave_decision'), max_num=2, min_num=0) formset = ARE_formset(initial=model_to_dict(LeaveTransactionLog)) return render(request,'ApproveRejectEscalateForm.html',{'formset':formset}) def post(self,request): responseformset = ApproveRejectEscalateForm(request.POST,initial= model_to_dict(LeaveTransactionLog)) print('Data : ',responseformset.data) counter = 0 for forms in responseformset: if forms.form.is_valid(): print('Valid.. !') counter = counter + 1 else: print('Invalid form #',counter) print(forms.errors.as_data()) print(forms.data) counter = counter + 1 print('Counter : ',counter) if responseformset.is_valid(): print('Formset valid … -
Update canvas element on form submit - Django
I'm trying to update an HTML canvas element on form submission with Django. I have my views.py that renders the index.html page with the processed data in JSON. return render(request, 'index.html', {'form': form, 'data': mark_safe(json.dumps(data))}) This render method is inside of an if request.method == 'POST', so essentially what's happening is it's sending the data through context to the HTML and JavaScript appropriately, however, I need canvas updates when I use the "submit" button. $('#form').submit(function() { /* all of my canvas logic */ }); Momentarily, the canvas will show the sign before the Django page is refreshed, and then reset to a blank canvas. Presumably this is because nothing in views.py explicitly tells the index.html to have a new canvas on the page with data, but I can't seem to find any information or docs on this. Furthermore: Python tkinter or other GUI libraries don't really apply here. I can only change and update the canvas through JavaScript. I can't pass a whole HTML canvas element as context through the view. e.preventDefault(); would cancel the whole submission; so if an input in the form changes, the POSTed data will not update, and in result, the drawn shapes on the canvas … -
django - modelforms and react - DRY
I'm adding React to my django web app and I'm not sure how to proceed with forms. In pure django, you can just render a form with {{my_form.as_p}} and this will create inputs for all the fields with the correct input type. If you use ModelForm, you don't even need to create a definition for the fields because it will just take it from the django model definition, keeping the DRY principle very nicely. With React I understand that it's best to give the data as json and let React take care of rendering and not use django template rendering. But with forms, this means that I have to write all the form fields by hand. Not only this is much more effort, but also it is breaking the DRY principle because I have to have two definitions of the same thing in two separate places that I need to keep in sync. Is there any library/best practice for this? Is there any way to create a json with the form definition as well as the data, and some way to render this in react without having to manually write all the fields? -
Python convert list of strings to zip archive of files
In a python script, I have a list of strings where each string in the list will represent a text file. How would I convert this list of strings to a zip archive of files? For example: list = ['file one content \nblah \nblah', 'file two content \nblah \nblah'] I have tried variations of the following so far import zipfile from io import BytesIO from datetime import datetime from django.http import HttpResponse def converting_strings_to_zip(): list = ['file one content \nblah \nblah', 'file two content \nblah \nblah'] mem_file = BytesIO() with zipfile.ZipFile(mem_file, "w") as zip_file: for i in range(2): current_time = datetime.now().strftime("%G-%m-%d") file_name = 'some_file' + str(current_time) + '(' + str(i) + ')' + '.txt' zip_file.writestr(file_name, list[i]) zip_file.close() current_time = datetime.now().strftime("%G-%m-%d") response = HttpResponse(mem_file, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="'str(current_time) + '.zip"' return response But just leads to 0kb zip files -
CSS href treated as URL
I'm trying to link a css file to an html file but the chrome console gives me this error: "GET http://127.0.0.1:8000/static/base/css/base-template.css net::ERR_ABORTED 404 (Not Found)" I don't know why but for whatever reason, django is looking for a URL when the file is stored locally. Anybody know solutions? -
Docker so slow while installing pip requirements
I am trying to implement a docker for a dummy local Django project. I am using docker-compose as a tool for defining and running multiple containers. Here I tried to containerize the Django-web-app and PostgreSQL two services. Configuration used in Dockerfile and docker-compose.yml Dockerfile # Pull base image FROM python:3.7-alpine # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY requirements.txt /code/ RUN pip install -r requirements.txt # Copy project COPY . /code/ docker-compose.yml version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: All seems okay. The path postgres integrations and all except one thing pip install -r requirements.txt. This is taking too much time to install from requirements. Last time I was giving up on this but at last the installation does completed but takes lots of time to complete. In my scenario, the only issue is why the pip install so slow. If there is anything that I am missing? I am new to docker and any help on this topic will be highly appreciated. Thank you. I was …