Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django user-uploaded media files in production with Dokku
I would like to serve user uploaded media files using nginx on the same host as the Django application rather than a CDN or S3 or similar. The django-private-storage library can be used to protect media files behind a login: https://github.com/edoburu/django-private-storage I am deploying my Django application with Dokku. Dokku says that dokku persistant storage plugin should be used to allow for user uploads to be persisted on the host. https://dokku.com/docs~v0.9.2/advanced-usage/persistent-storage/ My confusion is that django-private-storage requires you to edit the config for nginx. Specifically, it requires you to set the location of the private media being served to be internal. So that the URL cannot be accessed from the outside by a user who isn't logged in. The dokku docs don't explain how to use persistant storage behind an application login. Do I actually need django-persistant-storage to be able to write user uploaded media? How can I combine these solutions so that my application, which is inside a container, can read and write media files, which media files are served by nginx, and served at an internal location that can only be accessed by a user who is logged into the application? -
Why am I getting an integer precision error when I run: heroku run python manage.py migrate
I have deployed a Django app on Heroku, but I want to migrate to PostgreSQL, so I am following a video tutorial on YouTube on how to do that. In the tutorial, we have to run Heroku run python manage.py migrate to migrate my current SQLite database to the PostgreSQL one on Heroku. I keep getting this error: psycopg2.errors.CannotCoerce: cannot cast type date to double precision LINE 1: ...cted" TYPE double precision USING "lastInteracted"::double p... Here is my models.py file. I am pretty sure that the problem is in the Conversation model with the lastInteracted variable, but I do not know why it is happening. from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.fields import CharField from django.db.models.fields.files import FileField, ImageField, ImageFieldFile from django.utils.timezone import localtime, now from datetime import datetime import time import os import sys from django.core.files.base import File from django.core.files.uploadedfile import InMemoryUploadedFile class User(AbstractUser): userType = models.CharField(max_length=20, default="student") profile_pic = models.ImageField( null=True, blank=True, default="blankUserIcon.svg") class Classroom(models.Model): name = models.CharField(max_length=100, default="Classroom") students = models.ManyToManyField(User, blank=True) teacher = models.ForeignKey( User, on_delete=models.CASCADE, related_name="teacher") code = models.CharField(max_length=20) subject = models.CharField(max_length=50, default="") theme = models.CharField(max_length=20, default="cardBlue") class Comment(models.Model): date = models.DateTimeField(default=datetime.now()) text = CharField(max_length=5000, default="") commenter = models.ForeignKey( User, on_delete=models.CASCADE, related_name="commenter", … -
close div with js event listener in django
i want to add a js eventlistner so i could close an alert pop up after display, below is the current code...i have the script in separate file as well. Thank you Hello all, i want to add a js eventlistner so i could close an alert pop up after display, below is the current code...i have the script in separate file as well. Thank you JS Code: // Invoke Functions Call on Document Loaded document.addEventListener("DOMContentLoaded", function () { hljs.highlightAll(); }); let alertWrapper = document.querySelector(".alert"); let alertClose = document.querySelector(".alert__close"); if (alertWrapper) { alertClose.addEventListener( "click", () => (alertWrapper.style.display = "none") );`enter code here` } Template Code: <!DOCTYPE html> {% load static %} <html> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Favicon --> <link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" /> <!-- Icon - IconMonster --> <link rel="stylesheet" href="https://cdn.iconmonstr.com/1.3.0/css/iconmonstr-iconic-font.min.css" /> <!-- Mumble UI --> <link rel="stylesheet" href="{% static 'uikit/styles/uikit.css' %}" /> <!-- Dev Search UI --> <link rel="stylesheet" href="{% static 'styles/app.css' %}" /> <title>DevSearch - Connect with Developers!</title> </head> <body> {% include 'navbar.html' %} {% if messages %} {% for message in messages %} <div class="alert alert--{{message.tags}}"> <p class="alert__message">{{message}}</p> <button class="alert__close">x</button> </div> {% endfor %} {% endif … -
Django - Admin Area width
My admin area on my Django application is a little bit off since a few days. I don't know what I did wrong... At the moment, the width is not fully used by the tables and the forms. The buttons instead are using the full width. Where can I change the width to full for the forms and tables? Is this a problem in Django or just visualization? In the second screenshot you can see, that the area should be on the full width. PS: It's not a browser problem, I tried. Cheers guys :) Screenshot Django Admin Area Screenshot Django Admin Area with selected width -
I am new to Django Rest Framework and practicing this question but i am not able to understand it can anyone help me solve it
Summary: Extend Django Project with Django REST Framework for a simple prebuild booking app that have: - Listing object with two types - booking_engine.models : - Apartment(single_unit) have booking information (price) directly connected to it. - Hotels(multi-unit) have booking information (price) connected to each of their HotelRoomTypes. - filtering through Listings and returning JSON response with available units based on search criterias. - should handle large dataset of Listings. There is a pre-build structure for Hotels/Apartments (could be changed or extended). Database is prefilled with information - db.sqlite3. superuser username: admin password: admin We should be able to block days ( make reservations ) for each Apartment or HotelRoom. A new Model for blocked (reserved) days must be created NEW endpoint where we will get available Apartments and Hotels based on: available days (date range ex.: "from 2021-12-09 to 2021-12-12") - Apartment should not have any blocked day inside the range - Hotel should have at least 1 Hotel Room available from any of the HotelRoomTypes max_price (100): Apartment price must be lower than max_price. Hotel should have at least 1 Hotel Room without any blocked days in the range with price lower than max_price. returned objects should be sorted … -
Finding Largest Value of an Integer Field - Django
I have a Django website and one of my models has an integer field. Does anyone know of a way to retrieve the largest value currently in that field into the view? Thanks! -
Django: How to automatically generate the USERNAME_FIELD of a custom user model?
This is a learning project and I've been trying to create a custom user model with the possibility of having multiple accounts with the same nickname. The USERNAME_FIELD would be username = f"{nickname}#{random_number}" (just like the Blizzard and Discord format), but I can't figure out at which step I should include the function that would automatically create the username. I tried generating the username in the CustomAccountManager.create_user() method but it doesn't seem to be called while filling the RegistrationForm from the view and it fails to create the superuser with manage.py createsuperuser (TypeError: create_superuser() got an unexpected keyword argument 'username'). I'd be glad if someone could explain how to procede in this case or link a resource, I couldn't find one with this kind of example. Any additional insight on the code will be appreciated. I have registered the model in admin.py with admin.site.register(Account), included the accounts app in the settings and set AUTH_USER_MODEL = 'account.Account' account/models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from random import randint from django.contrib.auth import get_user_model ### ACCOUNT class CustomAccountManager(BaseUserManager): def create_user(self, email, nick, password = None): if not email: raise ValueError("Email was not provided during user creation. (account/models.py/CustomAccountManager.create_user)") if not nick: raise ValueError("Username was not … -
Django how to raise validation error if foreignkey objects id change in hidden input
I have an hidden foreigkey filed in my forms. I want to raise validation error or stop submitting forms if user try to change the value. here is my code: html: {%for i in user_profile%} <input type="hidden" name='userprofile' value="{{i.id}}"> {%endfor%} models.py: class BlogComment(MPTTModel): userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) #my others model fields... views.py: user_profile = UserProfile.objects.filter(user=request.user) I want to raise validation error if current id change in hidden input. how to do that? -
url template tag in django from parent project
i was trying to use the url tag in my template: <div><a href="{% url 'download_file' filename='rilasci_progetto_scuole.xlsx' %}">Esporta file Excel</a></div> the template path is: \FastFM\Scuole\templates the 'download_file' function is declared inside the views.py (\FastFM\FastFM\views.py) of the parent project (the name is FastFM) but the html in wich i want to use it is in the app named scuole Scuole: the parent urls.py (\FastFM\FastFM\urls.py) is: urlpatterns = [ path('admin/', admin.site.urls), path('', views.FastFMHome.as_view(), name='FastFM') , path('Scuole', include('Scuole.urls')), path('RilasciSettimanali', include('RilasciSettimanali.urls')), path('accounts/', include('django.contrib.auth.urls')), path('downloadxls', views.download_file, name='download_file'), the intention was to put the downloadxls path in the main project to use it in the others apps. By the way, i get the NoReverseMatch exception. -
Where to store files for admin to download in Django?
I have some example files that I want to serve in a download link to all admins. They are not model dependant or user dependant (other than requiring admin). They're txt files and the same files must be available to all admins. I cannot find anything about this in the docs, or maybe I don't know what to look for. As far as I understand only css, js and images are static files, so should txt files be in /media/? Where can I put these files so only admins can download them? Right now I have a hard coded link in my custom admin template to /media/admin/examples/data_template.txt, but anyone can get to this link. I have these configs in settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Django Rest Framework | TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')])
I'm trying to update a ManyToManyField in a UserProfile, which is part of my custom User model in my Django REST API. However, I get this error: TypeError: Field 'id' expected a number but got OrderedDict([('name', 'string')]) Since I'm doing this in my update() method in my UserSerializer, I already have an instance created. account/serializers.py class UserSerializer(serializers.ModelSerializer): password = serializers.CharField( max_length=68, min_length=6, write_only=True) userprofile = UserProfileSerializer(write_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'tokens', 'userprofile'] # Read-only b/c doesn't need any validating parameters read_only_fields = ['tokens'] def update(self, instance, validated_data): """Perform an update on User""" # Remove password field b/c we don't want to iterate over it in the # validated_data dictionary. Django will salt/hash it. validated_data.pop('password', None) profile_data = validated_data.pop('userprofile', {}) skills = profile_data.pop('skills', []) for (key, value) in validated_data.items(): # Set remaining keys in the user setattr(instance, key, value) instance.save() for (key, value) in profile_data.items(): setattr(instance.userprofile, key, value) for skill in skills: instance.userprofile.skills.add(skill) instance.userprofile.save() return instance The error occurs when I call add() for updating the user's skills. The model and serializer for Skill are defined below: user_profile/models.py class Skill(models.Model): name = models.CharField(max_length=120) def __str__(self): return self.name user_profile/serializers.py class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill … -
Creating a Blogpost Like/Dislike Button within Django/Wagtail
I'm new to Django and Wagtail and have looked for a way to implement a "simple" like/dislike button on a blog entry page using Wagtail. I included a total_likes IntegerField in my model for the page and would like to increment or reduce this int within the database when the user clicks a button on the html template. The user is not supposed to be logged in. Most tutorials I've found deal with this only for registred users which is not something I want. I would be glad if somebody could point me in the right direction. The models.py code is below. I do not understand how to call a function from within a template. class BlogEntry(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250, blank=False) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogEntryTag, blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=False) total_likes = models.IntegerField(blank=False, default=0) image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) streamBody = StreamField([ ("text", blocks.StaticContentBlock()), ("quotes", blocks.QuoteBlock()), ("image_and_text", blocks.ImageTextBlock()), ("related_articles", blocks.RelatedArticlesBlock()), ], null=True, blank=True) sidebarBody = StreamField([ ("text", blocks.StaticContentBlock()), ("quotes", blocks.QuoteBlock()), ("image_and_text", blocks.ImageTextBlock()), ("related_articles", blocks.RelatedArticlesBlock()), ], null=True, blank=True) search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel("image"), FieldPanel('date'), FieldPanel('tags'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ], heading="Blog information"), FieldPanel('intro'), … -
Django for...empty with different container when empty
I have a common pattern in which I have a container in HTML (e.g., ul, table ...) with elements from a queryset. However, when the list is empty, I don't want to display the container itself. I seek to get the equivalent of {% if query.exists %} <ul class="list-of-stuff"> {% for x in query %} <li>{{ x }}</li> {% endfor %} </ul> {% else %} <p class="information"> The list is empty. </p> {% endif %} but without extra query (query.exists), much like for...empty does. However, one large drawback of for...empty is that I cannot remove or change the container when the list is empty. How can I get an equivalent of the above with only one execution of my query in a clean way (i.e., without displaying the container tag if forloop.first and such)? I'm open for implementing new tags or filters. -
Django URLs file redirecting the different URLs to the wrong html files
My Django site isn't working properly. It's hard to explain but when I run my Django web server and go to http://127.0.0.1:8000/hello/ I see "Hello, World!" as expected. But when I go to http://127.0.0.1:8000/dashboard/ I see the same thing, when I should be seeing "Hello". There is to much code to put on stack overflow and it won't make sense so I made a GitHub repo https://github.com/Unidentified539/stackoverflow. -
Django models - how to track a field on an object when value of the field depends on the different users?
I want a Book object with the field is_read, but the value of the is_read depends on the user. When I first created this app I was only thinking of one user (me). class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) is_read = models.BooleanField(default=False) But if the app has multiple users then of course the is_read needs to change according to the user. new models class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) class IsRead(models.Model): user = models.ForeignKey(User, on_delete=CASCADE) book = models.ForeignKey(Book, on_delete=CASCADE) is_read = models.BooleanField(default=False) I think adding the IsRead class will help but I need an IsRead object to automatically be created every time a new user or book is created. Not only that, but every time a new user is created, I have to iterate through all the books. Or if a new book is added, I have to iterate through all the users. This seems like a lot of db work just to keep track of who has read what books. Even if the above is the correct strategy I don't know how to I would do it. I did try to overwrite AdminModel to save the IsRead but this did not work. I did not … -
retrive data according to the dropdown list item selected, in django
I have a dropdown list that is populated with "price range" from the database. I want to show the relevant "price" according to the "Price Range" for example, in the database, I have this row Price Range Price "0-1500" 28 "1501-1750" 30 What I want when I select the range "1501-1750" the corresponding "price" value shown in an input field or paragraph tag. Below are my Model.py, views.py, and home.html files models.py from django.db import models class price_range(models.Model): name = models.CharField(max_length=100, null=False) price = models.IntegerField(null=False) views.py from django.shortcuts import render from range.models import price_range def showobj(request): displayvalues = price_range.objects.all() return render(request, 'range/home.html', {"range":displayvalues}) home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Range</title> </head> <body> <center> <select name="drop1"> <option selected disabled="true">Select the Price Range</option> {% for results in range %} <option> {{results.name}} </option> {% endfor %} </select> </center> </body> </html> -
TypeError: filter must be an instance of dict, bson.son.SON, or any other type that inherits from collections.Mapping
In a Python function If I write like this, I get Expected expression Pylance in vscode. document = await collection.find({'date': {$gte: {start_date}, $lte: {end_date}}}).to_list(100) Here, date is my field and sart_date, end_date are the dynamic value that specify the specific range of documents I'd like to get from database. And, then because of Pylance error, I changed code like this: query_string = {"date": f'{{date: {{$gte: {start_date}, $lte: {end_date}}}}}'} document = await collection.find(query_string["date"]).to_list(100) And also, writing print(query_string) I get {date: {$gte: '2021-07-15T16:18:46.688Z', $lte: '2021-07-18T12:18:45.258Z'}} on terminal as well that means the value of query_string variable is right. Even If I check with this query in mongodb compass gui app, it returns me the desired data from database. So why getting title's error when the function runs? Please, help me up. For your convenience, the whole function is: # routing in FastAPI @router.get('/api/{start_date}_{end_date}') async def query_date_from_person(start_date, end_date): query_string = {"date": f'{{date: {{$gte: {start_date}, $lte: {end_date}}}}}'} document = await collection.find(query_string["date"]).to_list(100) return document -
Django/react Dockerfile stages not working together
I have a multistage Dockerfile for a Django/React app that is creating the following error upon running docker-compose up --build: backend_1 | File "/code/myapp/manage.py", line 17 backend_1 | ) from exc backend_1 | ^ backend_1 | SyntaxError: invalid syntax backend_1 exited with code 1 As it stands now, only the frontend container can run with the two below files: Dockerfile: FROM python:3.7-alpine3.12 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY . /code RUN pip install -r ./myapp/requirements.txt FROM node:10 RUN mkdir /app WORKDIR /app # Copy the package.json file into our app directory # COPY /myapp/frontend/package.json /app COPY /myapp/frontend /app # Install any needed packages specified in package.json RUN npm install EXPOSE 3000 # COPY /myapp/frontend /app # COPY /myapp/frontend/src /app CMD npm start docker-compose-yml: version: "2.0" services: backend: build: . command: python /code/myapp/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" networks: - reactdrf web: build: . depends_on: - backend restart: always ports: - "3000:3000" stdin_open: true networks: - reactdrf networks: reactdrf: Project structure (relevant parts): project (top level directory) api (the django backend) frontend public src package.json myapp manage.py docker-compose.yml Dockerfile The interesting thing is when commenting out one service of the Dockerfile or docker-compose.yml or the other, … -
Django: Save a formset with commit=False (Docs say nothing)
With a form its easy, one does something like this: obj = form.save(commit=False) obj.foo = 1234 obj.save() obj.savem_m2m() # If has a ManyToMany field Now for formset is seems much more complicated. The documentation does not shed any light: it only briefly mentions saving and deleting without explaining how. So I checked the sourcecode for a formset.save(): def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m return self.save_existing_objects(commit) + self.save_new_objects(commit) So if one has commit = False, I am guessing one needs to do the work of save_existing_objects, and save_new_objects. Looking at these two functions they are rather large: def save_existing_objects(self, commit=True): self.changed_objects = [] self.deleted_objects = [] if not self.initial_forms: return [] saved_instances = [] forms_to_delete = self.deleted_forms for form in self.initial_forms: obj = form.instance # If the pk is None, it means either: # 1. The object is an unexpected empty model, created by invalid # POST data such as an object outside the formset's queryset. # 2. The object was already deleted from the database. if obj.pk … -
Python/Django 'OperationalError:no such table: main.auth_user_old' in Django Rest Forest (DRF)
I'm trying to create an RESTful API at the URL /polls/ in Django and DRF using a SQLite database. But I keep getting the error below. I'm using DRF's authentication system. What could be the problem? Thanks in advance! cursor.execute(sql, params) ..... ..... django.db.utils.OperationalError: no such table: main.auth_user__old "POST /admin/vote/poll/add/ HTTP/1.1" 500 215568 ``` The apps URL Patterns code: ``` urlpatterns = [ path("polls/", PollList.as_view(), name="polls_list"), ] ``` The models code: ``` class Poll(models.Model): question = models.CharField(max_length=100) created_by = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now=True) ``` -
Renaming Django model without breaking existing migrations
I want to rename a model in Django 3.2, keep my existing migrations and be able to both migrate a db with the old table name and create a db from scratch. I've started by renaming the model class and all references to it in the code. As "./manage.py makemigrations" did not automatically create a migration, I manually created a migration that renames the model: from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('market_integrations', '0003_migration'), ] operations = [ migrations.RenameModel('OldModelName', 'NewModelname') ] My initial idea is that I should not update existing migrations, as I never do when creating other migrations. However, the references to the old model in the old migrations cause a LookupError when I run "./manage.py migrate". I've tried using both the model name string and apps.get_model(). Sample codes that break: operations = [ migrations.CreateModel( name="OldModelName", ... ) ] operations = [ migrations.CreateModel( name=apps.get_model("myapp", "OldModelName"), ... ) ] As keeping the old model name in old migrations didn't work, I replaced the old model name in old migrations with the new name. "./manage.py migrate" ran successfully, including the model renaming migration. However, when I try to create a new database, the model renaming migration fails because … -
How to display li tag in JavaScript or how to display p tag
I want to complete the following code with Django and JavaScript. What I want is <li><p id="optprice">{{value.extra_cost}}</p><option id="value" value="{{value.value_code}}">{{value.name} } (+{{value.extra_cost}}won)</option></li> In this part <p id="optprice">{{value.extra_cost}}</p> I want to float this. So in javascript var optprice = $("#optprice").text(); I did this, but it doesn't show up. What's the problem? Any help would be appreciated. <form method="POST" action="{% url 'zeronine:join_create' id=product.product_code %}"> <div class="form-group row" style="margin-top: -5px"> <label for="optionSelect" class="col-sm-6 col-form-label"><b>옵션</b></label> <div class="col-sm-6" style="margin-left: -90px;"> <select type="text" class="form-control" name="value_code" id="optionSelect" value="{{ form.value_code }}"> <option value="none">옵션을 선택하세요.</option> {% for option in option_object %} {% if option.option_code.option_code.option_code == value.option_code %} {%if option.product_code == product %} <optgroup label="{{option.name}}"> {% for value in value_object %} {% if value.option_code.option_code == option.option_code %} {%if value.product_code == product %} <li><p id="optprice">{{value.extra_cost}}</p><option id="value" value="{{value.value_code}}">{{value.name}} (+{{value.extra_cost}}원)</option></li> {% endif %} {% endif %} {% endfor %} {% endif %} {% endif %} {% endfor %} </optgroup> </select> </div> <div id="selectOptionList" style="margin-top:10px; margin-left: 20px; margin-bottom: -10px;"></div> </div> <script> $().ready(function() { $("#optionSelect").change(function(){ var checkValue = $("#optionSelect").val(); var checkText = $("#optionSelect option:selected").text(); var product = $("#productname").text(); var optprice = $("#optprice").text(); if (checkValue != "no") { // 없음 선택 아닐경우 var whtml = "<hr style='width: 300px; margin-bottom: 30px;'><p style='font-size: 17px;'>"+product+"</p><p style='font-size: 16px; margin-top: -10px; margin-bottom: … -
Django how to connect user profile model with comment model for showing data from user profile?
I want to show user profile picture publicly in my blog comment section. I tried to use foreignkey in my comment model for connect user profile model then use this in my html for showing profile picture but didn't work. <img src="{{blogcomment.userprofile.profile_pic.url}}"> #didn't show any profile picture until I manually go to admin panel and set foreignkey of userprofile in my blogcomment model. here is my full code: userprofile model class UserProfile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile") profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True) blogcomment model: class BlogComment(models.Model): blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True,related_name="blogcomment_blog") comment = models.TextField(max_length=50000) name = models.CharField(max_length=250) userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_comment',blank=True,null=True) views.py: if comment_form.is_valid(): isinstance = comment_form.save(commit=False) isinstance.user = request.user isinstance.blog = blog isinstance.save() -
django urlpattern path argument empty (' ') meaning?
I am linking a views to urls.py inside the app. Django docs show it like this from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Note: This urls.py is from app not the project, I have already directed the project(from urls.py) to this file. I want to ask what does path('') means, the first argument of path. What kind of urlpattern is this? -
Can't load CSS Django IIS
I have deployed my web app on Microsoft IIS on my company server. Web.config file is set up and app is running with all permissions. I have created Virtual Directory (to enable serving static files map a static alias to the static directory, C:/inetpub/wwwroot/PyWeb/static/). No matter what I do I can't get my 'blog/main.css'. CSS is not loaded and I get error: Refused to apply style from 'http://localhost/static/blog/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="shortcut icon" href="/media/favicon.ico"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> Part href="/media/favicon.ico" is working and my icon is loaded. I have tried to remove rel="stylesheet" but it did not help. Also, I have run collectstatic: C:\inetpub\wwwroot\PyWeb>python manage.py collectstatic Starting Scheduler... You have requested to collect static files at the destination location as specified in your settings: C:\inetpub\wwwroot\PyWeb\static This will overwrite existing files! Are …