Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 'dict' object has no attribute '_mutable'
I am testing Django Rest Framework code with Postman I called http://127.0.0.1:8000/api/users/1/documents/ But received error message 'dict' object has no attribute '_mutable' What is the right way to create request via Postman? (it seems that problem with postman) I read this topic, but didn't find solution DRF request.data has no attribute _mutable My code class UserDocumentCreate(generics.CreateAPIView, generics.RetrieveAPIView): serializer_class = UserDocumentSerializer permission_classes = (UserIsOwner, IsAuthenticatedDriver) queryset = Document.objects.all() def get_serializer_class(self): if self.request.version == "1.0": return UserDocumentSerializer def create(self, request, *args, **kwargs): request.data._mutable = True request.data["owner"] = kwargs.get("pk") serializer = self.get_serializer(data=request.data) ... -
Why does django print the traceback of an exception even though I catch it?
I'm creating a django web app and am currently in the process of writing tests for it. I want to check that my URL paths are working. In order messages that clutter the screen when testing, I tried catching the exceptions that get thrown, but this doesn't seem to work. Here's my method where I'm testing the path of the home URL: def test_home(self): path = '/' try: response = self.client.get(path) except Exception: assert False, ("There seems to be a problem with the view corresponding to the path", path) self.assertEqual(response.status_code, 200, ("Couldn't load page with page", path)) And this is the output: <a lot more exceptions> During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/opt/anaconda3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 16, in test_home response = self.client.get(path) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 395: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/me/Documents/project/project/app/tests/test_urls.py", line 18, in test_home assert False, … -
Django AllAuth URL patterns configuration
I created a sample view to display the detail of the user. In my project, I have 2 apps, the Accounts that contain all the details of the user and the Core for the web application. I've done configuring the Django AllAuth for Google Login and here is the outcome. Models.py class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) email = models.EmailField(max_length=254, null=True, blank=True) member_since = models.DateTimeField(auto_now_add=True) phone_number = PhoneNumberField(null=True, blank=True) street_address = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) country = models.CharField(max_length=50, null=True, blank=True) zip_code = models.IntegerField(null=True, blank=True) slug = models.SlugField(null=True, blank=True, unique=True) def __str__(self): return str(self.first_name) def get_phone_number(self): return self.phone_number @property def get_full_address(self): return f"{self.street_address}, {self.city}, {self.country}, {self.zip_code}" @receiver(user_signed_up) def populate_profile(sociallogin, user, **kwargs): user.profile = Profile() user_data = user.socialaccount_set.filter(provider='google')[0].extra_data first_name = user_data['given_name'] last_name = user_data['family_name'] email = user_data['email'] user.profile.first_name = first_name user.profile.last_name = last_name user.profile.email = email user.profile.save() def get_absolute_url(self): return reverse("profile", kwargs={"slug": self.slug}) def save(self, *args, **kwargs): self.slug = slugify("{obj.first_name}-{obj.last_name}".format(obj=self)) super(Profile, self).save(*args, **kwargs) Views.py class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'accounts/profile.html' Accounts Urls.py app_name = 'accounts' urlpatterns = [ path('profile/<slug>', ProfileDetailView.as_view(), name='profile') ] Main Urls.py from django.contrib import admin from django.urls import path, include urlpatterns = … -
template inheritance is not working in my django application
My base.html Template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title>MyResume Bootstrap Template - Index</title> </head> <body> {% block content%} {% endblock content%} </body> </html> My content block template {% extends "base.html" %} {% block content %} <h1>hello world</h1> {% endblock content %} I don't know what the issue is kindly help me with a solution -
Page keeps reloading after adding a new channels consumer and route
hope you all are doing well. I have been working on creating an asynchronous notification system, I already have a chat system but it is directed only towards the /inbox/ url. The problem that I'm facing is when I add a new consumer and access the home page the home page keeps reloading again and again and the terminal doesn't show any error. this is what my code looks like: Consumers.py async def websocket_connect(self,event): print("connected",event) await self.accept() async def websocket_receive(self,event): print("received",event) async def websocket_disconnect(self,event): print(event,"closed") class ChatConsumer(AsyncWebsocketConsumer): async def websocket_connect(self,event): print("connected") self.channel_layer = channels.layers.get_channel_layer() ..... await self.accept() async def websocket_receive(self,event): print("received2",event) ..... async def websocket_disconnect(self,event): print("disconnected",event) Routing.py from . import consumers from django.urls import re_path,path websocket_urlpatterns = [re_path(r"^a/inbox/(?P<username>[\w.@+-]+)", consumers.ChatConsumer.as_asgi()), re_path(r"a/(?P<username>[\w.@+-]+)",consumers.NotificationConsumer.as_asgi()), ] I'm trying to create a notifications websocket, any leads or any correction would be much appreciated. -
How do i find one tag with multiple text Content with Beautifulsoup
Am trying to scrap a website with multiple 'p' tags with beautifulsoup and I find it very difficult. please I need help. I want to get all posts associated with p tags. the find_all on beautifulsoup will not get this done and the image is not saving I get an error that the file cannot be saved and tell me how to retrieve, add or scrap all the text in p tags and the image on the HTML code below. Can you check out my code below kompas = requests.get('https://url_on_html.com/') beautify = BeautifulSoup(kompas.content,'html5lib') news = beautify.find_all('div', {'class','jeg_block_container'}) arti = [] for each in news: title = each.find('h3', {'class','jeg_post_title'}).text lnk = each.a.get('href') r = requests.get(lnk) soup = BeautifulSoup(r.text,'html5lib') content = soup.find('p').text.strip() images = soup.find_all('img') arti.append({ 'Headline': title, 'Link': lnk, 'image': 'images' }) let's take this HTML code as a scrapping sample <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p>Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <script></script> <p>the emergency of our matter is Once upon a time there were three little sisters, and their names were and they lived at the bottom of a well.</p> <p> … -
Displaying checked and unchecked ManyToMany choices in DetailView
I'm looking for an elegant way to show all available items (not just checked ones) in a Django DetailView, while stylizing the checked ones. Given following model: class Topping(models.Model): title = models.CharField(max_length=200) class Pizza(models.Model): topping = models.ManyToManyField(Topping, blank=True, null=True) I'm rendering toppings in my form with a CheckboxSelectMultiple (=rendered as multiple checkboxes), like: toppings = forms.ModelMultipleChoiceField( required=False, queryset=Toppings.objects.all(), widget=forms.CheckboxSelectMultiple, ) It is also relevant which toppings were not selected, hence I'd like to render something in my DetailView like the following (showing a checked checkbox when selected; showing an empty checkbox and light gray text when not selected, respecting the same order as seen in the form, i.e. alphabetically in this example): Chosen pizza toppings: ☑ Bluecheese ☐ Green peppers ☐ Onions ☑ Red peppers I currently go through the toppings as follows, but this only shows the selected ones: {% for option in object.toppings.all %}☑ {{ option }}<br />{% endfor %} I have a whole bunch of different ManyToManyFields on my main model. -
No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it
After hosting my Django application on Heroku while I try to download dynamic pdf my Django app's wkhtmltopdf causes this error. In local machine(Ubuntu) I've applied sudo apt-get install wkhtmltopdf I've also added Aptfile with my project directory so that Heroku installs those dependency and requirements while building the application. Aptfile: wkhtmltopdf But unfortunately Heroku don't even builds the app with the given dependency. I've also tried to install it by running Heroku bash but Heroku prevents. W: Not using locking for read only lock file /var/lib/dpkg/lock-frontend W: Not using locking for read only lock file /var/lib/dpkg/lock E: Unable to locate package wkhtmltopdf My code for generating pdf is: def pdf_generation(request, pk): ''' Will generate PDF file from the html template ''' template = get_template('bankApp/print_view.html') withdraw_obj = get_object_or_404(Withdraw, id=pk) year_month_day = withdraw_obj.withdrawn_on.split('-') day = year_month_day[2] month = year_month_day[1] year = year_month_day[0] word_amount = f'{num2words(withdraw_obj.withdrawn_amount)} Only' date = f'{day}{month}{year}' html = template.render({ 'pay_to': withdraw_obj.paid_to, 'date': date, 'amount': withdraw_obj.withdrawn_amount, 'amount_word': word_amount }) options = { 'page-size': 'A4', 'margin-top': '0.0in', 'margin-right': '0.0in', 'margin-bottom': '0.0in', 'margin-left': '0.0in', 'encoding': 'UTF-8', } pdf = pdfkit.from_string(html, False, options=options) response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment;\ filename="print.pdf"' return response Server Error: OSError at /bank/pdf/print/2 No wkhtmltopdf executable found: … -
Unable to save multiple value with Select2 in Django
I try to post multiple value selected from ajax response. But when I specify name of 'Select' tag as array - <select name="item_ids[]" nothing is saved. I use Select2 v 4.1.0 But if I set name="item_ids" without array brackets and choose 2 or more values, only last selected value is saved. For now it's an array field in the model but may be a char filed should be. models.py class Selected_items(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') item_ids = ArrayField(models.CharField(max_length=100), blank=True) file.html <select multiple="multiple" type="text" name="item_ids[]" class="form-control" autocomplete="off" required></select> forms.py class UserItemForm(forms.ModelForm): class Meta: model = Selected_items fields = ('item_ids',) def save(self, commit=True): selected_items = super(UserItemForm, self).save(commit=False) selected_items.item_ids = self.cleaned_data['item_ids'] if commit: selected_items.save() return selected_items views.py if request.POST and 'btn_save_user' in request.POST: form_7 = UserProfileForm(request.POST, instance=Profile.objects.get(user=user)) form_8 = UserItemForm(request.POST, instance=Selected_items.objects.get(id=user_id)) if form_7.is_valid() and form_8.is_valid(): form_7.save() form_8.save() return redirect('user-page') Please, help to resolve it. -
How to pass the customer id dynamically in the tap payment method to save the card value
** I and sending the post request to the TAP PAYMENT Gateway in order to save the card, the url is expecting two parameters like one is the source (the recently generated token) and inside the url the {customer_id}, I am trying the string concatenation, but it is showing the error like Invalid JSON request. ** ifCustomerExits = CustomerIds.objects.filter(email=email) totalData = ifCustomerExits.count() if totalData > 1: for data in ifCustomerExits: customerId = data.customer_id print("CUSTOMER_ID CREATED ONE:", customerId) tokenId = request.session.get('generatedTokenId') payload = { "source": tokenId } headers = { 'authorization': "Bearer sk_test_XKokBfNWv6FIYuTMg5sLPjhJ", 'content-type': "application/json" } *HERE DOWN IS THE url of TAP COMPANY'S API:* url = "https://api.tap.company/v2/card/%7B"+customerId+"%7D" response = requests.request("POST", url, data=payload, headers=headers) json_data3 = json.loads(response.text) card_id = json_data3["id"] return sponsorParticularPerson(request, sponsorProjectId) ** their expected url = https://api.tap.company/v2/card/{customer_id} their documentation link: https://tappayments.api-docs.io/2.0/cards/create-a-card ** Blockquote Blockquote -
Add product according to category in django
I am new in Django. I want to add product against the category which i select, but i don't know how can i do that. I select the category and add product but nothing happened. I don't know how can i do this. Thank u in advance Model.py class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=30) price = models.IntegerField() view.py class SelectCategory(TemplateView): template_name = 'purchase/selectCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() args = {'categories': categories} return render(request, self.template_name, args) def post(self, request): try: data = self.request.POST.get categoryId = ProductModel.category['category.id'].id product = ProductModel( category_id=data(categoryId), name=data('name'), price=data('price') ) product.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Temaplate {% extends 'auth/home.html' %} {% block content %} <form method="get"> {% csrf_token %} <label> Select Category <select name="Select Category"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value={{ category.id }}> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> <form method="post"> {% csrf_token %} <label for="name">Name <input type="text" name="name" id="name" placeholder="Enter Product name"> </label> <label for="price">Price <input type="number" name="price" id="price" placeholder="Enter Price of Product"> </label> <button type="submit">Submit</button> <button><a href="{% url 'menu' %}">Menu</a></button> </form> {% endblock %} -
getting error cannot read file data: is a directory when making migration in django rest framework
hi i am making an app which takes a users location and compares it with other people to find the distance. When i added a installed gdal geos postgis and proj4 i then added a pointfield from django.contrib.gis.db import then i did a migration and it returned an error of Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/aarush/anaconda3/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/home/aarush/anaconda3/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/aarush/anaconda3/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/aarush/anaconda3/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/aarush/git_fudo/food1_back/food1_back/posts_v1/models.py", line 1, in <module> from … -
Django model with Charfield Count and Zero values
I have a Django database model that has some attributes, one of them is a Charfield 'category' with Choices. I now want to annotate a queryset of this model with the count of the rows of each category. The thing is, the way i know to do it, only categories present in the queryset are getting counted, but i want a queryset with all categories annotated with the count (0 if no rows with this category). This is what im doing at the moment: Model.objects.all().values('category').annotate(total=Count('category')) Is there a way to display all categories, including such with count 0? -
How to close popup in Django Admin
I am using Python 3.7.10 with Django 3.1.6, and I have used the following code to create an admin popup that will be triggered when clicking on the "edit_link": class EditLinkWidget(forms.URLInput): def render(self, name, value, attrs, renderer): super().render(name, value, attrs, renderer) if not value: return '' return mark_safe(f'<a class="related-widget-wrapper-link change-related" href="{value}?_to_field=id&_popup=1" '\ 'data-href-template="{}?_to_field=id&_popup=1">Edit</a>').format( re.sub("(\d+)", "__fk__", value)) class PageForm(TranslatableModelForm): edit_link = forms.CharField(widget=EditLinkWidget, required=False, disabled=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance.pk: self.fields['edit_link'].initial = f'/admin/cms/car/{self.instance.car_id}/change/') class Meta: model = User fields = ('edit_link',) It works great, but the problem is that the popup doesn't close automatically when I click on the Save button, throwing the following javascript error: Does somebody know how can I fix it so the popup can be closed automatically? I guess it should communicate with the parent admin page somehow? -
How to use Base64FileField together with the FileField?
I am using Django rest and initially, I used form-data to upload images to Django. My model has a FileField and it worked well. Right now, I need to handle JSON uploads also. I integrated this Base64FileField from the drf-extra-fields, added it to the serializer, but now my form-data request fails with the following error: "innitial_file_path": [ "Invalid type. This is not an base64 string: <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>" ] How can I make it work for both the form-data and JSON request body? I suppose I still need to keep FileField in my model, but somehow convert base64 to the JSON. Also, should I create multiple serializers? Right now I have multiple nested serializes, so it would be difficult to use by creating multiple. I would then need to get the content-type in the create method of the serializer and depending on that use different serializer. How can I get that? -
django migration error, InvalidTemplateLibrary
this error started popping up after i install django rest_frame work and coverage: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'six' from 'django.utils'(C:\Users\kaleb\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\__init__.py) i even deleted the hole app and created it again but the error is still here. -
Better way to setup PWA for a Django project
thanks for your time. i have a Django project, with amp-html on front-end. and got to make it a PWA, the problem is that i still don't understand the requirements. Tried by just adding manifest.json and sw.js to the template folder, ain't got right. Tried with a third part library (https://pypi.org/project/django-pwa/) it worked, but i ain't understand why and how to work on it. Now i got the option to add service workers trough amp tag <amp-install-serviceworker> should i go to the simplest way that mozilla teachs('https://developer.mozilla.org/pt-BR/docs/Web/Progressive_web_apps')? I'm lost in which should be optional and which shouldn't -
use thousand separator in Django Admin input form?
I want to use a thousand separator in input forms in Django admin; such that when you enter the price in the price box, a separator added to it. -
virtualenv doesnt see to be isolated
Created Virtualenv Says Permission Denied (sometimes ..would love a fix for this too) Activated it with sudo pip freeze shows entire packages from global Installing packages shows Requirement already satisfied -
Photo upload: direct s3 upload vs via Django Imagefield and custom storage
My requirement: Get user to upload profile photo. Make sure that the file that is uploaded is really an Image. Image size cannot be more than 2MB. My options: Directly upload image to s3 using presigned url. In this case I don't have to worry about server resources running out when traffic load increases. But I would not be able to determine for sure if the file is an image. Just checking the extension is not enough to determine if the file is an image. I can upload it to s3 via django app using ImageField and custom s3 storage. ImageField uses pillow to make sure if the uploaded file is really an image. But I have to worry about server resources running out when traffic load increases. Increasing server resources is not an option. My questions: For direct upload how can I make sure if the file being uploaded is really an image? For image upload via django, how to mitigate or optimize the resource running out problem? -
Django-import-export problem importing foreignkey field
I am using the Django-import-export(version 2.5.0) module in Django(version 3.1.4). So I am able to import all my models fields except for the ForeignKey field. I don't know how to make this one work. Can you look at my code and see what is wrong or needs to change? I need Django Admin to import the ForeignKey field. models.py # myapp from django.db import models from django.contrib.auth.models import User class Agency(models.Model): system_name = models.CharField(max_length=255) county = models.CharField(max_length=60) state = models.CharField(max_length=2) active = models.BooleanField(default=True) system_no = models.CharField(max_length=7, unique=True) def __str__(self): return self.system_no class SitePart(models.Model): # I tried changing the "system_no" to another name "agency_no" through out the *.py's this did not resolve the problem. Maybe I missed something. system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, to_field='system_no', null=True, blank=True) part_name = models.CharField(max_length=125) status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('IA','Inactive'), ('SB','Stand By waiting acitvation'),('MO','Monitoring')] status = models.CharField(max_length=2, choices=status_tuple, default= 'SB') # sys_site_n is unique sys_site_n = models.CharField(max_length=15, unique=True) def __str__(self): return self.part_name resources.py from import_export import fields, resources, widgets from import_export.widgets import ForeignKeyWidget from myapp.models import Agency, SitePart class AgencyResource(resources.ModelResource): class Meta: model = Agency import_id_fields = ('system_no',) fields = ('system_name', 'county', 'state', 'active', 'system_no',) class SitePartResource(resources.ModelResource): system_no = fields.Field( column_name='system_no', attribute='system_no', widget=ForeignKeyWidget(Agency,'system_no')) print(system_no) class Meta: model = SitePart … -
Django: If I already deployed my app and want to make a change, how I manage the static files?
I already deployed my Django app, but now I'd like to make some changes to it, and I'll edit some static files too. Once I redeploy the app, should I run python3 manage.py collectstatic or should I do something else? Thanks for your precious time! -
Update variable passed to template on change of the model
I have a view home as follows: from .models import ExistencePredictions def home(request): context = { 'latest_prediction': ExistencePredictions.objects.last() } return render(request, 'detection/home.html', context=context) The problem is that new data is added to ExistencePredictions every second or so. Is it possible to update the context of the view every time the model is changed so that the latest data is shown in the template without reloading the page? -
How to create media folder and fetch images to my html dynamically | Django |
I have create a small project , where i am stuck at one point Issue : not able to get images dynamically and display in html using jinja i.image.url -> at this line in html images are not coming from folder media when i runserver the media folder is not getting created and images are not copied from pics to media folder As i uploaded images and its content from 127.0.0.1/8000/admin Project structure: My HTML {% for i in getdetails %} <div class="col-xl-3 col-lg-3 col-md-6 col-sm-12"> <div class="product-box"> <i> <img src="{{ i.image.url }}"/> </i> <h3>{{ i.name }} </h3> <span>{{ i.price }}</span> </div> </div> {% endfor %} My database My seeting.py file : 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 = '%g52q0hek460brm&!ty_)o5ucXXXXXXXXXXXXXXXX' # 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', 'LEARN_FROM_TELUSKO', ] 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 … -
Static file not found in Django production
I am trying to deploy my Django project using Ubuntu and apache webserver. When I transferred my project to the Ubuntu web server and tested it in development, everything went fine. However when changed to production, I experienced file not found problem and I suspect this problem is related to my setings.py, but I am unable to troubleshoot it further. The error I see in production when accessing my site is: Environment: Request Method: GET Request URL: http://139.162.163.35/ Django Version: 3.1.3 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback (most recent call last): File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jianwu/HD_website/website/env/lib/python3.8/site-packages/django/views/generic/base.py", line 63, in view self = cls(**initkwargs) File "/home/jianwu/HD_website/website/index/views.py", line 57, in __init__ self.ContextObject.importTextFile('static/mainAboutUs.txt') File "/home/jianwu/HD_website/website/index/views.py", line 50, in importTextFile with open(filePath,'r') as fid: Exception Type: FileNotFoundError at / Exception Value: [Errno 2] No such file or directory: 'static/mainAboutUs.txt' In my Meta I have CONTEXT_DOCUMENT_ROOT '/var/www/html' CONTEXT_PREFIX '' CSRF_COOKIE 'jF3vdEgpyhbKxavRw3pEWzRdIjc4lvw0MsV4lpBLdYXPqcGcIVyH02kEuBeGSXlh' DOCUMENT_ROOT '/var/www/html' GATEWAY_INTERFACE 'CGI/1.1' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' HTTP_ACCEPT_ENCODING 'gzip, deflate' HTTP_ACCEPT_LANGUAGE 'da-DK,da;q=0.9,en-US;q=0.8,en;q=0.7,bg;q=0.6,zh-CN;q=0.5,zh;q=0.4' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE 'csrftoken=jF3vdEgpyhbKxavRw3pEWzRdIjc4lvw0MsV4lpBLdYXPqcGcIVyH02kEuBeGSXlh' HTTP_HOST '139.162.163.35' HTTP_PURPOSE 'prefetch' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT …