Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django error __init__() takes 1 positional argument but 2 were given
I'm currently making a simple get/post api with django 2.1. After i run the server and go to the .../article/ url it return an error init() takes 1 positional argument but 2 were given TRACE BACK: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/article/ Django Version: 2.1 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api.apps.ApiConfig'] 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: File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\django-2.1-py3.6.egg\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in dispatch 483. response = self.handle_exception(exc) File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in handle_exception 443. self.raise_uncaught_exception(exc) File "C:\Users\admin\Miniconda3\lib\site-packages\rest_framework\views.py" in dispatch 480. response = handler(request, *args, **kwargs) File "C:\Users\admin\Desktop\crawler\api\views.py" in get 13. article_serializer = ArticleSerializer(article, many=True) Exception Type: TypeError at /article/ Exception Value: __init__() takes 1 positional argument but 2 were given My models.py from django.db import models # Create your models here. class Article(models.Model): class Meta: verbose_name_plural = "Article" verbose_name = "Article" id = models.ForeignKey('ArticlePicture', on_delete=models.CASCADE,primary_key=True) type = models.CharField(max_length=256, null=True) name = models.CharField(max_length=256, null=True) title = models.CharField(max_length=256, null=True) address … -
How to safely add column to db in a rolling Django deployment?
In a rolling deployment, new versions of an app server co-exist with old versions of the server and share a DB. (E.g., using AWS ECS) I'm trying to figure out how to add a column to a model in this setup, but am getting stumped by Django not storing the column defaults in the db. Any ideas? Requirements are simple: all deploys must be able to create and read from the table in question. PS: Here is some inspiration that talks about similar issues in the context of blue-green deploys. -
AttributeError at /process-ckt-schematics/4/ 'ProcessCktSchematics' object has no attribute 'branch_map'
Environment: Request Method: GET Request URL: http://127.0.0.1:8000/process-ckt-schematics/4/ Django Version: 2.1.1 Python Version: 3.7.0 Traceback: File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\ProgramData\Anaconda3\envs\myppe\lib\site-packages\django\views\generic\base.py" in get 149. context = self.get_context_data(**kwargs) Exception Type: AttributeError at /process-ckt-schematics/4/ Exception Value: 'ProcessCktSchematics' object has no attribute 'branch_map' You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code. -
How do i subclass Django CreateView
I have a model, for which i want to pass some arguments to the form. the model is : class CandidateNote(models.Model): candidate = models.ForeignKey(CandProfile, on_delete=models.CASCADE, related_name='candidatenotes_cand') note_by = models.ForeignKey(BaseUser, null=True, on_delete=models.SET_NULL, related_name='candidatenotes_user') job_note = models.TextField(max_length=3000) date_added = models.DateTimeField(auto_now_add=True) As you can see the model has 2 Foreign keys (candidate and note_by) On the form i will only be displaying the field 'job_note' the 'candidate' and 'note_by' fields will be populated by the view class CreateNoteView(CreateView): template_name = 'candidates/create_note.html' form_class = CreateNoteForm success_url = reverse_lazy('staff_main') I have been instructed that it is OK, to use the Generic CreateView, but that i will have to 'subclass' the 'get_form()' method and tack on the following: form = CreateNoteForm(...); form.instance.candidate = self.object; form.instance.note_by = self.request.user; form.save() I have looked at the default 'get_form()' method in the CreateView class and it has : def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" if form_class is None: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) How on earth do i tack on form = CreateNoteForm(...); form.instance.candidate = self.object; form.instance.note_by = self.request.user; form.save() to the 'get_form' method, and what do i put in the ... part of : form = CreateNoteForm(...); -
type error when excuting ajax code in django
I am using jquery ajax to get json data into my webpage (Django framework). I can not seem to render the json data (my first step is simply to do a console.log(data)-not working). I am getting a type "unknown" so I think that may be part or all of the problem. In my simple template, I have a button that makes an ajax call which is not working. Code below includes my urls.py file, views.py file with the relevant function, and the ajax code on my website. The network tab on the firefox developers page says code 200, I am assuming this means that my urls.py and views.py were correct, but please let me know if this is true. My app is on pythonanywhere. I am using console.log to if the ajax call can bring up the json data. It did not. My javascript triggers the error code--not sure whey. Thank you for any help you may provide. urls.py: see last url app_name = 'beach' urlpatterns = [ url(r'^$', views.index,name='index'), #when you go to the beach directory, it looks at this urls.py file, this says go to views.py in this folder, index function url(r'^(?P<lakes>[a].*)/$', views.searched, name='lakes'), #regex = starts with … -
Questions about performance and security on application servers
Question 1: My systems use Nginx, RabbitMQ, PostgreSQL, Django. For better performance and security should I keep them on the same server or on separate servers? Why? Question 2: Where is it correct to install memcached on this infrastructure? On the Nginx server? On the application server? -
Inherited serializer/Serialize multiple models in a single view
I have found some similar scenarios, and I have tried their solutions, but it doesn't work for me. Here's the scenario: I have a profile model, which was inherited from User, I have a education model, which extends from profile, they are many-to-one relation, and I hope the education information can be serialized in the profile page(can not be serialized independently) I think it relate to inherited serializer, but I am not sure two model, profile and education: class Profile(models.Model): user = models.OneToOneField(User,on_delete = models.CASCADE) [...] @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Education (models.Model): [...] profile = models.ForeignKey( Profile, related_name = 'education', on_delete=models.CASCADE, ) And I have the following serializers: class ProfileSerializer(serializers.HyperlinkedModelSerializer): user_url = serializers.HyperlinkedIdentityField(view_name='user-detail') user = serializers.ReadOnlyField(source='user.id') id = serializers.IntegerField(source='pk', read_only=True) username = serializers.CharField(source='user.username', read_only=True) [...] education = serializers.HyperlinkedIdentityField( many=True, read_only=False, queryset = Education.objects.all(), view_name='education-detail' ) class Mate: [...] class EducationSerializer(serializers.HyperlinkedModelSerializer): class Meta: depth = 1 model = Education fields = ('url', 'id', 'edu_name', 'qualification','institute','description') I think there is no relation with the view page, so I don't put it in here. I tried to serialize them, when I got the education page, and try to put … -
Set initial value in ModelChoiceField at setup
I am trying to figure out how to set the initial value of a ModelChoiceField when it's created (not on form creation). Below is a very simplified example of what I have now, and I'd like to set a default for State and Country when they render. I thought this could be done in the SetBillingInfo class in Forms.py, but can't get it to work. Say I want to default to California for state and United States for country. Is there a way to set this? FORMS.PY class SetBillingInfo(forms.Form): state = forms.ModelChoiceField( queryset=States.objects.all().order_by('group_order','name'), to_field_name='name', label = '', required=False ) country = forms.ModelChoiceField( queryset=Country.objects.all().order_by('group_order','name'), to_field_name='name', label = '', required=True ) VIEWS.PY billinginfo = SetBillingInfo(initial=request.GET) return render(request, 'index.html',{'billinginfo': billinginfo}) INDEX.HTML (this is not exactly correct but you get the idea) {% for field in billinginfo %} <select class="FormRow"> {{ field }} </select> {% endfor %} -
Saving a .pdf from wkhtmltopdf to a Django model
I am attempting the following: def render_ticket_view(request): template_path = 'ticket.html' context = { ... } response = PDFTemplateResponse( request=request, template=template_path, filename='file.pdf', context=context, cmd_options={'load-error-handling': 'ignore'} ) batch = TicketBatch.objects.create() batch.document.save( "{}-{}.pdf".format(event.name.replace(" ", "_"), batch.id), response.rendered_content ) batch.save() return response What I'd like to do is save the file generated by PDFTemplateResponse into a FileField() on a Django model (I don't care about the actual response at this time). I am having trouble with the response.rendered_content function. It seems it is supposed to return the file. However, no matter what I try to do with it, I get the following error: FileNotFoundError at /ticket/ [Errno 2] No such file or directory: 'wkhtmltopdf': 'wkhtmltopdf' I'm not sure what this means. Is there something I am missing? Furthermore, is there a way to simply get a bytes-like object so that I could attach it to a file handler and save it with ContentFile? -
UUID field in fresh Postgresql DB failing ValidationError: ["'1' is not a valid UUID."]
Wondering if anyone can shed some light on what this error may be coming from. I have just moved to Postgresql from sqllite and at the same time changed my ID fields to UUID. For most of the models it works however I have isolated a few which are causing the migration to fail. The error is AttributeError: 'int' object has no attribute 'replace' django.core.exceptions.ValidationError: ["'1' is not a valid UUID."] As I said this is a new db and am not aware of any code that would create rows upon migration so not sure where the 1 would be coming from. This question appears quite similar however the asker is explicitly setting the integer and trying to pass it as a UUID Model import uuid class Question(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) Trace Running migrations: Applying survey.0001_initial...Traceback (most recent call last): File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 2363, in to_python return uuid.UUID(value) File "/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/uuid.py", line 137, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'int' object has no attribute 'replace' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/jd/.virtualenvs/projectrisk_dev/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in … -
Show foreign key fields in Django Admin list_display
Right now I have two models: Inventory and Item An Item can have multiple Inventory transactions (you can think of these essentially as batches), but an Inventory transaction can have only one item, so one-to-many relationship, right? Anyway, I'm using a foreign key field like so: models.py class Item(models.Model): name = models.CharField(max_length=40) description = models.TextField() brand = models.CharField(max_length=40) class Inventory(models.Model): item = models.ForeignKey(Item, related_name="inventory") **Note: I have more fields than this, but am just narrowing down what I think is relevant to the example. I have it set up in admin to show the list_display for certain fields, and on the InventoryAdmin I can even see the foreign key relationship to the specific Item that Inventory is related to. I would like to see more than just the Item name however in the InventoryAdmin list_display and in the edit/form also. Is there a way to do this so I can show brand alongside Item name for example? Lastly, is there a way to after I add an Item using ItemAdmin to in the same ItemAdmin form be able to add edit/add Inventory directly without having to leave and having to do it through InventoryAdmin? Here's my admin.py, thank you: class … -
Django Rest Framework ManyToMany field ordering
I've got the following models: class BusStop(m.Model): street_name = m.CharField(max_length=255) class Meta: ordering = ['mpk_street'] ... class Carrier(m.Model): name = m.CharField(max_length=255) ... class CarrierStop(m.Model): bus_stop = m.ManyToManyField(BusStop, related_name='carrier_stop_fk') carrier = m.ForeignKey(Carrier, on_delete=m.CASCADE, related_name='test_carrier_fk') I made the serializer: class CarrierStopSerializer(serializers.ModelSerializer): carrier = serializers.StringRelatedField() bus_stop = serializers.StringRelatedField(many=True) class Meta: model = CarrierStop fields = ['id', 'carrier', 'bus_stop'] I've got some objects of BusStop models and serializer gives representation like this: [ { "id": 1, "carrier": "Fremiks", "bus_stop": [ "Armii Krajowej", "Kino Lot 01", "Kosynierów I 02" ] } ] bus_stop field from CarrierStopSerializer returns bus stops ordered by name. I want to order it by id in intermediate table carrierstop_bus_stop created by Django ManyToMany field. I know that i should use SerializerMethod field instead of StringRelatedField(or PrimaryKeyRelatedField, doesn't matter) but I'm not sure how to do this exactly. -
Django REST: Alternative serializer lookup field
I'm creating this simple shopping API in Django REST. Internally I'm using IDs for foreign key constraints, while guuids are brought to the outside world. For the checkout procedure the user provides a list of article IDs hes willing to purchase. The object in the POST data thus looks as follows: { assets: [ { 'product': 'd9d5044d-2284-4d15-aa76-2eee3675035b', 'amount': 4 }, .... ] } I'm using the following ticket/asset models: # Ticket class Ticket(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='tickets', on_delete=models.CASCADE) # Assets class Asset(models.Model): ticket = models.ForeignKey(Ticket, related_name='assets', on_delete=models.CASCADE) stock_item = models.ForeignKey(Stock, related_name='stock_item', on_delete=models.SET_NULL, null=True) amount = models.IntegerField(validators=[MinValueValidator(0)]) And the serializers look as follows: # Asset serializer class AssetSerializer(serializers.ModelSerializer): class Meta: model = Asset fields = ('stock_item', 'amount') # Ticket serializer class TicketSerializer(WritableNestedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') assets = AssetSerializer(many=True) class Meta: model = Ticket fields = ('uuid', 'owner', 'assets', ) def perform_create(self, serializer): serializer.save(owner=self.request.user) When posting an object of the type specified above, the following error is presented: {"assets":[{"stock_item": ["Invalid type. Expected PK, received string"]}]} Which I can't seem to solve, how do I instruct the serializer to use the uuid as the lookup value? I solved a similar problem on view-level earlier by using the 'lookup_field' … -
Add a custom button to Django change view page
I am following this tutorials to add a custom button in change view. but it add the buttons at bottom of the page which is not useful. https://media.readthedocs.org/pdf/django-admin-cookbook/latest/django-admin-cookbook.pdf (page 42) I want to add it like in the picture Here is my file templates\admin\pages\change_form.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} {{ block.super }} <div class="submit-row"> <input type="submit" value="Make Unique" name="_make-unique"> </div> {% endblock %} How to change the code so that i can make it appear at the top of page? -
Is there anything analogous to Django "make migration" or "migrate" in java hibernate /jdbc / flyway?
I am trying to create a database installation script based on the java models defined in my project . I was trying to work with liquibase but liquibase does not provides a way to compare the database to the java models and create a change log script . I want to achieve something similar to what we have in Django "Migrate" and "make migrations" . -
django+js: Display data in html using javascript
I have a function get_data in Django which returns json.dumps(data). The view for the page which gets this file is: def view_fn(request): data = get_data() return render(request, 'view.html', {'data': data}) I am experimenting with javascript and trying to get the data in html. <script> var json = '{{data}}'; alert(json); </script> I am not able to get/parse the json data properly in html. How to do this using javascript? -
concurrent celery tasks execute and stores result but .get not working
I have written a Celery Task class like this: myapp.tasks.py from __future__ import absolute_import, unicode_literals from .services.celery import app from .services.command_service import CommandService from exceptions.exceptions import * from .models import Command class CustomTask(app.Task): def run(self, json_string, method_name, cmd_id: int): command_obj = Command.objects.get(id=cmd_id) # type: Command try: val = eval('CommandService.{}(json_string={})'.format(method_name, json_string)) status, error = 200, None except Exception as e: auto_retry = command_obj.auto_retry if auto_retry and isinstance(e, CustomError): command_obj.retry_count += 1 command_obj.save() return self.retry(countdown=CustomTask._backoff(command_obj.retry_count), exc=e) elif auto_retry and isinstance(e, AnotherCustomError) and command_obj.retry_count == 0: command_obj.retry_count += 1 command_obj.save() print("RETRYING NOW FOR DEVICE CONNECTION ERROR. TRANSACTION: {} || IP: {}".format(command_obj.transaction_id, command_obj.device_ip)) return self.retry(countdown=command_obj.retry_count*2, exc=e) val = None status, error = self._find_status_code(e) return_dict = {"error": error, "status_code": status, "result": val} return return_dict @staticmethod def _backoff(attempts): return 2 ** attempts @staticmethod def _find_status_code(exception): if isinstance(exception, APIException): detail = exception.default_detail if exception.detail is None else exception.detail return exception.status_code, detail return 500, CustomTask._get_generic_exc_msg(exception) @staticmethod def _get_generic_exc_msg(exc: Exception): s = "" try: for msg in exc.args: s += msg + ". " except Exception: s = str(exc) return s CustomTask = app.register_task(CustomTask()) The Celery App definition: from __future__ import absolute_import, unicode_literals import os from celery import Celery, Task from django.conf import settings # set the default Django … -
SyntaxError: invalid syntax in URLpattern
hi am getting a syntax error url: url(r'^reset-password/$', PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'), What is the problem? thanks -
How to create/update in DRF many-to-many fields?
I have four models: QuestStatus AdventureStatus QuestAdventureStatus (consists of two things, foreign key fields to QuestStatus and AdventureStatus) QuestAdventure (has the M2M relationship to QuestAdventureStatus) I have a serializer for QuestAdventure and QuestAdventureStatus exists as a field on my serializer: quest_adventure_status = serializers.ListField(source='quest_adventure_status.all', required=False) How do I properly create a new QuestAdventure and create quest_adventure_status(es) as well (updating too)? For creating, quest_adventure_Status is mandatory, but when I pass in my instance it's already serialized and not model objects? Is there a proper way to deal with this in DRF? -
Django - extending contrib.sites.get_current_site logic
What is the best-practice pattern to replace/extend functionality in django.contrib libraries? My use case in this instance is to add domain alias awareness to the contrib.sites lib. A similar question was asked two years ago, but remains essentially unanswered: Override django get_current_site - Work with subdomain I've already created our own sites library that incorporates the additional model updates and logic we need, but other third-party libraries we use are directly calling django.django.contrib.sites.models.objects.get_current(). We've begun maintaining a local fork of each of these libs to update the call to point to our customized sites lib instead. Is there a more efficient solution here? -
Possible to have different requirements in django app than parent?
I'm trying to contribute to a project where is using some older package versions don't meet the minimum version requirements for the packages I need to use. Specifically, I need to use Channels which has a minimum Django requirement of 1.11, but the project is running on v1.8. I was told by the project lead that it's possible to have different requirements for different versions of packages in your apps by specifying them in your requirements.txt file, but I can't find any instructions online about how to achieve such a thing (I'm new to Django so learning as I go on this project). From what I understand the requirements.txt file is generated from the freeze command, so I would need to install these packages before I do that, in which case would I need to have nested virtual environments? I can see how this would be possible were I developing in a vacuum, but I need this app to exist in the context of the larger application. I will be using the existing database and visual styles and so need this to reference aspects of the existing site. I played around with upping the minimum version of Django for the … -
Django Class-based View and URL configuration
I am trying to learn Django and I am stuck with Class-based views and URLconf. From what I understand I should see my test.html at localhost/app1/test1/test/test.html, but I get an error page not found. I am not sure what I am doing wrong. #~/project_folder/mysite/ulrs.py urlpatterns = [ path('admin/', admin.site.urls), path('app1/test1/', include("app1.urls")), ] #~/project_folder/app1/urls.py urlpatterns = [ path('test/', TemplateView.as_view(template_name="test.html"), name="home"), ] #~/project_folder/static/templates test.html #~/project_folder/mysite/settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'static/templates'), ], 'APP_DIRS': True, ... } STATIC_URL = os.path.join(BASE_DIR, 'static/') -
Django python send email with non-english characters
I try to send email with russian chracters, but as an output I get Subject: (b'\xd0\xaf\xd0\x9a\xd0\xbb\xd1\x8e\xd1\x87\xd0\xbd\xd0\xb8\xd0\xba - \xd0\xbf\xd0\xbe\xd1\x81\xd1\x82\xd1\x83\xd0\xbf\xd0\xb8\xd0\xbb\xd0\xb0 \xd0\xbe\xd0\xbf\xd0\xbb\xd0\xb0\xd1\x82\xd0\xb0', 27) This is my code: subject = 'поступила оплата' body = 'email body' send_mail( subject body, 'from@gmail.com', ["to_email@test.com"], fail_silently=False, ) I tried subject.encode('utf8') subject.decode('utf8') subject.encode('utf8').decode('utf8') codecs.utf_8_encode(subject) But didn't help. What do I do? -
Remove extra characters from DateField in Django Admin form
I'm trying to have the DateField (created_at/updated_at) I have set up to be a readonly field that I can access through both the list_display and the form for adding in Django Admin. The way I have it set up it's showing as: %09/%24/%2018 I know it's pulling from DATE_FORMAT in settings.py: DATE_FORMAT = '%m/%d/%Y' I just haven't figured out how to remove the % before it is displayed in Admin. Is there a way to clean this up? I've tried already to access the created_at/updated_at fields to write an algorithm to remove the extra characters, but can't seem to extract the values. Here is my code if that helps. Thanks in advance! admin.py class BatchForm(forms.ModelForm): class Meta: model = Batch fields = '__all__' class BatchAdmin(admin.ModelAdmin): form = BatchForm readonly_fields = ('created_at', 'updated_at') list_display = ('item', 'active', 'desc', 'quantity', 'created_at', 'updated_at') models.py class Batch(models.Model): created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
Why will the css in my django project not render?
I'm still just playing around with Django and cannot figure out what I am doing wrong with my CSS file. My HTML works but not the CSS. I'm guessing it has something to do with settings.py or some special "Django code" I'm not using. Here is the code for my HTML (what I am guessing is the relevant code to show). Here is my HTML: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>home</title> <link rel="stylesheet" type="text/css" href="../css/styles.css"/> </head> <body> <h3>HELLO WORLD!</h3> </body> </html> Here is my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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 = 'ecommerce005.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Here is my urls.py: from django.conf.urls import url from django.contrib import admin from .views import home_page urlpatterns = [ url(r'^$', home_page), url(r'^admin/', admin.site.urls), ] Here is my views.py: from django.http import HttpResponse from django.shortcuts import render def home_page(request): return render(request, "index.html", {}) The order of my file are as follows: 'src' directory: 1) 'css' folder holds my styles.css file 2) 'projectname' folder contains all of my django files shown above 3) 'templates' …