Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while connecting to a cloud sql instance via cloud proxy in django using cloud run
I am trying to connect to cloud-sql for a django project in cloud run which is being deployed through cloud run in production. However Django throws me an error saying Error: 'asia-south1' is not a valid port number. My database settings in settings.py is as follows if os.getenv('ENV') == 'PROD': DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '/cloudsql/<PROJECT-NAME>:asia-south1:<INSTANCE-ID>', 'PORT': '5432', 'USER': <USER>, 'PASSWORD': <PASSWORD>, 'NAME': <DB_NAME>, } } I saw one possible solution as redirecting cloud proxy connections to 127.0.0.1:3306 but for that I'd have to install cloud proxy on the docker container and authenticate right? Isn't that what cloud run provides us without any of that hassle? Is there anyway of connecting to the cloud sql instance without installing cloud proxy on the container and redirection? -
python import module using relative path
Suppose I have the following files app/views/ - __init__.py - foo.py foo.py has def bar() # app/urls.py from . import views urlpattrns = [ path('foo', views.foo.bar) ] I get error module app.views has no attribute foo The error goes away when I add from . import foo to app/views/__init__.py I had a (possibly misguided) notion, you can access any module and any name inside module using relative path. But it fails here and wonder why -
Is it possible to store an attribute foreign key in django models?
In SQL, you can have a table attribute be a foreign key, where that foreign key is the attribute of the referenced table. In Django Models, the models.ForeignKey() references an object. Is it possible to reference the fields instead of the object? If not, how should one go about designing models in a way where we can use referenced object. For instance, if I had the following tables. I could do this in SQL: pk courseList(course_id, course_title, professor, day, time) pk TutoringClassList(course_id, tutor_id) Here, course_id in TutoringClassList is the foreign key to the course_id in courseList However, Django would have something like this for TutoringClassList TutoringClassList(course, tutor) Where course is a model foreign key object referencing the courseList, and tutor (we assume there is a TutorList model created as well), is also a model object referencing the TutorList END GOAL I want to store the attribute of the foreign key instead of the object. If I can't do that, what is the best way to manipulate that attribute value for that object? -
Is there a work around for css cut-off with linear gradients?
https://drive.google.com/file/d/11vMD9bFavvkPB0B19VL3GOUTLywA8tki/view?usp=sharing https://drive.google.com/file/d/1XruddpMVdu83itizNQM1fwQRQgOJD0op/view?usp=sharing the one that doesn't have the weird blue thing is how I want it to look, and it is how it looks when I am in full screen on my monitor, however the second one is what happens when I shrink the window and the table takes up too much space for it to fit, however you can still scroll sideways and then the result is this weird bar on the second page. Please note I am using django and its scaling, the background is the linear gradient builtin, in CSS. Any help is appreciated and please try not to be toxic in the comments :) -
Multiple types of users in Django
I want to create two types of login and registration models in Django. The first one will use the inbuilt User model for registering and logging in. The second one will use a 12-digit unique code and date of birth for login and registration. These are for two types of users and I don't want to combine the details into one model. I want to use "request.seconduser" like how Django provides "request.user" for the inbuilt User model so that I can recover unique code and date of birth by just doing "request.seconduser.uniquecode" just like how we can get username and other information in User model like "request.user.username". -
Unable to open datasource `' with the following drivers
I am trying to ensure I have geodjango properly installed so I can follow this tutorial. I have used Brew as my installer for Geodjango prequisites: postgresql, postgis, gdal, libgeoip. My gdal version is most recent: 3.1.2. However when I try to use ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp to examine an .shp file it returns this error in the console: Unable to open datasource '[this is the name of the file here'] with the following drivers. It then just lists a whole bunch of drivers. I can't for the life of me figure out what to do, all the other answers to similar questions recommend upgrading GDAL but mine is the most current version... -
Django Rest - Export CSV
I have Json like below [ { "id": 1, "interviewer": "hengtw1", "interview_date": "2020-06-28", "created_at": "2020-08-07T06:57:27.205527Z", "partner": { "id": 1, "name_kh": "fddafd", "name_english": "twg1", "joined_year": 1991, "child_center": "yes", "member_fee": 0, "date_registered": "2020-06-28", "twg": [ 1 ], }, "incidenttwg2": null, "incidenttwg1": { "id": 5, "name": "dddfd", "sex": null, "nat": null, "parent": null, "dad_name": null, "mom_name": null, "dad_age": null, "mom_age": null, "dad_nat": null, "incident": 1, }, "incidenttwg4": null, "incidenttwg3": null, "incidenttwg5": null }, ] I'm trying to compare if partner__twg == 1 it will show incidenttwg1 Or if partner__twg == 2 it will show incidenttwg2. Here My Code @api_view(['GET']) @renderer_classes((IncidentRender,)) def my_view(request): # twg = Incident.objects.filter(partner__twg=request.GET['twg']) incidents = Incident.objects.filter( # interview_date__range=( # request.GET['startdate'], request.GET['enddate']), partner__twg=request.GET['twg'] ) if(request.GET['twg'] == 1): content = [ { 'interviewer': incident.interviewer, 'interview_date': incident.interview_date, 'partner': incident.partner.name_kh, 'Q1.kid\'sname': incident.incidenttwg1.name, } for incident in incidents ] return Response(content) if(request.GET['twg'] == 2): content = [ { 'interviewer': incident.interviewer, 'interview_date': incident.interview_date, 'partner': incident.partner.name_kh, 'Q1.Kid\'sname': incident.incidenttwg2.name, } for incident in incidents ] return Response(content) return Response('Nothings!!') My current code is working, but its seem a bit ugly not clean. i wonder if there's a way that i can archieve it by QuerySet or somethings better than this. Thanks in advance :) -
Event Participation Sum Calculation in Django
I have a bunch of events. Each Event occurs over a period of time, with a start and end datetime captured in the event_dates DateTimeRangeField. Each Event has a number of participants. Here is the (very simplified) model definition: class Event(models.Model): name = models.CharField(max_length=10) event_dates = models.DateTimeRangeField(_("Event Dates"), blank=True, null=True) participants = models.IntegerField() It is important that, regardless of how many Events occur at one time, the number of participants remains below a certain user-defined level. I also want to be able to create a step chart showing the number of participants at any given time. Approach: Given a period of time (0800 to 2000 on May 27th in this example), I want to get the instantaneous participant sum at each time change (the start or end of an event), as well as the instantaneous sum at the beginning and end of the provided time period. Visual explanation of what I seek to accomplish In the image, you can get a visual idea of what I am aiming for. Each colored horizontal block is an event, with the number of participant indicated as an integer value. Whenever an event starts or ends, I want the total sum of participants at … -
Django 3.0: Unable to use password_reset but able to send emails from views
I am unable to use django's default password_reset. It isn't sending emails. I have tried many many configurations but nothing is working. I know my settings are right, As I am fully able to send emails in views.py Following Code is absolutely working. from django.core.mail import send_mail def contact_us(request): contact_form = ContactForm(request.POST or None) context = { "form": contact_form, } if contact_form.is_valid(): print(contact_form.cleaned_data) send_mail( 'Contacted By: {}'.format(contact_form.cleaned_data.get('name')), contact_form.cleaned_data.get('comment'), 'mydjangoemail@gmail.com', ['customerfeedback@gmail.com',], fail_silently=False, ) if request.is_ajax(): return JsonResponse({"message": "Thanks"}) if contact_form.errors: errors = contact_form.errors.as_json() if request.is_ajax(): return HttpResponse(errors, status=400, content_type='application/json') return redirect("App:home") I am using django's default password_reset by using following in project's urls.py, I am accessing all templates like password_reset at http://127.0.0.1:8000/accounts/password_reset/: path('accounts/', include('django.contrib.auth.urls')), templates are working fine too: my settings.py has following email config: EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mydjangoemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 25 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'mydjangoemail@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' MANAGERS = ( ('Abc', "mydjangoemail@gmail.com"), ) ADMINS = MANAGERS And 'django.contrib.auth' is also in INSTALLED_APPS. -
ValueError: Cannot assign "'x'": "y" must be a "z" instance
Trying to loop through some order data in a CSV and import it into models I created in Django. Some of the orders are zero'd out with nothing in the field. Attempting to import the data so the customer number defined in the Customer object in models is a ForeignKeyField pulled into the Order object in models. I get the following error right now: ValueError: Cannot assign "'customer_number'": "Order.customer_number" must be a "Customer" instance. Here is my loop: for row in reader: # print(row) print('original date' ,row[4]) print('total ammount', row[26]) date_string = row[4] if not row[26] == '': total_amount_decimal = int(float(row[26])) else: total_amount_decimal = 0 print("date_string =", date_string) print("type of date_string =", type(date_string)) date_object = datetime.strptime(date_string, "%m/%d/%Y") print("date_object =", date_object) print("type of date_object =", type(date_object)) p, created = Customer.objects.get_or_create(customer_number=row[2]) c, created = Order.objects.get_or_create( customer_number=row[2], order_number=row[1], order_date=date_object, total_amount=total_amount_decimal, ) Here are my models: class Customer(models.Model): customer_number = models.CharField(max_length=255, null=True, blank=True) name = models.CharField(max_length=255, null=True, blank=True) phone = models.CharField(max_length=255, null=True, blank=True) email = models.EmailField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Order(models.Model): customer_number = models.ForeignKey('Customer', on_delete=models.CASCADE) order_number = models.CharField(max_length=255, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) order_date = models.DateField(null=True, blank=True) total_amount = models.DecimalField(max_digits=16, decimal_places=8) I tried to search this issue and … -
django change the default query set based on the requesting user
I have a system with multiple organizations logging in and interacting with us and our partners. I have a table that keeps track of what users have access to what organizations. I would like for customers to only see their own records. I am doing this inside the views and whatnot. However, I find myself often trying to code around this. It makes it so I can't use some of the generic views as easily. Forms are a pain because when a field is pulled in as a dropdown option if shows all the records. In reality, I never want to receive all the records back. I would much rather the query check the access table and always just return what a user has access to. I have seem some mentions about using a middleware change but I would really like to keep this within the manager and query set. It seems like that is what they are there for. However, I can't seem to find a way to reference request.user without passing it in (this causes other changes and messes with all my forms....). Is way to do this within the manager and queryset? -
How to exclude pending migrations on Django 3.1
I'm creating my first app in Django (a blog) and I wanted to add a date field. I read in the documentation that the way to go was using models.DateTimeField(). Since I already had populate the database I added the null=True option. So in my models.py it was like this: date = models.DateTimeField(null=True,auto_now=False, auto_now_add=False, editable=True) I migrate it and it was okey. I went to the admin page and changed the date values for the existing tuples. Then I went to my models.py file and altered the date field: date = models.DateTimeField(auto_now=False, auto_now_add=False,default=models.DateTimeField()) I added the default because when I was running makemigrations, a prompt would show up saying I had to put a default value or add a null=True and my noob head though that what I did made sense. When I ran makemigrations I got no errors but when I tried to actually migrate this appeared: Operations to perform: Apply all migrations: admin, auth, blogApp, contenttypes, sessions Running migrations: Applying blogApp.0007_auto_20200808_0006...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/min/Documentos/Programação/Python/myDjangoBlog/VirtualEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/min/Documentos/Programação/Python/myDjangoBlog/VirtualEnv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/min/Documentos/Programação/Python/myDjangoBlog/VirtualEnv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in … -
How to get correct values from MultipleChoiceField with ajax and vanilla JavaScript in Django
forms.py class MyForm(forms.ModelForm): AVAILABLE_OPTIONS = [ ('a', 'a'), ('b', 'b'), ('c', 'c'), ] options = forms.MultipleChoiceField( ...... widget=forms.CheckboxSelectMultiple(), choices=AVAILABLE_OPTIONS, ) JavaScript .... var my_array = [] var options = document.querySelectorAll('input[name=options]:checked'); .... What I want: <QueryDict: {'csrfmiddlewaretoken': ....., 'options': ['a', 'b', 'c', ....], ......}> What I get when printing request.POST <QueryDict: {........, 'options': ['[object NodeList]'], .....}> And when I loop through options, and my_array.push(options[i].value), I get the following, and the form doesn't work because it's 1 value, not multiple. <QueryDict: {........, 'options': ['a, b, c'], .....}> What am I doing wrong?? Thanks! -
Django - makemigrations- app could not be found
I'm new to Django. I've seen variations of this questions and tried all the answers but nothing works. When trying to apply makemigrations on my app "products" it returns: App 'products' could not be found. Is it in INSTALLED_APPS? I tried makemigrations using these variations: python manage.py makemigrations python manage.py makemigrations products ./manage.py makemigrations products same result. I have 'products' on my INSTALLED_APPS list, I have the migrations folder under products and I have init.py file under products and migrations. 'products' also won't show on the admin interface even after importing it to to admin.py ps: using django 2.0.7 because the tutorial I'm following asked to. -
What am I doing wrong patching a function across all django tests in a class?
I'm trying to run several tests but they all need to patch a function that gets ran from a signal. This is what I have: class TestAppNameModel(TestCase): @patch('backend.models.some_function_that_gets_called') def test_creating_app_name(self): app_name = AppName.objects.create( label='foo', number='1234' ) self.assertEqual('foo', app_name.label) My problem is that this patching method can get very extensive and repetitive across all of my test cases. So I'm trying to change it into something like this: class TestAppNameModel(TestCase): def setUp(self) -> None: self.patcher = patch('backend.models.some_function_that_gets_called') self.mocked_signal_function = self.patcher.start() def tearDown(self) -> None: self.patcher = self.patcher.stop() # @patch('backend.models.some_function_that_gets_called') def test_creating_app_name(self): app_name = AppName.objects.create( label='foo', number='1234' ) self.assertEqual('foo', app_name.label) But my problem is this doesn't seem to be actually patching the function. some_function_that_gets_called still seems to get called as it would naturally instead of the patched function. What am I doing wrong? Just for clarification, the create method ends up triggering a signal that calls some_function_that_gets_called -
Field 'id' expected a number but got <property object at 0x03F53528>. -
I am building a registration app that needs to register people based on the specific User model instance. My urls are based on the slugs of my users and based on those values people can register at a specific user. For example, people can register at Apples or at Bananas. The form that is posted contains the specific user.id which is passed to the People Model alongside the filled in form fields. Now I am getting the following error which I can't get my head around: Field 'id' expected a number but got <property object at 0x03CC54B0>. My urls: app_name = 'register' urlpatterns = [ path('<slug>/contact/', ContactView.as_view(), name='contact'), path('<slug>/thanks/', ThanksView.as_view(), name='thanks'), ] My models: class Bedrijf(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) bedrijfsnaam = models.CharField(max_length=80, null=True) slug = models.SlugField(max_length=30) class Bezoeker(models.Model): bedrijf = models.ForeignKey(Bedrijf, on_delete=models.CASCADE) voornaam = models.CharField(max_length=30) achternaam = models.CharField(max_length=50) My Views class ContactView(CreateView): template_name = 'register/contact.html' form_class = BezoekerForm def get_success_url(self): return reverse('bedankt', kwargs={'slug': Bedrijf.slug}) def get(self, request, *args, **kwargs): form = BezoekerForm slug = get_object_or_404(Bedrijf, slug=Bedrijf.slug) context = {'form': form, 'slug': slug} return render(self, self.template_name, context) def post(self, request, *args, **kwargs): bedrijf = Bedrijf.objects.get(pk=Bedrijf.pk) if request.method == 'POST': form = self.form_class(request.POST) if form.is_valid(): new_register = form.save(commit=False) new_register.bedrijf … -
Quiero saber el campo que es nulo
Yo obtengo un registro de la base trabajando con orm django. Es una tabla que tiene varias columnas y solo algunas tienen datos y el resto es nulo. Como obtengo la columna o el campo que es nulo, es decir, quiero actualizar la primera columna nula. -
Why do I get error ERR_CERT_COMMON_NAME_INVALID when adding an external video into Django?
I have a Django view in which I include this code: <video width="100%" height="400" controls> <source src="{{ video }}" type="video/mp4"> </video> The {{ video }} I send is https://207.244.254.64/1596830935_5213411034573.mp4 . When the view loads, the video player is there, but the video doesn't load, and in the console the error ERR_CERT_COMMON_NAME_INVALID appears. My project currently accepts all in ALLOWED_HOSTS, so it can't be that. Do you know why could this issue appear? I found no information that was relevant to my problem. -
Django Static Image Showing then Not Showing, Views Share Base Html File Where Static Logo image is
My logo which is in my djangoprojectdir/static/media/ folder is showing on my homepage but in none of my other views. I dont know why it doesnt show up on other pages it shares the same base.html file for the navigation bar and header. Currently hosted website in production on digital ocean, nginx, gunicorn. I am just trying to serve static files in production debug off for small project with no database. I have already collected static. The image only works on my IndexView. My other static image files relating to my objects seem to be rendering fine. I have been exhaustively trying to figure this out. The Image code out of the base.html that is problematic is: <a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a> I have tried mapping with {{ MEDIA_URL }}/Dirt logo3.png and {{ STATIC_URL }} to no avail, Hardcoded would be fine if it worked. from base.html #bootstrap stuff here# {% load static from staticfiles %} <a class="navbar-brand" href="{% url 'maps:index' %}"><img src="static/media/Dirt logo3.png" hieght="5" class="img-fluid" alt="Responsive image"> </a> {% block body %} {% endblock %} from settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'mysite', 'maps', … -
How can I replicate this beautiful dialogue box?
The field is: amount = models.DecimalField(max_digits=11, decimal_places=2) When I enter an invalid value like 1.111 for example, it gives this nice dialogue box. I tried to replicate it for additional criteria first by adding custom validation, (because I thought it was is_valid() that was doing it) but turns out that error needs HttpRedirect and manual rendering. Then I realized it's probably a database constraint so I added a CheckConstraint, but that needs to be handled manually as well. Is it possible? -
Django post request is returning querydict instead of object id for model form
I have the modelform class CollectionForm(forms.ModelForm): Medicine_Name = forms.ModelChoiceField(queryset=Medicine.objects.all()) class Meta: model = Medicine fields = ['Number_Of_Boxes', 'Last_Collected'] def __init__(self, user = None, *args, **kwargs): super().__init__(*args, **kwargs) if user: self.fields['Medicine_Name'].queryset=Medicine.objects.filter(User_Associated=user) And the view to handle the form: def update(request, *args, **kwargs): if request.method == 'POST': qd = request.POST['chosen_medicine'] instance = Medicine.objects.get(id=qd) form = CollectionForm(request.POST, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() else: form = CollectionForm() context = {'form': form, 'meds': Medicine.objects.filter(User_Associated=request.user), } return render(request, 'tracker/medicine_collection.html', context ) The template for the form is here: <form method="POST" action = ''> {% csrf_token %} <label for="Medicine_Name">Medicine Name</label> <select class = "form-control" id = "Medicine_Name" name = "chosen_medicine"> {% for med in meds %} <option value = '{{med.auto_id}}'>{{ med.Medicine_Name }}</option> {% endfor %} </select> {{form.Number_Of_Boxes }} {{form.Last_Collected }} <button class="btn btn-outline-info" type="submit">Create</button> </form> I am trying to get the id of the Medicine_Name which the user chooses from the dropdown list. To do this I have a POST request in my view to get the id. However, when submitting my form I get the error: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['rrkPEpuZqxWQ9TS4lLMRDwAQ7xZAOUVZl8iHLVfZJ8gEfKundDMvDh9oWp42l1Jf'], 'chosen_medicine': ['1'], 'Number_Of_Boxes': ['3'], 'Last_Collected': ['03/16/2020']}>. How can I make sure the POST request actually gets the ID, … -
How to solve Reverse for 'all_worker' with keyword arguments '{'Slug': 'elctric'}' not found. 1 pattern(s) tried: ['jobs/(?P<slug>[-a-zA-Z0-9_]+)$']
i have two models(category&Worker)and i need to show all category at home page , when press in any category i get all workers that belong to this category models.py from django.db import models from django.utils.text import slugify from django.urls import reverse class Category(models.Model): name = models.CharField( max_length=40) img = models.ImageField(upload_to='category_img') Slug = models.SlugField(blank = True , null = True) def __str__(self): return self.name def save(self , *args ,**kwargs ): self.Slug = slugify(self.name) super(Category , self).save( *args , **kwargs) def get_absolute_url(self): return reverse('jobs:all_worker', kwargs={'Slug': self.Slug}) class Worker(models.Model): job = models.ForeignKey('Category', on_delete=models.CASCADE) name = models.CharField(max_length=50) image = models.ImageField(upload_to='worker_img') place = models.CharField(max_length=50) Slug = models.SlugField(blank = True , null = True) def __str__(self): return self.name def save(self , *args ,**kwargs ): self.Slug = slugify(self.job) super(Worker , self).save( *args , **kwargs) views.py def all_worker(request,slug): workers = get_object_or_404(Worker,slug=slug) return render(request, 'jobCategory/worker_list.html', {'workers':workers}) urls.py urlpatterns = [ path('', views.category, name='category'), path('<slug:slug>', views.all_worker, name='all_worker'), ] -
AWS s3 & Django & Nginx
I did a configuration for my s3 bucket, Django media files, and Nginx server. It worked, but after a few hours, it doesn't work... I don't know is it matter, but I created s3 bucket policy for "getObject" action with condition that request must have User-Agent header with secret string, for example: curl -I some.url -H "User-Agent: dog" My Django AWS Configuration (django_storages): AWS_ACCESS_KEY_ID = 'my_access' AWS_SECRET_ACCESS_KEY = 'my_private' AWS_STORAGE_BUCKET_NAME = 'diasmart-media-static' S3_REGION = 'eu-north-1' AWS_S3_CUSTOM_DOMAIN = f'https://s3-{S3_REGION}.amazonaws.com/{AWS_STORAGE_BUCKET_NAME}' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # Static and media STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/media/' My Nginx config location /media { resolver 8.8.8.8; limit_except GET { deny all; } set $aws_bucket "diasmart-media-static"; set $aws_endpoint "s3-eu-north-1.amazonaws.com"; set $aws_custom_secret "for_example_dog"; proxy_set_header User-Agent $aws_custom_secret; rewrite ^/media/(.*)$ /$aws_bucket/$1 break; proxy_buffering off; proxy_pass https://$aws_endpoint; } When I upload photos with the Django admin page, there are no errors, but images aren't shown. And my s3 bucket is empty... Please help me 🙏 -
How do I associate multiple hierarchical data categories to one model in Django?
I'm creating a database of books and their subjects. So far I've used django-mptt to create a subject hierarchy ie: Fiction: ---- SciFi ---- Romance Non-Fiction: ---- Science -------- Chemistry ------------ Molecular Chemistry -------- Physics ---- History I cannot figure out how to make it possible for a Book to have multiple subjects associated to it. For example a Book may be about the history of molecular chemistry. How should I go about this? My code so far: models.py: from django.db import models from mptt.models import MPTTModel, TreeForeignKey from people.models import Person class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField('people.Person') subject = TreeForeignKey('Subject', null=True, blank=True, on_delete=models.PROTECT) class Subject(MPTTModel): subject_type = models.CharField(max_length=30, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.PROTECT) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['subject_type'] class Meta: unique_together = ('parent', 'slug',) verbose_name_plural = 'Subjects' admin.py: from django.contrib import admin # Register your models here. from people.models import Person, Recommender from books.models import Book, Subject from mptt.admin import MPTTModelAdmin admin.site.register(Person) admin.site.register(Recommender) admin.site.register(Book) admin.site.register(Subject, MPTTModelAdmin) -
CSS File not styling the text
I have been recently developing a website on Django and would like to use CSS for some basic stuff. As a test, i made a static dir, and all. And applied my css like this h1 { color:blue }. This works, but when i want to change the color to something like red, and I refresh the page, it doesnt work at all (It stays Blue). Any ideas on how to fix this? I loaded static like this on the HTML <link rel="stylesheet" type="text/css" href="{% static 'WEBApp/style.css' %}">