Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model post_save
How do I insert new data to another models if the system detects the field is updated? for example i have two models FmCustomerEmployeeSupplier and TrCustomerEmployeeSupplierSubmittedRecords, this is the model //FmCustomerEmployeeSupplier class FmCustomerEmployeeSupplier(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] fmCustomerID = models.ForeignKey('FmCustomer',on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") email = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(null=True, blank=True) employee_number = models.CharField(max_length=500, blank=True, null=True) inputdate = models.DateField(auto_now_add=True) inputBy = models.CharField(max_length=500, blank=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def clean_name(self): return self.cleaned_data["employee_number"].upper() def save(self, force_insert=False, force_update=False): self.employee_number = self.employee_number.upper() super(FmCustomerEmployeeSupplier, self).save(force_insert, force_update) @property def is_past_due(self, *args, **kwargs): return date.today() > self.modifyDate //TrCustomerEmployeeSupplierSubmittedRecords class TrCustomerEmployeeSupplierSubmittedRecords(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] fmCustomerID = models.ForeignKey('FmCustomer',on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Customer") email = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(null=True, blank=True) employee_number = models.CharField(max_length=500, blank=True, null=True) inputdate = models.DateField(auto_now_add=True) inputBy = models.CharField(max_length=500, blank=True) modifyDate = models.DateField(auto_now=True, blank=True, null=True) modifyBy = models.CharField(max_length=500, blank=True) status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) Storyline: the user updated the body temperature in FmCustomerEmployeeSupplier, i just want that in my models, i have a trigger when the system detect that the FmCustomerEmployeeSupplier updated, the record will insert in TrCustomerEmployeeSupplierSubmittedRecords. -
Django HttpOnly Cookies Not Persisting on Mobile Devices
My Django HttpOnly cookie is not persisting on mobile devices. I am creating the cookie like this: response.set_cookie( key=settings.SIMPLE_JWT['AUTH_COOKIE'], value=data["access"], expires=settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure=settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly=settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite=settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) with these settings: SIMPLE_JWT = { 'AUTH_COOKIE': 'access_token', # Cookie name. Enables cookies if value is set. 'AUTH_COOKIE_SECURE': True, # Whether the auth cookies should be secure (https:// only). 'AUTH_COOKIE_HTTP_ONLY': True, # Http only cookie flag.It's not fetch by javascript. 'AUTH_COOKIE_PATH': '/', # The path of the auth cookie. 'AUTH_COOKIE_SAMESITE': 'Strict', # Whether to set the flag restricting cookie leaks on cross-site requests. # This can be 'Lax', 'Strict', or None to disable the flag. 'ACCESS_TOKEN_LIFETIME': timedelta(days=28) } This works perfectly fine on desktop browsers but these cookies don't persist for more than a few minutes on mobile browsers. How do I get the cookies to persist for 28 days on mobile devices? -
Behave failed on websocket test
I am currently working on test with behave, everything is working as intended but when I try to connect to a websocket I can't seem to connect and it returns 404. I have read at [https://github.com/behave/behave-django/issues/16][1] that I have to set up a channel backend. I tried using channels ChannelLiveServerTestCase instead of StaticLiveServerTestCase but all I got is connection refused as the error. I am not sure if I am doing it right since I'm just new to behave and channels. Below is my environment.py import os import django from django.contrib.staticfiles.testing import StaticLiveServerTestCase from channels.testing import ChannelsLiveServerTestCase from django.shortcuts import resolve_url from django.test.runner import DiscoverRunner os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings_test" django.setup() def before_all(context): context.test_runner = DiscoverRunner() context.test_runner.setup_test_environment() context.old_db_config = context.test_runner.setup_databases() context.test = BehaviorDrivenTestCase() context.test.setUpClass() # This starts a transaction context.test() context.base_url = context.test.live_server_url class BehaviorDrivenTestCase(ChannelsLiveServerTestCase): serve_static = True """ Test case attached to the context during behave execution This test case prevents the regular tests from running. """ def runTest(*args, **kwargs): pass def test(self): self.live_server_url def after_all(context): context.test.tearDownClass() del context.test context.test_runner.teardown_databases(context.old_db_config) context.test_runner.teardown_test_environment() -
Django Admin Theming
My Django admin dashboard is loading with a dark theme. I don't have any extensions for dark themes installed into my browser. How can I revert it to the light theme? Currently, my admin area is in this state: django admin image Any help would be greatly appreciated -
how can correct this to render list of data in page reactjs?
import axios from "axios"; import React, { Component } from "react"; class ArticleHome extends Component { constructor(props) { super(props) this.state = { articles: [], errorMessage: '', } } componentDidMount() { axios.get('http://127.0.0.1:8000/article/') .then(response => { console.log(response) }) .catch(error => { console.log(error) this.setState({ errorMessage: 'error retriving Data' }) }) } render() { const { articles, errorMessage } = this.state return ( list porps { articles.length ? articles.map(a => {a.id}{a.title}{a.slug}{a.updated_on}{a.content}) : null } {errorMessage ? {errorMessage} : null} ) } } export default ArticleHome; -
How to filter by nested field in Django
I'm working on a small project using Django Rest Framework, i have two models class Task(models.Model): status = models.ForeignKey(Status, related_name="tasks", on_delete=models.CASCADE) contact = models.ForeignKey(Contact, on_delete=models.CASCADE) title = models.CharField(max_length=60, blank=False, null=False) class Status(models.Model): title = models.CharField(blank=False, null=False, max_length=255) slug = models.CharField(blank=False, null=False, max_length=255) order = models.SmallIntegerField(default=0) def __str__(self): return self.title This is my serializers : class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' class StatusSerializer(serializers.ModelSerializer): tasks = TaskSerializer(many=True) class Meta: model = Status fields = '__all__' This is my view code : def list(self, request): objectSerializer = StatusSerializer(Status.objects.all(), many=True) return Response(objectSerializer.data) Until the moment I'm happy with the data structure that I have created, I would like now to create another function in my views to filter by the (contact) which is a foreign key as you can see -
Problem listing out 3rd level of data from my models effectively (Django)
I need to create a monitoring/summary view for the last 7 days of assurance data we collect on a daily basis. I have 3 models: Customer Equipment (The Customer's equipment) Stats (Daily data on performance, i.e. uptime percentage) In the views I'm filtering out the active customers and passing this to the template based on active equipment (remotes), and I'm also passing on the calculated date range (today's date -7 days). In the view I was easily able to list out the customer (name, parent's name) and the equipment data (serial number, installation date). But for the next level I'm really banging by head against the wall how to retrieve the Stats (uptime percentage) based on date and serial number of the equipment without some ugly nested for loops that runs the same query multiple times and makes the load take very long. The solution so far: for remote in remotes</br> # remotes bassed from the view <tr> <td>{{remote.parent}}</td> <td>{{remote.serial}}</td> <td>{{remote.install_date}}</td> for date in dates # dates passed from the view for stat in remote.stat_set.all|dictsortreversed:"date"|slice:":8" if date == stat.date: <td>Output the {{stat.percentage}} value</td> endif endfor endfor </tr> endfor I've made a hack with combining django and javascript in the template/html, … -
Django and Javascript - Like Button Not Working
I am new to Django and Javascript - I am making a project that has posts on a site, and I want to create a 'like' button on each post. So far here is my code - I am not getting any errors at all. No console errors in the browser either. But nothing happens. When you click the heart image, if it is liked, it should be a red image. When it is not liked, it is the white heart image. Currently when I click the image, it just stays white. It is always defaulting to that white image. The code doesn't work. Any help is appreciated. views.py for the like button: @csrf_exempt def like(request): if request.method == "POST": post_id = request.POST.get('id') is_liked = request.POST.get('is_liked') try: post = Post.objects.get(id=post_id) if is_liked == 'no': post.like.add(request.user) is_liked = 'yes' elif is_liked == 'yes': post.like.remove(request.user) is_liked = 'no' post.save() return JsonResponse({'like_count': post.like.count(), 'is_liked': is_liked, "status": 201}) except: return JsonResponse({'error': "Post not found", "status": 404}) return JsonResponse({}, status=400) views.py for the page to show all the posts: def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() paginator = Paginator(list_of_posts, 10) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "list_of_posts": list_of_posts, "page_obj": page_obj }) Javascript … -
How send data from javascript-datatable to Django and after redirect to other url, People says ajax but i dont know use it very well
Please help, I have a Jquery datatable with checkable options, which are displayed through a List View, and I would like to send the selected options to Django and change the current URL after this, most people tell me to send the data by ajax, but I don't know how to do that part This is my table <table class="table display" id="table_selecting_formularios"> <thead> <tr> <!-- <th scope="col">#</th> --> <th></th> <th scope="col">Nombre</th> <th scope="col">Descripcion</th> <th scope="col">Subsistema</th> </tr> </thead> <tbody> {% for formulario in formularios %} <tr> <td></td> <td style="text-transform: uppercase;"> {{formulario.nombre_formulario}} </td> <td>{{formulario.descripcion_formulario}}</td> <td>{{formulario.subsistema_estadistico}}</td> </tr> {% endfor %} </tbody> </table> This is my class based view where in the post method i'd like grab the checked data from the table and then redirect to other url class SelectingFormulariosView(LoginRequiredMixin, generic.ListView): #? Y que modelo pongo aqui model = Formulario template_name = 'forms/publicacion/selecting_formularios.html' @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get_queryset(self): return Formulario.objects.all() def get(self, request, *args, **kwargs): context = self.get_context_data() return self.render_to_response(context) def post(self, request, *args, **kwargs): # print(request.POST['formularios[]']) # names = request.POST['formularios[]'] # # data = Indicador.objects.filter(formulario__nombre_formulario__in=names) # request.session['formularios'] = names # return HttpResponseRedirect('/handler/seleccionar-indicadores/') return reverse_lazy('handler:seleccionar-indicadores') def get_context_data(self, **kwargs): self.object_list = super().get_queryset() context = super(SelectingFormulariosView, self).get_context_data(**kwargs) try: … -
Deploy django app in heroku with poetry environment
I've been using poetry for a while for many practice projects but haven't deployed anything until now, and when I try to do it in heroku I get this error. -----> Installing python-3.9.1 -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 -----> Installing SQLite3 -----> Installing requirements with pip Processing /home/santi/.cache/pypoetry/artifacts/9c/90/26/d9fa1dfd567d8ba46faa44b741eb6442f3b97eb9f10a40bc1ad7a7f10e/asgiref-3.3.1-py3-none-any.whl ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/home/santi/.cache/pypoetry/artifacts/9c/90/26/d9fa1dfd567d8ba46faa44b741eb6442f3b97eb9f10a40bc1ad7a7f10e/asgiref-3.3.1-py3-none-any.whl' ! Push rejected, failed to compile Python app. ! Push failed I can't seem to find anything specific to this django-poetry-heroku issue so maybe I can find some help over here, I have my petry.lock and .toml files, also a requirements.txt since heroku requires it, here they are... pyproject.toml [tool.poetry] name = "Team Wool Capstone App" version = "0.1.0" description = "News app with likes, and user submission feature" authors = ["Joseph Dubon <josephdubon@pm.me>"] [tool.poetry.dependencies] python = "^3.9" Django = "^3.1.7" flake8 = "^3.9.0" Pillow = "^8.2.0" whitenoise = "^5.2.0" django-environ = "^0.4.5" gunicorn = "^20.1.0" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" -
Django - How to run consecutive forms?
I have a user registration form that asks for user information and also asks a question: "Are you a PSMC member?" The options are: rank = [ ('Supporter', 'Supporter (non-member)'), ('Anak', 'Anak'), ('Uso', 'Uso'), ('Chief', 'Chief'), ] If Supporter is selected, then the registration form proceeds and saves user info, etc. This part works fine. However, if Anak is selected, I want it to take the user to another form that asks additional questions. In my forms.py, I have class RegisterForm which is the main registration form for all users. I also have class AnakRegisterForm which is what I want it to continue on to. I used Django's AuthenticationForm based off what I read from their website (but I could be wrong). I know the issue is in views.py register function. Specifically: if rank == 'Anak': anak_register(response) During my debug session, after it moves response to anak_register function, it gets a bunch of scrambled information. I'm pretty lost, any help would be appreciated. Here is my code: forms.py class RegisterForm(UserCreationForm): email = forms.EmailField( initial='', required=True, help_text='Please enter a valid email address' ) rank = forms.ChoiceField( label='Are you a PSMC member?', choices=SavBlock.models.User.rank, initial=False, required=True, help_text='Member accounts will be validated with your … -
ValueError: logout didn't return an HttpResponse object. It returned None instead
I realize that this question has been asked before, but I'm struggling for explanation as to why I'm getting the following error: ValueError: The view django.contrib.auth.logout didn't return an HttpResponse object. It returned None instead. I'm following exactly what Django has in their docs here when it comes to logging out: https://docs.djangoproject.com/en/3.2/topics/auth/default/#how-to-log-a-user-out class LoginPage(TemplateView): template_name = "users/login_page.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['login_form'] = LoginUserForm(data=self.request.POST or None) return context def get(self, request): context = self.get_context_data() return self.render_to_response(context) def post(self, request): context = self.get_context_data() form = context['login_form'] if form.is_valid(): user = form.get_user() login(request, user) return HttpResponseSeeOther(reverse("questions:mainpage")) return self.render_to_response(context) def logout_user(request): logout(reqeust) return HttpResponseSeeOther(reverse("users:login")) user_urls = ([ path("register/", uv.RegisterPage.as_view(), name="register"), path("login/", uv.LoginPage.as_view(), name="login"), path("logout/", uv.logout, name="logout") ], 'users') urlpatterns = [ path('admin/', admin.site.urls), path("", include(question_urls)), path("users/", include(user_urls)), ] -
Serving static images in Django development
this is a commonly asked question so I am not sure why I can't get this to work. Foremost, here is the file structure of my project: -blog -templates - - about.html -media -static - -css - -img - - profile_pic - -js ... I have gone through the process of configuring my settings.py to serve static files during development by adding the following: STATIC_URL = '/static/' and STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static',), ] into my settings.py file. In my about.html, I place the {% load static %} tag at the top of the page, then I attempt to load my image by calling the tag like so: <img class = "card-img-top" src="{% static 'img/profile_pic'%}" alt="My profile picture"> Nothing appears. The logs state "GET /static/img/profile_pic HTTP/1.1" 404 1671 So the file isn't loading at all. Could this be a problem with my filepaths? -
How to specify the user in the blog post in django?
I'm quite new in django, and here is my question: I have a django model (like posts in blog with a form) -> class Product(models.Model): asset_name = models.CharField(verbose_name='Название актива', max_length=50) asset_sector = models.CharField(verbose_name='Отрасль', max_length=50) asset_price = models.DecimalField(verbose_name='Цена', max_digits=10, decimal_places=2) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) and here is field called author, I have an authorization and i need the next: when the user add his post, the post would automatically choose the author (current user) Now my model don't add anyone, just give the possibility to choose here to see the screenshot of django admin imports: from django.db import models from backend import settings model of User class CustomUser(AbstractUser): balance = models.DecimalField(max_digits=10, decimal_places=1, null=True, default=0) email = models.EmailField(blank=True, null=True) username = models.CharField(unique=True, max_length=150) USERNAME_FIELD = 'username' def __str__(self): return self.username form of adding the post class ProductForm(ModelForm): class Meta: model = Product fields = ['asset_name', 'asset_sector', 'asset_price', ] widgets = { "asset_name": TextInput(attrs={ 'class':'form-control', 'placeholder': 'Название актива', }), "asset_sector": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Отрасль', }), "asset_price": NumberInput(attrs={ 'class': 'form-control', 'placeholder': 'Цена', }), } -
Building django web app which uses algorithms running on google colab
i wanted to create a Django web application on where i will put some ML algorithms and a user interface to make easy to upload pictures and videos ,and these algorithms gonna run on google colab. but the problem is that i don't know how to make my app interacts with google colab mostly that there is no api for this google service. if you have any idea which can help me , please don't hesitate -
Nginx https not redirecting on iphone and macos's browser chrome
I just screwed up with this problem for last 4 days and i posted about it on stackoverflow 3 times, no one couldn't solve the problem. I dont know if it is possible to solve. My server is working very well with https and redireting http to https when i type example.com. it is working on all devices except ios/macos. I don't know whats wrong with my configuration. Can anyone help me to fix this. this is my current configuration server { listen 443 ssl; server_name example.com www.example.com; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_certificate /etc/certs/example_com.crt; ssl_certificate_key /etc/certs/definesys.key; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://backend:80; } } # Redirext https server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by ssl server_name example.com; listen 80; return 301 https://$host$request_uri; } The isue only ios/macos. But if i try with this: https://www.example.com it works but i want whenever user type example.com it should always redirected to https and this is working very well on all device except apple device. My app is django and running on docker, with nginx and gunicorn. Can anyone help me to fix this? -
Celery Tasks in Chain Starting Out Of Order
I am trying to implement some celery chains/groups/chords using django 3.0, celery 4.3, redis and python 3.6. From the documentation, I thought tasks in a group run in parallel, and tasks in a chain run sequentially, but I am not observing that behavior. I have this chain of task signatures: transaction.on_commit(lambda: chain(clean, group(chain(faces_1, faces_2), folder, hashes), change_state_task.si(document_id, 'ready')).delay()) where I expect the change_state_task to wait for all the other tasks to complete before it starts. This did not work, in that the change_state_task started before hashes finished. All the tasks ran and completed successfully. I then tried this chain: transaction.on_commit(lambda: chain(clean, faces_1, faces_2, folder, hashes, change_state_task.si(document_id, 'ready')).delay()) where all the signatures are in a long chain. However, the change_state_task is still starting before the hashes task finishes. I even tried using change_state_task.s(document_id, 'ready') (replaced si with s), thinking that the change_state_task could not start without the output of the hashes task. But it still starts before hashes ends. I then tried using task.s versus task.si for all the task signatures, and the change_state_task still started before the hashes task ended. What am I missing? Thanks! Mark -
How to create user status active deactivate toggle button in Django?
I want something like this in my Django . enter image description here Can anyone tell me how should I code in html template and views.py ? -
TemplateSyntaxError: Could not parse the remainder: '${id}' from '${id}'
I am trying to pass javascript variables into the URL template in my ajax call within my script tag but it keeps telling me that it could not parse the remainder. Any idea how it should be? $.ajax({ type: 'POST', url: `{% url 'posts:toggle-reaction' object_id=${id} object_type=${type} %}`, data: serializedData, success: function (response) { }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) -
Site matching query does not exist even. Everything is set, site domain defined
So i just want my sitemap.xml to work in production. I have included this module in INSTALLED_APPS: 'django.contrib.sites', I have declared SITE_ID: SITE_ID = 1 I defined domain name 'mydomain.com' in sites model which is exacly the domain my site running on. I restarted the server And i still get 'django.contrib.sites.models.Site.DoesNotExist: Site matching query does not exist' error I don't get this error when i run on localhost. -
django.core.exceptions.ImproperlyConfigured after using reverse()
I'm new in Django. Here is my issue. I'm trying to use reverse() function to add 'data-url' attribute to my form in my forms.py file in order to use it in my JavaScript then. But I run into the following exceptions: django.core.exceptions.ImproperlyConfigured: The included URLconf 'orthodontist.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import The thing is reverse() with the same url name works fine in my view.py file. Here is my code: forms.py class OrderByForm(forms.Form): order_by = forms.ChoiceField(required=False, choices=ORDER_BY, label='Сортировать по', widget=forms.Select(attrs={ 'class': 'form-control', 'data-url': reverse('ask:question_ajax') })) project urls from django.contrib import admin from django.urls import path, include from index import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index), path('signup/', views.signup, name='signup'), path('login/', views.login_view, name='login'), path('logout/', views.logout_view, name='logout'), path('user/<int:pk>/', views.UserView.as_view(), name='user'), path('user/<int:pk>/popular/', views.UserViewPopular.as_view(), name='user_popular'), path('user/<int:pk>/update/', views.UserViewUpdate.as_view(), name='update'), # path('user/<int:pk>/update_post', views.user_update_post, name='update_post'), path('admin/', admin.site.urls), path('search/', views.SearchResults.as_view(), name='search'), path('question/', include('ask.urls')), ] if bool(settings.DEBUG): urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls from django.urls import path from . import views app_name = 'ask' urlpatterns = [ path('', views.AskView.as_view(), name='index'), path('<int:pk>/', views.QuestionDetail.as_view(), name='question'), path('ask/', views.AskQuestionView.as_view(), name='ask_question'), path('<int:pk>/delete_question/', views.delete_question, name='delete_question'), path('<int:pk>/delete_answer/', … -
Custom @property used as APIField is displayed correctly but can't be used for ordering the results
I have a model for a Normal Wagtail page, which has two fields, and a custom property like this: class DetailPage(AbstractSitePage): total = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) additional_amount = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True, default=Decimal("0.00") ) content_panels = [ FieldPanel("additional_amount"), ] + AbstractSitePage.content_panels api_fields = [ APIField("additional_amount"), APIField("total"), APIField("new_total") ] class Meta: ordering = ("-total",) @property def new_total(self): if self.additional_amount: return str(self.total + self.additional_amount) return str(self.total) doing so makes the following URL works just fine and displays the new_total values correctly /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-total but if I try to order with the new_total property /api/v2/pages/?type=sitepages.DetailPage&fields=additional_amount,new_total&order=-new_total isn't it supposed to work since it's already displayed and computed correctly?? and what can I do about this? -
Django wrong directories
My project has a core/template folder to place submit.html. I need to display some images. My project structure is like bellow: myproject static/images (my images) core/template (html files) I've also tryied core/template/images (jpg or png files) I've put some commands like these in settings file STATIC_URL = '/static/' MEDIA_URL = 'templates/images/' But it won't show up on submit.html page. I've tryied 3 ways for showing images but none will show them. This is what my terminal shows [21/Apr/2021 05:48:34] "POST /submit HTTP/1.1" 200 1054 [21/Apr/2021 05:48:34] "GET /static/images/coxinha.jpg HTTP/1.1" 404 1682 [21/Apr/2021 05:48:34] "GET /static/images/mini_coxinha.jpg HTTP/1.1" 404 1697 Not Found: /images/coxinha.png [21/Apr/2021 05:48:34] "GET /images/coxinha.png HTTP/1.1" 404 2230 -
Django problems loading static files
I am trying to add external JS file to my Django project. Unfortunately it doesn't work while I am trying to add it in many ways: In my template.html I have specified direct path: {% load static %} < script> src="{% static 'commerce/static/js/test.js' %}" < /script> it doesn't work. My settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] my layout.hmtl: {% load static %} <script src="{% static 'js/test.js' %}"></script> Depending on sources combination, I receive various output in terminal regarding status of loaded files: "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 304 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 200 0 "GET / HTTP/1.1" 200 5167 "GET /static/js/test.js HTTP/1.1" 404 0 Even if my 'test.js' is loaded correctly (HTTP status 200 or sometimes no information regarding test.js load status), my javascript functions doesn't work. In order to check if other static files are loaded I even tried to remove my CSS file from static folder and surprisingly (or not), after re-running my app it is still formatted. Although I left source for CSS unchanged in my layout.html: {% load static %} <link href="{% static 'css/styles.css' %}" rel="stylesheet"> Summarizing: I cannot manage … -
Django: No ReverseMatch. How to reverse to the previous URL?
I have a model class Client and the URL for this model object is <local_server>/object_id/ Where object_id is the id of the object of model Client. Now, when I am at this URL, there is a button on the page called Add Installment to add the installment for that particular Client. When I click on this button it takes me to the following URL: <local_server>/object_id/add_installment Now if I add the new installment, it works fine. But the Add Installment page has two buttons, Add and Cancel. I want that If I click on Cancel it should get back to the following URL: <local_server>/object_id/ And for that I have the following template for adding installment, where you can see the Cancel button. installment_form.html {% extends "client_management_system/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content_section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add New Installment</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-success" type="submit">Add Installment</button> <a class="btn btn-outline-danger" type = "submit" href="{% url 'client_details' object.id %}" >Cancel</a> </div> </form> </div> {% endblock %} In the Cancel button, client_details is the name of the URL <local_server>/object_id. I have written the object.id in that line, but when …