Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sharing Pika Connection Singleton Object between gunicron workers on django application
Hi I am trying to connect to email queue from django application. I have created an EmailPublisher which will be a singleton object which extends RabbitMQProducer object which has actual code of connecting to rabbitmq service. Now I want to share the rabbitmq connection between gunicorn workers how can I do this? Please help. class RabbitMQProducer(ABC): def __init__(self): self.credentials = pika.PlainCredentials( settings.RABBITMQCONFIG['username'], settings.RABBITMQCONFIG['password'], ) self.parameters = pika.ConnectionParameters( host=settings.RABBITMQCONFIG['host'], port=settings.RABBITMQCONFIG['port'], virtual_host=settings.RABBITMQCONFIG['virtual_host'], credentials=self.credentials, heartbeat=600, blocked_connection_timeout=300, client_properties={ 'connection_name': self.get_connection_name(), } ) self.connection = None self.channels = {} self.connect() def connect(self): if not self.connection or self.connection.is_closed: self.connection = BlockingConnection(self.parameters) self.close_channels() self.declare_channels() def declare_channels(self): for i in range(self.get_channel_count()): self.channels[i] = self.assign_channel() def send(self, message): try: self.connect() self.thread_safe_publish(message) except Exception as e: Log.e(f"Failed to send message to RabbitMQ: {e}") def assign_channel(self): if not self.connection or self.connection.is_closed: self.connect() return None channel = self.connection.channel(channel_number=None) channel.exchange_declare( exchange=self.get_rabbitmq_exchange_name(), exchange_type=self.get_rabbitmq_exchange_type(), durable=True, ) return channel def thread_safe_publish(self, message): try: random_channel_number = CommonUtils.get_random_number(0, self.get_channel_count() - 1) channel = self.channels[random_channel_number] if not channel or channel.is_closed: channel = self.assign_channel() if channel: self.channels[random_channel_number] = channel self.channels[random_channel_number].basic_publish( exchange=self.get_rabbitmq_exchange_name(), routing_key=self.get_rabbitmq_routing_key(), body=json.dumps(message), properties=pika.BasicProperties( delivery_mode=2, # make message persistent ) ) event_key = self.get_event_key() self.process_data_events(event_key) except Exception as e: Log.e(f"Failed to send message to RabbitMQ: {e}") def process_data_events(self, event_key): try: … -
Django Rest Framework UpdateAPIView is saying a field is required but the field is there
I have this model that represents an Ad: class BigAd(models.Model): DA = 'DA' WE = 'WE' MO = 'MO' INTERVAL = [ (DA, 'Day'), (WE, 'Week'), (MO, 'Month'), ] IM = 'IM' VI = 'VI' TYPES = [ (IM, 'Image'), (VI, 'Video'), ] title = models.CharField(max_length=50, default=None) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) audience = models.ForeignKey(AdAudience, on_delete=models.CASCADE, default=None) active = models.BooleanField(default=False) body = models.TextField(max_length=255, null=True, blank=True) ad_image = models.FileField(upload_to=bigad_directory_path, null=True, blank=True) ad_type = models.CharField(max_length=2, choices=TYPES, default=IM) big_image = models.FileField(upload_to=bigad_directory_path, null=True, blank=True) video = models.FileField(upload_to=bigad_video_path, null=True, blank=True) link = models.URLField(max_length=256, null=True, blank=True) budget_interval = models.CharField(max_length=2, choices=INTERVAL, default=DA) budget = models.DecimalField(max_digits=30, decimal_places=0, default=200) lowest_bid = models.DecimalField(max_digits=20, decimal_places=2) highest_bid = models.DecimalField(max_digits=20, decimal_places=2) includes_products = models.BooleanField(default=False) product_list = ArrayField(models.IntegerField(), null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, default=None) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "big ad" verbose_name_plural = "big ads" db_table = "big_ads" ordering = ["created_at"] def __str__(self): return self.title def get_absolute_url(self): return self.slug and this serializer for serializing the data: class BigAdSerializer(serializers.ModelSerializer): campaign = ShortCampaignSerializer() class Meta: model = BigAd fields = [ "id", "title", "campaign", "audience", "ad_image", "ad_type", "big_image", "active", "body", "video", "link", "budget_interval", "budget", "lowest_bid", "highest_bid", "user", "includes_products", "product_list", "active", "created_at", "updated_at", ] and this view for … -
How to store next/return URL in Django FormView
I have a Django FormView that has two entry points from different edit buttons on different URLs. Once the user is done editing, I would like to return then to the URL they were originally on. To do this, I need to know the URL the user originally came from. So far, I have done the following: include a next parameter in the call to the FormView, then add that next parameter to the form action so that when the form is posted I can retrieve it e.g. <form method="post" action="http://127.0.0.1:8000/main/2/item/update?next=read_view"> ... </form> However, on the form post I cannot seem to get hold of the action to get the next parameter. Is there a standard way to handle this in Django? My approach feels a bit clunky. -
Not able to migrate, Foreignkey in models is causing the issue
so I have the two following models that I'm trying to migrate. class Organisation(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=64,choices=STATUS,default='active') logo_file_path = models.CharField(max_length=2048) and class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=64,choices=STATUS,default='active') org_id = models.ForeignKey(Organisation(),to_field=id, on_delete=models.CASCADE) I need Team.org_id linked to Organisation.id, so I'm trying to use it as a foreign key. but while trying to make migration it is giving me the following system error: SystemCheckError: System check identified some issues: ERRORS: db_app.Team.org_id: (fields.E312) The to_field 'db_app.Team.id' doesn't exist on the related model 'db_app.Organisation'. Note: db_app is my django app name. I guess the to_field argument in the foreign key is causing the issue. I'm not sure though. I have tried it on different models in a different project the error remains the same. -
How do I correctly add one model to another in Flutter?
I'm really confused on how do I add director model to my show model. I'm writing Android application in Flutter, that uses local Django Rest API. This is Director Model in Django class Director(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) country = models.CharField(max_length=20) image = models.ImageField(null=True, blank=True, upload_to="images/") This is Shows Model in Django class Show(models.Model): name = models.CharField(max_length=50) annotation = models.TextField(max_length=1000) language = models.CharField(max_length=20, null=True) image = models.ImageField(null=True, blank=True, upload_to="images/") director = models.ForeignKey(Director, on_delete=models.CASCADE, null=True) This is Director Model in Flutter import 'package:flutter/widgets.dart'; class DirectorModel with ChangeNotifier { final int id; final String name; final String surname; final String image; DirectorModel({required this.id, required this.name, required this.surname, required this.image}); factory DirectorModel.fromJson(dynamic json) { return DirectorModel( id: json['id'], name: json['name'] as String, surname: json['surname'] as String, image: json['image'] as String, ); } static List<DirectorModel> directorFromSnapshot(List snapshot) { return snapshot.map((data) { return DirectorModel.fromJson(data); }).toList(); } } This is Shows model in Flutter import 'package:flutter/widgets.dart'; import 'package:kulises_app/models/directors.dart'; class ShowsModel with ChangeNotifier { int id; String name; String annotation; String language; DirectorModel director; String image; ShowsModel( {required this.id, required this.name, required this.annotation, required this.language, required this.director, required this.image}); factory ShowsModel.fromJson(dynamic json) { return ShowsModel( id: json['id'], director: DirectorModel.fromJson(json['director']), name: json['name'] as String, annotation: json['annotation'] … -
How to add more param to Serialization Model for using at to_presentation
Here is my so class DataFieldSerializer(serializers.ModelSerializer): class Meta: model = DataField fields = ["field", "topic", "category", "group", "alias", "units"] def __init__(self, *args, **kwargs): self.extra_param = kwargs.pop('extra_param', None) super().__init__(*args, **kwargs) def to_representation(self, instance): data = super().to_representation(instance) print("Extra Param:", self.extra_param) This is how I call the DataFieldSerializer result_data = DataFieldWithUnitsSerializer(data_fields, many=True, extra_param='example').data When I run the code I got this result Extra Param:None I guess it is not the right way to add more param into a model serializer. To sum up, I want to find away to pass an extra param to the Serializer Model -
Why is a shallow copy used with self.cart in this Django Python code?
in this python code, def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item Is the Python copy function a shallow copy? Why is it shallow copying self.cart instead of just using self.cart directly? using self.cart directly instead of using variable cart. -
Django allauth telegram provider not working
Has anyone successfully implemented using allauth's telegram provider? I've followed the documentation and everything but it still does nothing. -
Experience auto increment according to DOJ
I have DOJ (Date of Joining) in my Django models and also i have Experience field in my models so according to my DOJ my experience should change daily automatically. This should be done in Django Could anyone please help me on this Thanks in advance -
One to many relationship query in Django ORM, Where I want to query on One table and want to get output with many table data as a list
Here is my model: from django.db import models from django.db.models.expressions import F class Publication(models.Model): name = models.CharField('name of publication', max_length=1024, null=True, blank=True) def __str__(self): return f'{self.name}' class Meta: verbose_name = "Publication" verbose_name_plural = "Publications" class Book(models.Model): name = models.CharField('name of book', max_length=1024, null=True, blank=True) publication = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.name}//{self.publication.name}' class Meta: verbose_name = "Book" verbose_name_plural = "Book" I want outcome json as single publication with list of book (Please show me using Django ORM query and Django Serializer OR using DRF): Output JSON like below: [ { "id": 1, "name": "publication 001", "book": [ { "id": 1, "name": "Book 001" }, { "id": 2, "name": "Book 002" } ] }, { "id": 2, "name": "publication 002", "book": [ { "id": 3, "name": "Book 003" }, { "id": 4, "name": "Book 004" } ] } ] I tried it through several way but unable to solve it using django orm query. I've done it through raw query. But I wantto implement it through Django ORM Query. SO please help me. TIA -
Filtering the products by price in django
Here im trying to do filtering the products by price View def Shop(request): min_price = Product.objects.all().aggregate(Min('price')) max_price = Product.objects.all().aggregate(Max('price')) FilterPrice = request.GET.get('FilterPrice') if FilterPrice: Int_FilterPrice = int(FilterPrice) product = Product.objects.filter(price__lte = Int_FilterPrice) print(product) else: product = Product.objects.all() Here I got the value in backend <QuerySet [<Product: OnePlus Nord Buds 2 True Wireless in Ear Earbuds with Mic, Upto 25dB ANC>]> by filtering the product by price range HTML here in this HTML code if I click the filter button I got all the products it is not filtered by price <div class="product-widget mb-30"> <h5 class="pt-title">Filter By Price</h5> <div class="price__slider mt-30"> <input type="range" class="multi-range success" style="color:red;" value="{{FilterPrice}}" min="{{min_price.price__min}}" max="{{max_price.price__max}}" id="rangeInput" oninput="maxPrice.value=this.value" width="400px;" /> <div> <form action="" class="s-form mt-20" method="get"> <b>₹</b><input type="number" id="maxPrice" readonly="" name="FilterPrice" onkeyup="rangeInput.value=this.value" value={{FilterPrice}}{{minMaxPrice.price__min}}> <button type="submit" id="priceFilterBtn" class="tp-btn-square-lg">Filter</button> </form> </div> </div> </div> The output I expect: If I click the filter button I want to get the filtered product by price range... -
Extending 'bootstrap/base.html' works fine in Flask but not in Django, how to make it work?
{% extends 'bootstrap/base.html' %} this line works just fine in flask but doesnt work in django how can i make it work this is the head of the page fddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd -
Django ModelForm Validation not validating
Can someone check what i'm omitting here? The Validation error is not showing up even when it should. It's just returning successful when it should've showed a validation error. When I run my server and insert a title less than 5 charcters, it still returns successful instead of raising a Validating error. views.py; def form_view(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return HttpResponse("successful") else: return render(request, "product_create.html", {'form': form}) else: form = ProductForm(None) return render(request, 'product_create.html', {'form': form}) models.py; from django.db import models # Create your models here. class Product(models.Model): title = models.CharField(max_length=120) description = models.CharField(blank=True, null=True, max_length=250) price = models.FloatField() forms.py; from django import forms from .views import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = [ 'title', 'description', 'price', ] def cleaned_title(self): title = self.cleaned_data.get('title') if len(title) < 5: raise forms.ValidationError("This is not a valid title") return self.cleaned_data template; product_create.html: {% block content %} <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="save"> </form>`enter code here` {% endblock %} -
How do I create a tally card for my items in my warehouse management system
I am building a warehouse management system and I want to design a tally card for each item in stock where store officers can receive and issue items in their warehouse and keep the transaction for each item. I want it to update the item balance in stock anytime the user receives and issued like a real-world tally card. I want it to look like this let's assume this is transactions made on item1. | Date | Description |Receive | Issue | Balance | | 1-2-2023 | site1 | | 76 | 235 | | 3-2-2023 | store1 | 50 | | 285 | On the Item list page, I want the user to click on a receive button and it will direct him to a form to enter the quantity he has received and the description and it will automatically update the balance and save that transaction against the item and the same applies to the issue. And when the user clicked on the item, it will display all the transactions made on that item like the table above So far, I have this in my model to save items and their info in the warehouse. Model class Item(models.Model): … -
How can I display the result of steganalysis on my website using Django and HTML?
I am currently developing a website for steganalysis. All codes and functions can be used appropriately, however I could not make the result appear on the page of my website. In this website, I should have produced the result of steganalysis onto the same pagee in its own section but it did not happen. I have intergrated the index.html and views.py according to the mentioned code below. return render(request, 'index.html') For each tasks in views.py, I have included above code, however nothing changed. The result still does not display on the web page. The concept of the website is similar to cyberchef where it does not store any of the analysis tasks. It only perform tasks selected by user and produces the results. -
How do I insert data into Django models with foreign key tables and OneToOne fields?
"Hello everyone, I hope you're doing well. I'm currently facing an issue with inserting data in models with foreign key table and OneToOne field. I've tried inserting data in, but I haven't been able to find a success. It would be great if someone could help me out or provide some guidance on how to resolve this. Any insights or suggestions would be greatly appreciated. Thank you in advance for your time and assistance!" MODELS: class Department(models.Model): department = models.CharField(max_length=100) def __str__(self) -> str: return self.department class Meta: ordering = ['department'] class StudentID(models.Model): student_id = models.CharField(max_length=100) def __str__(self) -> str: return self.student_id class Student(models.Model): department = models.ForeignKey(Department, related_name='depart', on_delete=models.CASCADE) student_id = models.OneToOneField(StudentID, related_name='studentId', on_delete=models.CASCADE) student_name = models.CharField(max_length=100) student_email = models.EmailField(max_length=100) student_age = models.IntegerField(default=18) student_address = models.TextField() def __str__(self) -> str: return self.student_name class Meta: ordering = ['student_name'] verbose_name = 'student' class Subject(models.Model): subject_name = models.CharField(max_length=100) def __str__(self) -> str: return self.subject_name class SubjectMark(models.Model): student = models.ForeignKey(Student, related_name='studentmark', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks = models.IntegerField() def __str__(self) -> str: return f' {self.student.student_name} {self.subject.subject_name} ' class Meta: unique_together = ['student' , 'subject'] I've tried this view but I got only errors. Views def create_student(request): if request.method == "POST": data = request.POST … -
How do I modify a Django filter to search for a specific word and variations with a dash using regex or any other option?
I have this filter filters = Q(my_text__icontains=typed_word) I need to modify it in a way that would works like this: if the typed_word is "ABCD", it should return any ABC that could have a "-" (dash) at any position in the word, examples: would return the "ABCD" itself, but also "A-BCD" and "AB-CD" and "ABC-D" btw any word in the database only have one dash, none of then would have more then one I tried some patterns using something like this my_text__iregex=pattern But no luck -
Django Filter through Form input not working
After clicking on the Filter button it shouldn't return the property with 20000 rent. But that is not happening. Anyone can explain why? I have attached the template, view, and form code below. Template code: <div class="container-fluid"> <div class="row"> <div class="col-sm-3"> <form action="/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Filter"> </form> </div> <div class="col-sm-9 row" id="filtered-product"> {% for l in listings %} <div class="card w-25 float-left p-2"> <img src="{{ l.image.url }}" class="img-fluid" alt=""> <h3 class="card-title text-center">{{ l.type }}</h3> <h5 class="card-subtitle text-center">Rent: {{ l.rent }}</h5> <a href="/listings/{{ l.id }}/" class="btn btn-primary"> View details </a> </div> {% endfor %} </div> </div> View: def listing_list(request): form = FilterForm() if form.is_valid(): min_price = form.cleaned_data["minrent"] max_price = form.cleaned_data["maxrent"] listings = listings.filter(rent__gte=min_price) listings = listings.filter(rent__lte=max_price) else: listings = Listing.objects.all().select_related('user') context = { "listings": listings, "form": form } return render(request, "listings/listings.html", context) Form: class FilterForm(forms.Form): minrent = forms.IntegerField() maxrent = forms.IntegerField() -
How to implement authentication in postgresql based on Django?
Сould you explain or explain ? How to properly implement authorization to the django database (without migrations). That is, there is a database, it has a table in which the login and password are stored. We can simply go through authorization when accessing it. How to make it so that when a user registers, the login and password are entered directly into this table (where the login and password are stored)? An account is also created so that you can log into the database itself under this account. Initially, we have a server account connected, and when someone does something, we will see that it is the server account that does it, not the user -
Django template render a nested dict with tuples
Here's my dict = { '123': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, '456': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, '789': {'metric_1': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')], 'metric_2': [('url_1', 'caption_1'), ('url_2', 'caption_2'), ('url_3', 'caption_3'), ('url_4', 'caption_4')]}, } it basically is a dict of a dict of a list of tuples. what I'd like to render via Django template is: 123 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 456 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 789 metric_1 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 metric_2 url_1 url_2 url_3 url_4 caption_1 caption_2 caption_3 caption_4 but I'm not able to do so, here's my current Django template: <div class="grid grid-cols-2 gap-2 p-2"> {% for one_analysis_id, all_metrics in url_dict.items %} <table> <tr><p>Analysis ID: {{ one_analysis_id }}</p></tr> {% for metric_name, url_and_caption_tuple_list in all_metrics.items %} <tr><p>{{ metric_name }}</p></tr> <tr> {% for url_and_caption_tuple in url_and_caption_tuple_list %} <td><img width="350" height="300" src="{{ url_and_caption_tuple.0 }}"><div>{{ url_and_caption_tuple.1 }}</div></td> {% endfor %} … -
ValueError: libcublas.so.*[0-9] not found in the system path
I'm trying to import and use ultralytics library in my Django rest framework project, I use poetry as my dependency manager, I installed ultralytics using poetry add ultralytics and on trying to import the library in my code I recieve this error ValueError: libcublas.so.*[0-9] not found in the system path [my project and virtual environment paths] so how can I solve that? I tried searching and asking ChatGPT but I didn't reach any thing. -
How to find which site ids I have in Django Admin panel sites
I have deleted my previous site xxx.xxx.com and added a new site xx1.xxx.com. So then in the settings.py I have configured the site id to 2 and, yet it's not giving me the django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist. error. How can I check the exact site ids I have right now with the shell. Because my admin panel is not loading too. I am pretty new to django. So apologies if this is a very basic one to ask. I tried to change the site id from 1 to 2 -
Django: Problems with Fileresponse in production
Django: Fileresponse works fine in local but it doesnt in deployment In local i did this @login_required @permission_required('plataforma.ADMIN', raise_exception=True) def admin_descargar_planilla(request,plantilla_id): try: plantilla = Plantilla.objects.get(pk=plantilla_id) except: return render(request, "plataforma/error.html",{"tipo_error":"No se puede realizar esta accion ya que la plantilla ya no existe"}) buffer = util.crear_pdf(plantilla) return FileResponse(buffer, content_type='application/pdf', filename=(plantilla.eett.username+" ("+str(plantilla.fecha)+")")) The function crear_pdf returns an io.BytesIO(). When I try to use this views in production I recieve an Internal Server error (500) from the server instead of an django error. In the deployment I'm using openlitespeed. Also I try using an existing pdf instead of a buffer but its worst because i receive error 404 saying the url doesnt exist when it exist (this also works fine in local) -
Hwo to save multiple vlaues, which are reteived from frontend, in database in django Many to Many relationship?
While adding a book, I have to get data from frontend. I created a AddBookForm form. Book and Author have Many-to-Many relationship. From the frontend Form I get the names of the authors for the corresponding book as a list(from dynamic input field). Now the data is saved but is stored incorrectly. I know this is not the optimized way to save many to many relationship data. Please help me do this in an optimized way. models.py: class Book(models.Model): name = models.CharField(max_length=200, null=False, blank=False) description = models.TextField(null=True, blank=True) no_of_copies = models.IntegerField(default=1, null=True, blank=True) status = models.CharField(max_length=15, choices=[('Out of Stock', 'Out of Stock'), ('Available', 'Available')], default='Available') updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=100, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name class Genre(models.Model): name = models.CharField(max_length=50, null=True, blank=True) books = models.ManyToManyField(Book) def __str__(self): return self.name forms.py class AddBookForm(forms.ModelForm): authors = forms.CharField(max_length=255, required=False) genres = forms.CharField(max_length=255, required=False) class Meta: model = Book fields = '__all__' views.py def add_book(request): if request.method == 'POST': form = AddBookForm(request.POST) if form.is_valid(): book = form.save(commit=False) authors = request.POST.getlist('authors') book.save() for name in authors: author, created = Author.objects.get_or_create(name=name) author.books.add(book) return redirect("/") else: form = AddBookForm() context = {'form': form} … -
django-STATICFILES _DIRS not collecting
In my django project settings, I defined my static files like so: STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR + '/static' STATICFILES_DIRS = [ BASE_DIR +'/folder1', BASE_DIR + '/folder2', ] But collectstatic doesn't collect what is defined in "STATICFILES_DIRS". Even though it works locally, on the server it doesn't work. What am I doing wrong?