Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a modal popup in django_tables2
I am trying to add an edit button that brings up a modal in django_tables2. The first entry in the table behaves correctly but the subsequent entries do no result in a modal popup. When I inspect the buttons, the first shows an event while the rest do not. Any ideas why the behavior isn't repeating. tables.py import django_tables2 as tables from .models import expenseModel from django_tables2 import TemplateColumn class expenseTable(tables.Table): class Meta: model = expenseModel template_name = "django_tables2/bootstrap.html" fields = ('vendor', 'date', 'amount', 'category', 'description') edit = TemplateColumn(template_name = 'edit_button.html') edit_button.html <!DOCTYPE html> <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> </head> <body> <button id='editBtn'>Edit</button> <div id='myModal' class='modal'> <div class='modal-content'> <span class='close'>&times;</span> <p>Some Text in the modal</p> <form action="/summary/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="submit"> </form> </div> </div> <script> let modal = document.getElementById("myModal"); let btn = document.getElementById("editBtn"); let span = document.getElementsByClassName("close")[0]; btn.onclick = function() { modal.style.display="block"; } span.onclick = function() { modal.style.display="none"; } window.onclick = function() { if (event.target == modal) { modal.style.display = "none"; } } </script> </body> The first button shows this: Button 1 The second button shows this: Button 2 -
How do I fix overlarge button (or over-small panel header) in django-bootstrap3?
I have been working on a django project recently and am having problems with one of the templates. I am revising a dashboard to use bootstrap3 drop-down panels, but the toggle buttons are larger than the panel headers. I have tried the advice from a few other answers with no luck. This is my first time using bootstrap so I'm running from mostly basic django tutorials and a W3Schools series. I've tried advice from a few other answers and sites but only succeeded in getting myself confused. I did manage to get the panel header to expand, but that left my title right at the top of the header (instead of centered) and me completely confused, so I backtracked to the code I have here. My code looks like this: <div class="panel panel-default"> <div class="panel-heading"> <div class="pull-right"> <button data-toggle="collapse" data-target="#orders" class="btn btn-primary">+</button> </div> <h3 class="panel-title my-auto">Orders</h3> </div> <div class="panel-body collapse" id="orders"> {% for order in orders %} <p>{{order}} <a href="{% url 'view_order' order.id %}">View</a></p> {% empty %} <p>No outstanding orders. Time to get more business!</p> {% endfor %} </div> </div> And here is a screenshot of how it comes out: screenshot -
How to Style The Django Forms?
So, I am making a project, and I need a couple of settings, in the form of BooleanFields. so, class SettingsForm(forms.ModelForm): notifications = forms.BooleanField(label="", required=False) email_notifications = forms.BooleanField(label="", required=False) restricted_mode = forms.BooleanField(label="", required=False) hide_subscriber_count = forms.BooleanField(label="", required=False) private_channel = forms.BooleanField(label="", required=False) playlists_private = forms.BooleanField(label="", required=False) class Meta: model = Settings fields = ['notifications', 'email_notifications', 'restricted_mode', 'hide_subscriber_count', 'private_channel', 'playlists_private'] How to use widget=forms.BooleanField(attrs={"id":"notifications", "class":"notifications"})? How to stick an id to the notifications field or email_notifications field? -
How to keep Django 2.2 migrations on Kubernets while developing?
I have a rather complex K8s environment that one of the Deployments is a Django application. Currently we are having a very hard time whenever I need to update a model that has already been migrated to a PostgreSQL database. Let's say for instance that I create an application named Sample, that has a simple table on the models.py. My development process (skaffold) builds the docker and apply it locally on the minikube, after this is done I connect to the pod via kubectl exec and execute the python manage.py makemigrations and python manage.py migrate, so far so good. After some time, let's say I need to create a new table on the models.py file of the Sample application, the skaffold builds the docker, kills the old pod, and create the new pod. So I connect as usual via kubectl exec and try to execute the makemigrations and migrate command, lo and behold, there's no migration to apply. And of course no change is made on the PostgreSQL. Upon further searching this, I believe that the reason for this is that since the docker is built without the Sample/migrations folder, and there's already a table (the original one) on the … -
Using Python 3.9 and Django 3.1.3 server crashes when re-launched
this is my first question at Stack overflow. I have been learning Python for about a month and Django for two weeks. I tried to run a second server on my MacBook Pro and then had these problems.(the error messages from my terminal below) The second server included some other applications including Pihole. I deleted the second server files and re-booted, problem solved! The next thing was that I tried editing my Views.py file in Django and then the same error message came back when I re-booted my Django server in the virtual environment folder. See errors below: mymac@michaels-MacBook-Pro mfdw_root % python manage.py runserver Traceback (most recent call last): File "/Users/mymac/Desktop/mfdw_project/mfdw_root/manage.py", line 22, in <module> main() File "/Users/mymac/Desktop/mfdw_project/mfdw_root/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked … -
How to Preventing duplicate signals by using dispatch_uid
I am using a signal to send a notification to the Authors when a new activity such as a User clicking a like button to a post. I am having a side effect of using the signal which is when a user creates a new post and a user likes the post, the author receives 2 notifications instead of just 1. I have searched for several answers but they affected other sides of the project so I found on the Django documentation that using a dispatch_uid="my_unique_identifier" will fix these problem. https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals I have made a trial but it didn't work out. So here it is: Here is the Like model.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" def user_liked_post(sender, instance, *args, **kwargs): like = instance if like.value=='Like': post = like.post sender = like.user dispatch_uid = "my_unique_identifier" notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() def user_unlike_post(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user notify = Notification.objects.filter(post=post, sender=sender, user=post.author, notification_type=1) notify.delete() def like_progress(sender, instance, *args, **kwargs): like = instance post = like.post sender = like.user dispatch_uid = "my_unique_identifier" if … -
Deleting a Previously sent Notification in a Django Project
I am going to try to be as descriptive as possible to explain my issue. First I have a Like button in my Django Blog Project which is working fine. My issue is I have a Like Model and I have created signal where when a user clicks to like on a post a signal is sent and a notification is created, but I am struggling with the logic that if the same user Unlike the post (clicking the like button for the second time), I want a signal to be sent to delete the created notification So currently here is what is happening: A User clicks the Like button. The value of the Like button is Like Notification sent to the Author of the Post The same user clicks the Like button again. The value of the Like button is Unike Nothing happens What I want is the previously sent notification to be deleted Here is my Models.py related to the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') num_likes = models.IntegerField(default=0, verbose_name='No. of Likes') likes = models.ManyToManyField(User, related_name='liked', blank=True) Here is the views.py: class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" def get_context_data(self, … -
docker log don't show python print output
I have a Django Proj running in Docker Container My Debug=True but docker up logging doesn't show any print('') output. Is there a way to fix it? thanks! -
Django url dispatch error - AttributeError: 'WSGIRequest' object has no attribute 'data'
I am dispatching based on the path to my methods in the class. The problem arises when I have to pass it to a post method. Else I can wrap it over a Request using the process_request method. How do I pass the correct request to the methods which is not HttpRequest but the DRF 3 Request I suppose. class AddInvoice(APIView): @staticmethod def process_request(request, *args, **kwargs): if isinstance(request, HttpRequest): return Request(request,parsers=[MultiPartParser, FormParser, JSONParser, DjangoMultiPartParser]) return request parser_classes = (MultiPartParser, FormParser, JSONParser, DjangoMultiPartParser, FileUploadParser) def dispatch(self, request, *args, **kwargs): response = None #request = AddInvoice.process_request(request, *args, **kwargs) if request.method == 'PUT': if request.path.rstrip('/') == '/invoice/digitize': response = self.digitize(request,*args, **kwargs) elif request.method == 'GET': if request.path.startswith('/invoice/isdigitized/'): response = self.isdigitized(request, *args, **kwargs) elif request.path.startswith('/invoice/get/'): response = self.get(request, *args, **kwargs) elif request.method == 'POST': if request.path.rstrip('/') == '/invoice': response = self.post(request, *args, **kwargs) if not response: response = Response(status=status.HTTP_406_NOT_ACCEPTABLE) if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) request.accepted_renderer, request.accepted_media_type = neg response.accepted_renderer = request.accepted_renderer response.accepted_media_type = request.accepted_media_type response.renderer_context = self.get_renderer_context() return response -
Django - ensure there is only one ACTIVE product per user
Having this model class Product(models.Model): user = models.ForeignKey(...) STATUS_ACTIVE = 'active' STATUS_CANCELLED = 'cancelled' STATUS_DRAFT = 'draft' STATUS_CHOICES = ( (STATUS_ACTIVE,'Active'), ... ) status = models.CharField(..., choices=STATUS_CHOICES) I'm trying to figure out how to make User model having only one product that is ACTIVE. User is allowed to have any number of CANCELLED and DRAFT products, but only one can be ACTIVE. I'm thinking about CheckConstraint but I can't figure out such query. -
How do I get images to show on my django app?
On my Django app, I am trying to make an eBay type of site that lets people post listings with pictures and bid on them. Everything works except posting an image. The image won't show and I do not know if it's the HTML or the python. If you have any questions let me know. Html code: {% extends "auctions/layout.html" %} {% block body %} <div class="container"> <h2>Create listing</h2> </div> <div class="container"> <form action="{% url 'submit' %}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlInput1">Title</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="Title of the lisiting..." name="title" required> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Description</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="5" placeholder="Description..." name="description" required></textarea> </div> <div class="form-group"> <label for="exampleFormControlSelect1">Category</label> <select class="form-control" id="exampleFormControlSelect1" name="category" required> <option>Fashion</option> <option>Tools</option> <option>Toys</option> <option>Electronics</option> <option>Home accessories</option> <option>Books</option> </select> </div> <div class="form-group"> <label for="exampleFormControlInput1">Initial Bid</label> <input type="number" class="form-control" id="exampleFormControlInput1" placeholder="Starting bid..." name="price" required> </div> <div class="form-group"> <label for="exampleFormControlInput1">Image link (optional)</label> <input type="text" class="form-control" id="exampleFormControlInput1" placeholder="https://blah-blah.jpg..." name="link"> </div> <button class="btn btn-outline-info" type="submit">Submit</button> </form> </div> {% endblock %} This is the python function for making listings: def create(request): try: w = Watchlist.objects.filter(user=request.user.username) wcount=len(w) except: wcount=None return render(request,"auctions/create.html",{ "wcount":wcount }) -
Shared configuration across python threads/modules
Something very simple (python!) gone very very bad: I have a Django service app - main thread create a selenium service and keeps its parameters (for all that it matters a string) in a global variable. Another thread that handles a request is required to access this global string with the shared service address (and actually pass it to another thread, but let's leave that for now). There seem to be no sane way to do that. Not without using shared memory or database. I suspect python has better means of sharing data across threads/modules? -
How do I get object in JavaScript/HTML from Django by ID?
I'm doing a small clinic project using Django. In one page of all html pages I would like to create big buttons in which I have data of specific appointment(id, title, doctor, patient, start hour, end hour). It looks like: APPOINTMENT BUTTON There are the fundamental files: models.py class Appointment(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100, default=defaultTitle) description = models.CharField(max_length=480, null=True, blank=True) start_date = models.DateTimeField(null=True, blank=True, default=datetime.date.today) end_date = models.DateTimeField(null=True, blank=True, default=datetime.date.today) doctor = models.ForeignKey(User, on_delete=models.CASCADE) patient = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='+', blank=True) def __str__(self): return self.title views.py def doctortoday(request): today = datetime.date.today().strftime("%d.%m.%Y") today_appointments = None if request.method == 'GET': today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min) today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max) try: today_appointments = Appointment.objects.filter(doctor=request.user, start_date__range=(today_min, today_max)) except: today_appointments = None context = { 'today': today, 'appointments': today_appointments } return render(request, 'doctortoday.html', context) If we click the appointment button then will show popup modal. At the moment there is only QuerySet - {{ appointments }}. POPUP MODAL And the my major problem - how can I display in the popup modal the specific appointment's data without refreshing page? I just want, if we click the button with Appointment 2 then in the popup modal will be data of the Appointment 2. The same … -
Django - Random sort after distinct
I want to do is: Always return a random sort for my query Query result should not include duplicates Support Paging for that This is my query simplified # merge two queries and eliminate duplicates queryset = (items_no_cards | items_no_categories).distinct() # return a sort order queryset.order_by('?') If i do this ^ then it returns duplicated items with a random order, if i just do: # merge two queries and eliminate duplicates queryset = (items_no_cards | items_no_categories).distinct() # return a sort order queryset.order_by("-date_created") No duplicates but returns a sorted order. I know that i can use a python random function instead of doing .order_by('?') but i want to support paging, so it doesn't apply for this case. Thanks in advance -
Django URL and Vue Router Conflict
I have been searching high and low for some way to fix this problem and can't seem to find anything that will work. I appreciate any insight you can give. My project is built with Django and Vue and the router in Vue always picks of the URL to my /media directory, preventing files from being able to download properly. My Django URL setup looks like this: urlpatterns = [ # path('admin/', admin.site.urls), url(r'^admin/', admin.site.urls), path("accounts/register/", RegistrationView.as_view( form_class=CustomUserForm, success_url="/", ), name="django_registration_register"), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api/", include("users.api.urls")), path("api/", include("questions.api.urls")), path("api/", include("contacts.api.urls")), path("api/", include("filemanager.api.urls")), path("api-auth/", include("rest_framework.urls")), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), path(r"", IndexTemplateView.as_view(), name="entry-point") # re_path(r"^.*$", IndexTemplateView.as_view(), name="entry-point") ] if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) The Vue router looks like this: export default new Router({ mode: "history", routes: [ { path: "/", name: "home", component: Home }, { path: "/question/:slug", name: "question", component: Question, props: true }, { // the ? sign makes the slug parameter optional path: "/ask/:slug?", name: "question-editor", component: QuestionEditor, props: true }, { path: "/answer/:id", name: "answer-editor", component: AnswerEditor, props: true }, { path: "/contacts/", name: "contacts", component: ContactView, props: true }, { path: "/contacts/:id", name: "single-contact", component: SingleContactView, props: … -
How to add "public" by default to cached views by Django?
Im trying to use Google Cloud CDN to cache Django responses. Django properly sets the cache-control header with the max age, but it is missing the 'public' part of the header. Basically, currently all cached views have: cache-control: max-age=3600 But I want: cache-control: max-age=3600,public -
Question about integrating my python Django-Dash-Plotly app to a sub-domain in SquareSpace
I currently have a python app deployed using Django, which uses Dash-plotly as a critical aspect. All of my copy/content has to be done through source code, which works for me, but is not convenient for everyone. I have a friend that wants to help me with the copy/content website. So due to circumstances: I want to create a SquareSpace for the website, and then use a sub-domain to connect the python app. Would it make sense to keep my app deployed via Django (trimming down all unnecessary code)? And then just connect my app to the sub-domain? The last thing I want is for things to feel slowed down, I have my doubts that Django might be overkill for this specific case. How viable would this turn of events be in terms of development? -
How to set up chat rooms with limited access in Django? That is, we allow connections only from users registered in a particular chat room?
I recently joined a friend and his colleague in creating a social network-like website. I have sizeable programming experience, though no experience with Django. The friends have intermediate experience in general, but distinctly more with Django than me. We want to implement chat rooms, which behave similar to e.g. WhatsApp groups: Upon certain events, the server can add users to a particular chatroom and conversely also remove them. The users can send and recieve messages to and from that chatroom when connected and retrieve old messages which they missed since the last time they were online. My question is no to ask for the standard way to implement that system. We already have chat rooms where everyone can join via the right URL. However that is evidently not sufficient because we can't restrict access yet. Up to this point, we are using Django channels and we have set up the public chat rooms in accordance with the Channels Tutorial. I have already seen the django private chat package. However, I am reluctant to integrate that because I'm trying to avoid cluttering the project with packages and more importantly am trying to minimize the new technologies that we, particularily I, have … -
Mysterious Django API Behavior In Production
Long time reader but newly joined the community. I have a mysterious issue that I would like to seek help with. Since this is a part of the code that is currently running in production I need to redact parts of the info and will provide information is and when required. If needed I will also make a new sample code to make sure we can all test and also guide me the right way to troubleshoot the issue. Currently, there is an web application ( django/wagtail/coderedcms ) backend that need to be converted into a mobile app. To allow the mobile app to communicate with the Backend server, I have implemented an API endpoint using the Django-rest-framework. To authenticate the user, I have already implemented a simple authentication endpoint using Django-rest-simplejwt. This part is working fine. One of the requirement for the app is that the user must be able to view/update their profile through the mobile app. When working in dev server in my localhost, The behaviour is as intended, each user may login using the application, the backend will send back a token, and the tokan will be use subsequently to access the various part off the … -
Can't connect to PostGreSQL from a same-host container
I am using docker to manage my Django apps, and have the same configuration on my laptop and digital ocean : From my laptop I can connect to PostGreSQL thanks to the adminR image (https://hub.docker.com/_/adminer) But if I try to connect to PostGreSQL from adminer on the localhost, I can't : I can ping and find PostGreSQL from the django container : But I can't migrate my database from django scripts : Funny enough, I can migrate on the digital ocean cloud from my laptop : I can see the updated database on my laptop's admineR page : So the issue is obviously an issue of networking between the containers... But if I can ping the service, why can't django access it ???? -
How in django set in url unrequirement argument
All sense in title of query, i try this: path(r'get_turnover/<str:attributes>/\?product=(?P<product>\w+$)', views.OutputTurnover.as_view(), name='get_turnover') but it's not work for me. -
How can fix this error in python " ProgrammingError: 1064,"
Traceback (most recent call last): File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\current_task\Django\360ehs\ime360ehs\views.py", line 792, in createOrder cursor.execute(query + category_condition2 + " ORDER BY category") File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 100, in execute return super().execute(sql, params) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "D:\current_task\Django\360ehs\env\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "D:\current_task\Django\360ehs\env\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ORDER BY category' at line 1") category_condition1 = "" category_condition2 = "" count_left = 0 count_right = 0 category_counts = "SELECT category, COUNT(category) FROM tbl_products GROUP BY category ORDER BY COUNT(category) DESC" with … -
Cannot get frontend to run on localhost. nginx docker nuxt/express
I'm trying to configure nginx to serve frontend and backend of my app. My frontend is a nuxtjs application and my backend is django. I can access backend at localhost:8000 But I cannot access nuxt at localhost:3000 I'm using nginx as a reverse proxy. When I run npm run dev which uses the "nuxt" command my project builds successfully. I can't see anything in the logs and I don't know why localhost or 0.0.0.0 isn't getting any response or error when the frontend is build and running. How do I get the front to be mapped and served by nginx so I can access the api of django? ℹ [HPM] Proxy created: / -> http://backend:8000/api [HPM] Subscribed to http-proxy events: [ 'proxyReq', 'proxyRes', 'error', 'close' ] ℹ Listening on: http://172.19.0.5:3000/ ℹ Preparing project for development ℹ Initial build may take a while ✔ Builder initialized ✔ Nuxt files generated ℹ Compiling Client ℹ Compiling Server ✔ Server: Compiled successfully in 11.82s ✔ Client: Compiled successfully in 19.09s ℹ Waiting for file changes ℹ Memory usage: 212 MB (RSS: 337 MB) ℹ Listening on: http://172.19.0.5:3000/ docker-compose.yml version: '3.3' volumes: autobets_data: {} redis_data: networks: random_name: driver: bridge services: backend: build: context: ./backend … -
media file not serve in django with wihtenoise
Media files in Django are not visible and are not displayed. I used WhiteNews. like this: in wsgi.py i add this: application = WhiteNoise(application, root=BASE_DIR / 'static') application.add_files(BASE_DIR / 'media', prefix='mdeia/') in settings.py i add this: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', . . . MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', . . . STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' STATIC_ROOT= BASE_DIR / 'static' STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT= BASE_DIR / 'media/' in html file : <img src="{{user.photo.url}}" style=" width:90px; height:90px; border-radius:50px 50px 50px 50px;"> and in models.py i using this: photo=models.ImageField(upload_to='users/photos/',default='user-photo.png',null=True,blank=True) I download static files without any problems and media files are saved without any problems but they are not downloaded. Thank you for your help. -
Django templates tag value separation
I have tag in my template {{ x.list }} which prints entire entry from database. Is there a way to print entries one by one separated by space? {{ x.list.1 }} prints first letter.