Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting model name in Django template
I am trying to do a search over many data models in Django to my site. Now I have code like this in views. class Search(ListView): template_name="search.html" context_object_name="result_serch_all" paginate_by = 10 def get_queryset(self): news = Articles.objects.filter(title__icontains=self.request.GET.get("q")) docs = Doc.objects.filter(name_doc__icontains=self.request.GET.get("q")) query_sets = list(chain(news, docs)) return query_sets def get_context_data(self, *args, **kwargs): paginator = Paginator(self.get_queryset(), 5) context = super().get_context_data(*args, **kwargs) context["q"] =f'q={self.request.GET.get("q")}&' print(context['result_serch_all']) return context In the template, I output like this {%for el in result_serch_all%} <div> {{el}} </div> {% endfor %} How can the output in the template be divided into blocks?So that in front of all found articles there is an inscription Found in the news section. Before the documents Found in the documents section`? I found this option. In my model im add def get_my_model_name(self): return self._meta.model_name and in the template I check {% if el.get_my_model_name == 'articles' %} Maybe there is some standard way in Django? -
coercing to Unicode: need string or buffer, FieldFile found
models.py def document_file_name(instance, filename): char_set = string.ascii_uppercase + string.digits dat = ''.join(random.sample(char_set*6, 12)) x = str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename) return 'documents/' + str(instance.created_by_id) + '/' + dat + '_' + re.sub(r'[^a-zA-Z0-9-_.]', r'_', filename); class UploadDocument(models.Model): document = models.FileField(upload_to=document_file_name, blank=True, null=True) other_doc = models.ForeignKey("doc.OtherDocuments") views.py def opportunity_document_add(request, opportunity_id): c = setup_context(request) other_documents = get_object_or_404(OtherDocuments, pk=opportunity_id) c['other_documents '] = other_documents c['other_documents_id'] = other_documents document = UploadDocument(other_doc=other_documents ) errors = {} if request.method == "POST": document.type = request.POST.get('type') if('document' in request.FILES): document.document = request.FILES['document'].read() file = document.document bucket = settings.AWS_STORAGE_BUCKET_NAME s3_client = boto3.client('s3') object_name = None with open(file, 'rb') as f: s3.upload_fileobj(f, bucket, file) document.save() Here i am getting the error "coercing to Unicode: need string or buffer, FieldFile found" -
Preference to choices based on a value of another model in Django?
I declared my choice as STATUS_CHOICES = ( ('A', 'available'), ('N', 'new'), ('R', 'reserved'), ('S', 'sold-out'), ) And i use this preferences in my Item model to show the current status of my item "status = models.CharField(choices=STATUS_CHOICES, max_length=1)" My problem here is that based on the "stock_no" category in my item model "stock_no = models.CharField(max_length=10)" The product status should automatically change from "Available to Reserved" or "Available to Sold-Out" can some one please help me with the logic for this issue Thank you. -
How to add some cutom code to post method in django rest framework
I am new to django rest framework. I was trying to build a API where I want to edit the POST method so that I could execute some actions and change some data from the POST body. I tried to follow some documentations and Guide from django rest framework website but didnt followed any. Please help me. Here I need to set some values for some fields that are going to be saved in the database. views.py from .models import LoginActivity from .serializers import LoginActivitySerializers class LoginActivity(viewsets.ModelViewSet): queryset = LoginActivity.objects.all() serializer_class = LoginActivitySerializers urls.py from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'LoginActivity', views.LoginActivity, basename='LoginActivity') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. appname='api' urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] serializers.py from rest_framework import serializers from .models import LoginActivity class LoginActivitySerializers(serializers.HyperlinkedModelSerializer): class Meta: model = LoginActivity fields = ('id', 'user_id', 'datetimelog', 'device_os', 'device_token', 'device_model') Please Help me. -
Create a related object in django
I have a model Inventory related to another model Product class Inventory(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) owner = models.ForeignKey(User, on_delete=models.CASCADE) whenever I create a "Product" I want to create a blank entry of "Inventory" as well. How can I do that? Views.py class ProductCreateAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = ProductSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): owner = request.user.pk d = request.data.copy() d['owner'] = owner serializer = ProductSerializer(data=d) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) Inventory.objects.create(product=serializer.data['id'], quantity = 0, owner = owner) <= Will this work? return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How to read data from an External Server and apply migrations on a local Db file in Django?
My situation is as follows: I have an external database with a read-only access from where I want to import my Data Models, which I did using: python manage.py inspectdb > models.py After I have handled all my exceptions after importing the models, when I try to migrate, it asks for permission to write to the external db to create extra tables for running the django project, like admin, auth, contenttypes, sessions How do I continue reading data from my external database for running my REST API while applying the required migrations for Auth and other important tables to another locally stored database? Following is the error I'm getting: LINE 1: CREATE TABLE "django_migrations" ("id" serial NOT NULL PRIMA... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema editor.create_model(self.Migration) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 307, in create_model self.execute(sql, params or None) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\base\schema.py", line 137, in execute cursor.execute(sql, params) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\prateek.jain\Anaconda3\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, … -
bulk-updating a bunch of many-to-many fields proves to be expensive, given my constraints (Django Rest Framework)
If you've noticed the discord roles system or the structure, each role has an unique position which determines which role is greater or lesser. From official documentation So, when a new role is created, if the role's position overlaps with an existing role's position, all the roles below the new role are shifted down (position value is changed by 1). Taking inspiration from this, I have developed my own roles system with django-rest-framework. Here's code from the backend: class Role(models.Model): """ Represents a Role object. Every parent can have it's own roles. Roles have their own: - Hex Color Code [Integer Representation] - Name [&] - Permissions. Role permissions for individual datasheets override global parent permissions. Parent IS NULL indicates the parent is for the whole parent. """ objects = models.Manager() id = models.BigAutoField(primary_key=True, db_index=True, editable=False, auto_created=True) name = models.CharField(max_length=512, db_index=True) hex_color_code = models.IntegerField(db_index=True) position = models.IntegerField(db_index=True) permissions = models.ManyToManyField(Permission) parent = models.ForeignKey('api_backend.DataSheet', on_delete=models.CASCADE, db_index=True) cluster = models.ForeignKey('api_backend.DataSheetsCluster', on_delete=models.CASCADE, db_index=True, editable=False) created_at = models.DateTimeField(auto_now=True, editable=False, db_index=True) REQUIRED_FIELDS = [name, cluster, position] Serializer for the same: class RoleSerializer(serializers.ModelSerializer): """ A serialized Role object. Roles have an array of permissions. When roles are given to members in clusters, these roles determine the … -
detect related model or create in django
I have two models # models.py class Expert(models.Model): company = models.ForeignKey( Company, on_delete=models.SET_NULL, blank=True, null=True ) first_name = models.CharField(blank=True, max_length=300) class Meeting(models.Model): expert = models.ForeignKey(Expert, on_delete=models.SET_NULL, blank=True, null=True) start = models.DateTimeField(db_index=True, blank=True, null=True) timezone = TimeZoneField(default="America/New_York") What's the best way to write a view that will create a Meeting with an Existing Expert in the database OR create a new Expert and associate it with the new Meeting? my forms # forms.py class ExpertForm(forms.ModelForm): first_name = forms.CharField(widget=forms.TextInput(attrs={"placeholder": "Name"})) class Meta: model = Expert fields = [ "first_name", "company", ] widgets = { "company": autocomplete.ModelSelect2( url="company_private", attrs={ "data-placeholder": "Company", "data-delay": "250", "data-tags": "true", }, ) } class MeetingForm(forms.ModelForm): class Meta: model = Meeting fields = [ "start", "timezone", "expert", ] class MeetingDateAMPMForm(forms.ModelForm): """Meeting Form with support for calendar and am/pm format.""" date_format = "%m/%d/%Y %I:%M %p" # django_date_format = "%m/%d/%Y %H:%M" start = forms.DateTimeField( input_formats=[date_format], widget=DateTimePickerInput(format=date_format), ) class Meta: model = Meeting fields = [ "start", "timezone", "expert", ] def clean_expert(self): data = self.cleaned_data["expert"] if not data: raise ValidationError("An expert is required to create a meeting.") return data my view thusfar # views.py def meeting_expert_create(request): logger.info("meeting_expert_create: running") est_offset = datetime.timedelta(hours=5) if request.method == "POST": meeting_form = MeetingDateAMPMForm(request.POST) expert_form = ExpertForm(request.POST) params … -
Implementation of SSO to my application using Django
I have appX, appY that is build by my organization which is used by other organizations. So now we have plan of implementing SSO to our application. I know my applications will be Service Providers. My question: What should be my approach in reaching to many customers IdP with my SP? Apart from SAML protocol any other suggestions? This would be helpful. -
Hey i want to sum up Total Income and Total Indirect Income Using Jquery How can i do that?
Hey i want to sum up total income and total indirect income. This total values in html table comes using jquery by providing a class. But now i want to sum up two table total values in a single variable and put in a new html table. The new html table looks like we have a column total (income+indirect income) = variable How can i do that using Jquery.Here you can see that the values of total amount column are sum up and lies in the footer on every table. But now i want to sum up two table values in a single variable and that new variable i want to put in a new html table on a same page. $(document).ready(function() { var total_1 = 0; $('.income-amount').each(function(i, obj) { total_1 += parseInt($(obj).text()); }); $('#income-total').text(total_1.toFixed(1)); }); This Jquery i use in Html table for total amount column sumup. Here i also provide my html table. <table id="example" class="table table-striped table-bordered table-responsive-xl"> <caption style="caption-side:top; text-align: center;"><h3>Income</h3></caption> <thead class="thead-dark"> <tr> {# <th>S No.</th>#} <th>Particulars</th> <th>Description</th> <th>Total Amount</th> </tr> </thead> <tbody> {% for item in all_profit %} {% if item.category.under == "Income" %} <tr> {# <td>{{ }}&nbsp;</td>#} <td>{{item.category}}</td> <td>{{item.category.desc}}</td> <td class='income-amount'>{{ item.balance }}&nbsp;</td> … -
django annotate on large data (SLOW) - an alternative?
I have 2 models: Follower has 10M queries class Follower(models.Model): identifier = models.BigIntegerField( _("identifier"), unique=True, null=False, blank=False) username = models.CharField( _("username"), max_length=250, null=True, blank=True) Actions has 5M queries class ActionModel(models.Model): target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username is_followed_back = models.BooleanField(_("Followed Back"), null=True, blank=True) # is target followed back user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, editable=False ) # django user that performed the action Each time I get into Admin panel at Follower I want to count the number of actions per follower per user, and the follow_back field is True : def get_queryset(self, request): ... actionmodel__user = Q(actionmodel__user=request.user) qs = qs.annotate( been_followed_count=Count('actionmodel', filter=actionmodel__user, distinct=True) ).annotate( follow_back_count=Count( 'actionmodel', filter=(actionmodel__user & Q(actionmodel__is_followed_back=True)), distinct=True ) ) IT WORKS BUT IS VERY SLOW ! I guess it filter for each one out of the 10M followers it actions ... so it runs 10M X 5M times ? What is the alternative? I can't store the "been_followed_count" and "follow_back_count" on the Follower model since it common for all django users, so can I somehow store those value instead or recalculate it each get_queryset ? -
How o assign date to Datefield in flask
I have a scenario where I will have to assign date returned from Database to my DateField in flask UI application. I am trying to assign the date but its removing my DateField/Calendar from UI and hence user not able to change/select differen date from Calendar. Can you please tell me correct way to do that? Code: Form Code: class GetDate(FlaskForm) : my_date = DateField('Date of Birth') @ap.route('/customerinfo', methods=''GET','POST']) def customer_data: dob=dbcall.selectsql('my sql query') customer_data=GetDate() customer_data.dob = dob return render_template('/customerinfo.html', customer_data=customer_data) Html Code: {{customer_data.dob.label }} {{customer_data.dob}} -
Django rest framework return validation error messages from endpoints
Using Django==3.0.8 djangorestframework==3.11.0 I am trying to validate a GET endpoint which looks like this. /users?role=Prospect&limit=10&offset=0 How can we validate this request in DRF using serializers.Serializer and get all the validation error messages when invalid and return in api response? Serializer using for this request: class UserIndexSerializer(serializers.Serializer): offset = serializers.IntegerField(required=True) limit = serializers.IntegerField(required=True) role = serializers.CharField(allow_null=True, default=None, max_length=255) View looks function looks like: @api_view(["GET"]) def user_list(request): serializer = UserIndexSerializer(data=request.data) // trying to validate using this serializer print("query params", request.GET) print("request valid", serializer.is_valid()) users = User.objects.all() serializer = UserGetSerializer(users, many=True) return AppResponse.success("User list found.", serializer.data) -
How to Use annotate function to in django for below condition?
class Surface(models.Model): name = models.CharField(max_length=100) class SurfaceGeometry(models.Model): surface = models.ForeignKey(Surface, on_delete=models.DO_NOTHING) geometry_parameter = models.ForeignKey(SurfaceGeometryParameters, on_delete=models.CASCADE) value = models.FloatField() class SurfaceGeometryParameters(models.Model): name = models.CharField(max_length=30, unique=True) Surface.objects.prefetch_related('surface_class',Prefetch('surfacecorrelationcontroller_set'),Prefetch('surfacegeometry_set')).annotate(height=?).order_by('surface_class__name','-height') I want to take height(value) from SurfaceGeomentry model where Height is name of geometry parameter from SurfaceGeometryParameters models for Surface. I can get a height from SurfaceGeometry like this. SurfaceGeometry.objects.get(surface__id = 1, geometry_parameter__name__iexact= 'Height') where surfcace__id's value 1 should come from parent query. How I can achieve the this? -
wagtail-menus is loading the menu but not my page links
It was working before I deleted and recreated my database, I have no idea why it's no longer working, I've ensured that show in menus is checked under the promote panel. base.html {% load static wagtailuserbar %} {% load wagtailcore_tags %} {% load menu_tags %} <!DOCTYPE html> <html class="no-js" lang="en" content="text/html"> <head> <meta charset="utf-8" /> <title> {% block title %} {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %} {% endblock %} {% block title_suffix %} {% with self.get_site.site_name as site_name %} {% if site_name %}- {{ site_name }}{% endif %} {% endwith %} {% endblock %} </title> <meta name="description" content="text/html" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> {% block extra_css %} {# Override this in templates to add extra stylesheets #} {% endblock %} {% load static wagtailsettings_tags %} {% get_settings %} <body class="{% block body_class %}{% endblock %}"> {% main_menu max_levels=2 add_sub_menus_inline=True %} templates/menus/main/menu.html {% load menu_tags %} <nav class="navbar fixed-top navbar-dark navbar-expand-lg navbar-lg" role="navigation"> <div class="container"> <a class="navbar-brand" href="/">Title</a> <button type="button" class="navbar-toggler text-white" data-toggle="collapse" data-target="#navbar-collapse-01"> <i class="fas fa-bars fa-1x"></i> </button> <div class="collapse navbar-collapse" id="navbar-collapse-01"> <ul class="nav navbar-nav ml-auto text-white"> {% for item in menu_items %} {% if item.sub_menu %} <li class="nav-item dropdown {{item.active_class}}"><a class="nav-link dropdown-toggle" … -
Is it possible to create separate customer auth_user for two different Django projects in same database?
Say Project-1 and Project-2 are using same database. Both the Project-1 and the Project-2 planing to have separate custom user model. For example db_table=p1_user for Project-1 and db_table=p2_user for Project-2. Dose Django actually allow to do this customization? Or How to achieve it? -
Django Admin: Custom User model in app section instead of auth section
As in question 36046698, I have a CustomUser model defined in models.py. I would like it to appear in the Authentication & Authorization section in Django Admin. I tried adding app_label = 'auth' as suggested, i.e. class CustomUser(AbstractUser): class Meta: app_label = 'auth' When I do that, my app won’t start, and errors out like so: Traceback (most recent call last): File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/config.py", line 178, in get_model return self.models[model_name.lower()] KeyError: 'customuser' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 157, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/registry.py", line 211, in get_model return app_config.get_model(model_name, require_ready=require_ready) File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/apps/config.py", line 180, in get_model raise LookupError( LookupError: App 'myapp' doesn't have a 'CustomUser' model. During handling of the above exception, another exception occurred: 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 "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line .... File "/Users/paul/myapp/myapp/admin.py", line 3, in <module> from django.contrib.auth.admin import UserAdmin File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 6, in <module> from django.contrib.auth.forms import ( File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/forms.py", line 21, in <module> UserModel = get_user_model() File "/Users/paul/myapp/.direnv/python-3.8.5/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 161, in get_user_model raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'myapp.CustomUser' that has not … -
Using Router vs including url in urlpatterns
Say I am creating a Todo app in Django, traditionally I would include a path to my app in the base_project urls.py file. However, today I came across a tutorial where they used a router for this same purpose I've already stated. Why would I want to use a Router instead of including the path in my urls.py file? For reference, here is a snip from the tutorial found at https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react # backend/urls.py from django.contrib import admin from django.urls import path, include # add this from rest_framework import routers # add this from todo import views # add this router = routers.DefaultRouter() # add this router.register(r'todos', views.TodoView, 'todo') # add this urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) # add this ] Here backend is the main django project name. -
Running Django with Gunicorn over Nginx in Kubernetes is a good idea?
I created Django site and I expecting a lot of processing on my site. I'm running Nginx server with Gunicorn as explained in this tutorial I would like to make something scalable to be able to raise processing power on my site. I have a simple question. Is it possible to move this severs-lump into kubernetes? And if yes, is it a good idea? Or should I use nginx with uWSGI ? -
Django F() expression not working inside a function parameter
I'm trying to convert DateTime value with a specific timezone in a query, it worked when I explicitly added the timezone InventoryDetails.objects.filter(Q(check_time=checktime.astimezone(timezone('Asia/Kolkata'))) But it's not working when I use the below F() expression InventoryDetails.objects.filter(Q(check_time=checktime.astimezone(timezone(F('time_zone'))) -
Django Polls App: Background Image Not Loading
I am learning Django and building out the first test poll app but am running into issues with the background images. The green text works, but adding the background image does not do anything (background is just white). Any idea why this is not functioning properly? Background Image C:\Users\xxx\Python\Django\mysite\polls\static\polls\images\sample123.jpg Style CSS: C:\Users\xxx\Python\Django\mysite\polls\static\polls\style.css li a { color: green; } h1 { color: red; } body { background: white url("images/sample123.jpg") no-repeat; } Index HTML: C:\Users\xxxx\Python\Django\mysite\polls\templates\polls {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} -
UpdateView and Preventing Users from Editing Other Users' Content
I'm using the UpdateView class to allow users to update their content in my app. I am now trying to figure out how to allow users to only edit their own content (and not other users' content). Appreciate any help. class OrganismUpdate(UpdateView): model = Organism fields = ['name', 'edibility', 'ecosystem', 'weather', 'date', 'location'] template_name_suffix = '_update_form' success_url ="/organism_images" -
Trying to access 'content_object' fields in Django under ContentType
I am trying to access the Item model through the Thing queryset, and keep getting the error: django.core.exceptions.FieldError: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. class ThingContent(models.Model): content_id = models.AutoField(primary_key=True, null=False) thing = models.ForeignKey('Thing', on_delete=models.SET_NULL, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') I have tried updating the fields on Item by adding a related_query_name to no success. self.queryset.filter(content_object__item_date=exact_item_date)) -
How to show 3 Cards in a Row in Bootstrap Grid System
I am trying to add 3 cards in a row using bootstrap grid system but the problem is that when I use Django loop each card is showing on its own in each row which is not what I want. I have searched for the answer and I have added it to show my trial but it did not work. Here is the template.html before adding django loop <div class="row row-cols-1 row-cols-md-3 g-4"> <div class="col"> <div class="card h-100"> <img src="" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text"> This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer. </p> </div> <div class="card-footer"> <small class="text-muted">Last updated 3 mins ago</small> </div> </div> </div> <div class="col"> <div class="card h-100"> <img src="" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text"> This card has supporting text below as a natural lead-in to additional content. </p> </div> <div class="card-footer"> <small class="text-muted">Last updated 3 mins ago</small> </div> </div> </div> <div class="col"> <div class="card h-100"> <img src="" class="card-img-top" alt="..." /> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text"> This is a wider card with supporting text below as a natural lead-in to … -
Collecting static in Django - Gunicorn wont find the directory
I have settings.py in my /home/suomi/mediadbin/mediadbin directory with settings BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' I've used python manage.py collectstatic so my static files are in /home/suomi/mediadbin/static In the directory with manage.py (/home/suomi/mediadbin/) I run gunicorn like this gunicorn mediadbin.wsgi:application --bind 0.0.0.0:8000 when I access my site it shows Not Found: /static/main_app/main.css I also tried STATIC_URL = os.path.join(BASE_DIR, 'static') what I'm doing wrong??