Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing name to a hidden field in Django form
I am trying to pass string to a hidden field scenario of a form whose data is stored in a database. The goal is to be able to retrieve extra information on client side without having it as another field of the form. This is my Model: class Person(models.Model): INDUSTRY_CHOICES = (('whatever','whatever'), ...) REGION_CHOICES = (('Europe', 'Europe'), ...) region = models.CharField(max_length=30, choices=REGION_CHOICES) industry = models.CharField(max_length=30, choices=INDUSTRY_CHOICES) uuid = models.CharField(max_length=50, blank=True, unique=True, default=uuid.uuid4) scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE,) def __str__(self): return "{}".format(self.uuid) My Form class PersonForm(forms.ModelForm): class Meta: model=Person scenario = forms.CharField(widget=forms.HiddenInput()) fields=['industry', 'region','scenario'] widgets = { 'scenario': forms.HiddenInput(), } My View def personforms(request): persons = Person.objects.all() if request.method == 'POST': filled_form = PersonForm(request.POST) if filled_form.is_valid(): created_person = filled_form.save() print(filled_form.cleaned_data['region']) created_person_pk = created_person.id filled_form = PersonForm() return redirect('/scenariopage', {'persons':persons}) else: created_person_pk = None return render(request, 'core/scenario-landing-page.html', {'personform':filled_form, 'created_person_pk':created_person_pk}) else: form = PersonForm() return render(request, 'core/scenario-landing-page.html', {'personform':form}) And my template <form action="{% url 'personform' %}" method="post" class="custom-form"> {% csrf_token %} {% for field in personform %} {% render_field field.industry class="form-control" %} {% render_field field.region class="form-control" %} {% render_field field.scenario value='{{ scenario.name }}' %} {% endfor %} <input type="submit" class="btn color-btn" value="Go to Scenario page" data-dismiss="gallery-item"/> </form> Questions I have: What I am doing … -
Modal form not submitting Django
I have a modal which does not submit. I'm using the Django base model. I think it could be a problem with the CSRF token since it's been throwing that error. I'm not even making it to the 'something went wrong' error message. I added something to catch form.errors, but it doesn't show any errors. The variables are being passed, but for some reason - it's not working. def voting(request): if request.method == 'POST': user=request.user if user.is_authenicated: price, created = Voting.objects.get_or_create( user=request.user, anonymous_user=False, object_id = Object.objects.get( objectid=request.POST.get('objectid') ), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) price.save() else: pass response_data = 'success' return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps({"message": "Something went wrong"}),content_type="application/json") Here is the html code: <div class="voting text-right"><small>See a problem?</small> <a onclick="thumbsup('{{ data.object.objectid }}'> <i class="fas fa-thumbs-up"></i> </a> <a data-toggle="modal" data-target="#feedback" data-object-id="{{ data.object.objectid }}"> <i class="fas fa-thumbs-down"></i> It does not work and does not submit. I keep getting a problem with the CRSF token as well. Here is the modal: <!-- Modal --> <div class="modal fade" id="feedback" tabindex="-1" role="dialog" aria-labelledby="feedback" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Feedback</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="feedback-form" action="/api/voting/" method="post"> {% csrf_token %} <input type="hidden" name="objectid"> <input type="hidden" … -
TemplateDoesNotExist on Django custom management command tests
I have the following custom management command: from django.template.loader import render_to_string from django.core.management.base import BaseCommand class Command(BaseCommand): args = "" help = """Validates models.""" def handle(self, *args, **options): ... message = render_to_string( "validation_email.html", context ) ... When I run it from the command line, it works as expected without an issue. However, when I try to test it with the following test case: from io import StringIO from django.core import mail from django.core.management import call_command from django.test import TestCase from my_app.management.commands import validate_models class TestValidateModels(TestCase): def test_successful_call(self): out = StringIO() cmd = validate_models.Command() call_command(cmd, stdout=out) self.assertEqual(len(mail.outbox), 1) It gives me the following error: django.template.exceptions.TemplateDoesNotExist: validation_email.html Am I missing something? Why the command works just fine from the command line, but generates template problems while running unit tests? Is there any tweak needed about the templates to be able to test Django custom management commands? -
ImportError: No module named skeleton.settings
I'm using django 1.8 and satchmo project. But after successful installation of satchmo project when I try to start the server it's showing me this error `Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@2/2.7.16_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named skeleton.settings` -
django form save but not redirect
I'm make a store using django, I want when a add a new product not redirect to the cart page, only want that after save the item , I can see the same page How I can make this -
Showing related instance on readonly popup in django admin
When you see the control (e.g. a dropdown) for a related field in a Django admin create/edit form for a Model, by default it comes with 2 icons, one for add a new instance and one for editing the selected instance. I know that the formfield's widget can be tweaked with the can_add_related and can_change_related flags to not show those icons, but I wonder: is there any out-of-the-box way to have a "view" icon that would display a pop-up just like the edit one but with all fields being displayed as readonly? (There's a can_view_related flag, but that's not what it's for) So far the "easiest" way I can think of is extending the admin/change_form.html template and seeing if I can somehow force all controls to be readonly when is_popup is set to true. -
AttributeError: 'NoneType' object has no attribute 'split' in Firefox only
I have recently started a project in Django and I don't have too much experience in this framework. However, everything is working fine so far, but I am getting these errors when I open the project's site in the browser. I am not sure what it is about, but I have noticed that this happens only in Firefox and only after opening any other site (particularly in my case Facebook or Gmail) in new tab, while navigating to any page on my project. Prior to the visit of these websites, everything is working fine without any error in the console. If I clear the cache of the browser after this happen and close the additional tabs, everything is back to normal until I reopen any of the websites again. Also, I have checked if this would be a case in Chrome and I have noticed that everything is working fine there, even when the mentioned websites are opened in new tab. Can anyone provide me more information on what would be the reason for these errors? Thanks Traceback (most recent call last): File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Users\Varangian\AppData\Local\Programs\Python\Python37-32\lib\wsgiref\handlers.py", line 274, … -
Django form not submitting without forms.py
I have a Django form that does not submit. I'm using the Django base model. The following is the view for the model. I think it could be a problem with the CSRF token since it's been throwing that error, but the form itself does not submit. I'm not even making it to the 'something went wrong' error message. def voting(request): if request.method == 'POST': user=request.user if user.is_authenicated: price, created = Voting.objects.get_or_create( user=request.user, anonymous_user=False, object_id = Object.objects.get( objectid=request.POST.get('objected') ), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) price.save() else: pass response_data = 'success' return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps({"message": "Something went wrong"}),content_type="application/json") Here is the html code: <div class="voting text-right"><small>See a problem?</small> <a onclick="thumbsup('{{ data.object.objectid }}'> <i class="fas fa-thumbs-up"></i> </a> <a data-toggle="modal" data-target="#feedback" data-object-id="{{ data.object.objectid }}"> <i class="fas fa-thumbs-down"></i> It does not work and does not submit. I keep getting a problem with the CRSF token as well. -
django: how to download a dataframe that is returned from a view
I have a form that takes an api key and an id and retrieves some data with a "load" button. That data is served as html in a template. Once the user sees the data that was retrieved, I would like them to be able to download the data as a CSV file by clicking a "download" button. What I've been trying to do is pass data as a context variable into a template, and then send that data on to another view that returns a download response from a view called "export". Perhaps there's a better way to do this? Sorry if this is a really dumb question. views.py def myview(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = WorkbenchForm(request.POST) # check whether it's valid: if form.is_valid(): context['form'] = form # Retrieve data from api [...] context['data'] = pandas_dataframe.to_html() context['file'] = pandas_dataframe.to_csv() return render(request, 'app/data.html', context) def export(request): response = HttpResponse(request, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=' + 'test.txt' return response data.html <body> <h1>Data</h1> <form action= "" method="post"> {% csrf_token %} {{ form.as_ul }} <input type="submit", value="Load"> </form> {% if data %} <h4>Data</h4> {{ data | safe }} <form … -
ㅁㄴㄹThe format is different when copying the input using django summer note
enter image description here For example If I copy this The result is output like this The problem is that the tab spacing line spacing is different =================================================================== const LOG_IN = 'LOG_IN' const LOG_OUT = 'LOG_OUT' const loginAction = { type : LOG_IN, data: { nickname:'제로초', }, } const logoutAction = { type:LOG_OUT, } =================================================================== this is code <div id="select-textarea-{{p.id}}" style="width:900px;">{{p.content2 | safe}}</div> ==================================================================== To copy and paste in its original format what should I do? -
What is the django rest framework suggested way, to render a serializer html template using Response() with Class Based View?
I'm defining a Class based view CRUD using Response() method, where I need to return my serialized data to a html template, but I haven't found a functional example using CBV (class based view) instead of FBS (function based view). I have read the DRF documentation about viewsets, requests and Response, and I found some ways to do that, but I'm not sure what is best suggested way according to my context. My project structure is as below: api core fixtures logs static templates users web In api folder I have my serializer and my api class: serializers.py class CustomDictionarySerializer(serializers.ModelSerializer): class Meta: model = CustomDictionary fields = ('__all__') api.py class CustomDictionaryViewSet(viewsets.ModelViewSet): queryset = CustomDictionary.objects.all().filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] serializer_class = CustomDictionarySerializer pagination_class = StandardResultsSetPagination urls.py router.register('api/customdictionary', CustomDictionaryViewSet, 'customdictionary') Then, in my web folder, I needed to render my serialized data, so I tried as below: views.py class CustomDictionaryView(View): def get(self, request, *args, **kwargs): queryset = CustomDictionary.objects.all() serializer = CustomDictionarySerializer(self.get_queryset, many=True) return Response(serializer.data,status=status.HTTP_200_OK,template_name='web/dictionary_get.html') ... (post,put and remove) But CustomDictionaryView didn't work by reason of this error: .accepted_renderer not set on Response My intention is to use CBV instead of FBV, so I can't use @api_view (that is … -
How to get all related objects from a reverse foreign key Django serializer (one-to-many)?
I have been trying to create a Trello-like clone and storing my 'Lists' and 'Applications' as separate models with a foreign key on my 'Applications' model to create a One-To-Many between Lists and Applications. I usually use Node and Sequelize and have been unsuccessful in trying to query my Lists and also returning all the Applications with the List's ID as the Applications foreign key. I suspect I am just missing something silly on my Serializers. I've tried a few things that broke the code, but now I just have it returning the List's fields like this: [ { "title": "My First List" }, { "title": "My Second List" }, ] when in reality what I really want back is something like: [ { "id": 1, "title": "My First List", "applications": [ { "id": 1, "company_name": "Spotify", "position": "Web Engineer", "date_applied": "2019-09-09", "application_id": "xv112_cv", "priority_level": "High", "company_contact_email": "jg@spotify.com", "notes": "Seems promising", "location": "New York", "status_list": "1" }, { "id": "2", "company_name": "Foursquare", "position": "Client Solutions Engineer", "date_applied": "2019-10-09", "application_id": "fsq_app_1", "priority_level": "High", "company_contact_email": "jdwyer@foursquare.com", "notes": "Interview on 9/29/19", "location": "New York", "status_list": "1" }, ] }, { "id": "2" "title": "My Second List", "applications": "applications": [ { "id": "3", "company_name": … -
How do I automate this sendinblue api?
Trying to automate the adding of contacts to sendinblue's api. The example given on their site shows adding a email and then adding it to a list in your account. I have tried fstrings and .format(email, industry, role) but for some reason it keeps throwing back errors. Heres what their website shows which works. import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\"someonesEmail97@gmail.com\",\"listIds\":[1,4],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers Here's what I tried import requests url = "https://api.sendinblue.com/v3/contacts" payload = "{\"email\":\f"{email}"\",\"listIds\":[f"{industry}",f"{role}"],\"updateEnabled\":false}" headers = { 'accept': "application/json", 'content-type': "application/json" } response = requests.request("POST", url, data=payload, headers=headers) I want this in the signup part of my site so it will grab their email thats been authenticated and add it to the appropriate list that I have set up. But what I get back from using fstrings is invalid syntax in the terminal pointing to the email field. I then tried .format and that didn't show any errors on the terminal but on the webpage I got this error back payload = "{\"email\":\{}\",\"listIds\":[{},{}],\"updateEnabled\":false}".format(email, industry, role) KeyError at /accounts/signup/activate/ "'email'" points to line that the payload is on. What am I missing? Thanks for reading -
How to handle return render in django function
def url_filter(request,x): if x<10: url=request.path[1:-9] elif x<100: url=request.path[1:-10] elif x<1000: url=request.path[1:-11] else: url=request.path[1:-12] return url def form_valid(form,request,url): if form.is_valid(): form.save() if request.user.is_staff: messages.success(request, f''+url+' List has been updated!') else: messages.warning(request, f'You do not have Admin access!') else: print(form.errors) context={ "form":form, "form_name":url, } return render(request,'movies_list/list_create.html',context) @login_required def Award_list_update(request,award_id): obj=get_object_or_404(Award_list,award_id=award_id) url=url_filter(request,award_id) form=Create_Award_list_form( data=(request.POST or None), files=(request.FILES or None), instance=obj, ) form_valid(form,request,url) I want to use same template for multiple views so,i decleared a seprate function form_valid for this but i dont know how to handle the return render function. -
How to download a csv file from django docker container
I have an mounted django app using docker-compose. I also have generated a csv file in the server django app directory and inside the docker container. server django directory /restapi |*filename.csv |*app1 |*app2 inside docker container directory /django |*filename.csv |*app1 |*app2 i already tried setting up a static absolute path for both server and docker directory, but i still couldn't download the csv file. response = HttpResponse(content_type='text/csv') django_root_path = '/django' file_path = '{}/myfilename.csv'.format(django_root_path) logger.info(file_path) response['Content-Disposition'] = 'attachment; filename=file_path' response.write(u'\ufeff'.encode('utf8')) return response -
Django ValueError: Missing staticfiles manifest entry, but the manifest appears to show the entry
On a Django 1.11 app deployed to Heroku. When loading the root URL / (and I presume when Django gets to {% static 'angular/angular.min.js' %} in the homepage.html template) I get the following error: ValueError: Missing staticfiles manifest entry for 'angular/angular.min.js' File "django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "homepage/views.py", line 87, in homepage "latest_python3": Version.objects.filter(supports_python3=True).select_related("package").distinct().order_by("-created")[0:5] File "django/shortcuts.py", line 30, in render content = loader.render_to_string(template_name, context, request, using=using) File "django/template/loader.py", line 68, in render_to_string return template.render(context, request) File "django/template/backends/django.py", line 66, in render return self.template.render(context) File "django/template/base.py", line 207, in render return self._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/loader_tags.py", line 177, in render return compiled_parent._render(context) File "newrelic/api/function_trace.py", line 60, in dynamic_wrapper return wrapped(*args, **kwargs) File "django/template/base.py", line 199, in _render return self.nodelist.render(context) File "django/template/base.py", line 990, in render bit = node.render_annotated(context) File "django/template/base.py", line 957, in render_annotated return self.render(context) File "django/template/defaulttags.py", line 411, in render return strip_spaces_between_tags(self.nodelist.render(context).strip()) … -
Django category didn't work corrctly href not work
I have made a script to display all posts in a categroy so, when I try to open the single category it didn't open the page and show the article page, I've followed a tutorial for makeing this code, the link is: https://www.youtube.com/watch?v=o6yYygu-vvk . Can someone help me plz? Models.py from django.db import models from django import forms from django.contrib.auth.models import User from django.urls import reverse # Categorie class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True) def get_absolute_url(self): return reverse("blog:CategoryList", args=[self.slug]) def __str__(self): return self.name # Articles class Article(models.Model): class Meta: verbose_name = 'Articolo' verbose_name_plural = 'Articoli' ''' Classe per creare articoli generali con media ''' title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE,) category = models.ForeignKey (Category, on_delete=models.CASCADE) desc = models.CharField('Descrizione', max_length=10000, blank=True) text = models.TextField('Testo', max_length=10000, blank=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) class Meta: # Order post by date ordering = ['-data',] def __str__(self): return "Crea un nuovo articolo" Views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import render … -
type str doesn't define __round__ method/how to grab form fields ? django and cropper.js?
I have a Django form where users would upload images and sometimes crop only parts from it so I used cropper javascript to grab the coordinates but the problem is the data received is treated as strings here's how i grab data of the form /* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */ $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); $("#formUpload").submit(); }); Forms.py class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) and this is how i get the data from the form if form.is_valid(): image = form.save(commit=False) x = request.POST.get('x') y = request.POST.get('y') w = request.POST.get('width') h = request.POST.get('height') but it always returns this error type str doesn't define round method so what i get is that I'm grabbing the data as strings instead of floats as it's saved in the form feild so how can i grab the data right ? -
Stripe Connect Express - Callback URI for Localhost Doesn't Seem to Work
I'm trying to set up a platform that uses Stripe, and since I need marketplace type of setup I'm using Connect, which does payments and payouts. I'm testing on local and the redirect URLs I've tried don't seem to work. After registering with Stripe, I'm still taken to their default redirect URI, which says: Congrats, you're almost done setting up your application! After connecting with Stripe, your users will be redirected to a page of your choosing (this is just the default). Make sure to change the test redirect URI under your application settings to something that makes sense on your own server (or localhost). However, I have tried all of these as redirect URIs in my Stripe Connect Dashboard, under the 'testing' option: http://localhost:8000/test-stripe/connect/default/oauth/test http://localhost:8000/test-stripe/oauth/callback http://localhost:8000/test-stripe/ These are supposed to be the URI that Stripe redirects back to on my site, with an added parameter at the end. Am I missing something? I find their documentation labyrinthine, as you have to click on link after link to get one part of their solution working, and then see if you can find your way back to where you left off. Maybe I missed something along the way. Thanks in advance … -
Channel Worker crash: how do some task?
For debugging purposes, I need to send an email when some Channel Workers stops for an error. I don't find a closure method in the SyncConsumer or AsyncConsumer. channels==2.2.0 channels-redis==2.4.0 -
How to use instance object with request.FILES and request.POST
views.py form=Create_Award_list_form(request.POST or None,instance=obj,request.FILES) if form.is_valid(): form.save() using request.FILES django doesn't let me to use instance object and using instance django doesn't let to use request.FILES. -
Cannot auth users in django
I have a problem with my code in django. I can't login user, I have form, display users but if i write password is ignored, there is any authentication and when i click submit button i go to next site with any authentication. And when entering a password user or not does not matter as if the password was not checked. I only see in comment in html all list users and their password from db when I do examine the login page. Please look at my code. login.html {{context.error}} {%else%} <form action="../logistics/choosework/" method="post"> {% csrf_token %} <select list="employees" id="opr_login" name="opr_login"> <option hidden="">Login</option> {% for login in peoples %} <option value="{{login.opr_login}}">{{ login.opr_name }} {{ login.opr_surname }}</option> {% endfor %} </select> <br> <input placeholder="Password" value="{{login.opr_pass}}" type="password" id="opr_pass" name="opr_pass"> <br> <input type="submit" value="login" /> </form> {% endif %} <hr> dbmodel_index.py class Peoples(models.Model): opr_login = models.CharField(db_column='OPR_LOGIN', primary_key=True, max_length=50) # Field name made lowercase. opr_name = models.CharField(db_column='OPR_NAME', max_length=255, blank=True, null=True) # Field name made lowercase. opr_surname = models.CharField(db_column='OPR_SURNAME', max_length=255, blank=True, null=True) # Field name made lowercase. opr_pass = models.CharField(db_column='OPR_PASS', max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'PEOPLES' views.py peoples = dbmodel_index.Peoples.objects.all() context={} if request.method == 'POST': opr_login = request.POST['opr_login'] opr_pass = … -
How to run django server and show it inside a NWjs application
I want to use Django Rest Framework to provide an API for saving data to a sqlite3 database, with the frontend made in React. And I want it to be a NW.js app. I have used succesfully Django and react. It works correctly. But when I try to save a file, it does not let the user choose a directory. It goes to the default "Downloads" in windows. The option to let the user choose a custom directory is something that can be done with NW.js. I used the file-saver and it saves the file but does not let the user choose a directory, wich is very important var FileSaver = require('file-saver'); var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"}); FileSaver.saveAs(blob, "hello world.txt"); I expect the user to be shown a window similar to the FileUpload type, but it just downloads it. -
Django findstatic: "No matching file found" but the file is there
On a Django 1.11 app deployed to Heroku. The Django management command findstatic is saying that it cannot find a file angular.min.js even though the file appears to be in a folder findstatic is checking. $ heroku run python manage.py findstatic --verbosity 2 angular.min.js Running python manage.py findstatic --verbosity 2 angular.min.js No matching file found for 'angular.min.js'. Looking in the following locations: /app/static /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/static /app/.heroku/python/lib/python3.6/site-packages/django_extensions/static /app/.heroku/src/django-floppyforms/floppyforms/static /app/.heroku/python/lib/python3.6/site-packages/rest_framework/static $ heroku run ls /app/static/angular/ Running ls /app/static/angular/ angular.min.js controllers.js So it appears that angular.min.js is at /app/static/angular/. Why does findstatic not find it? Relevant part of settings.py: I followed Heroku's instructions for service Static Files with Django: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"),] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ...others here too ] Also, whitenoise in requirements.txt Related questions that did not solve my problem: Django findstatic : No matching file found (STATICFILES_DIRS appears to me to be correctly set up) django findstatic not looking in every directory (In my situation, findstatic appears to be looking in the correct parent directory) -
Password Change URL in Django is accessible by directly entering URL, but fails when clicking on "Change Password" button
I am making a website based on William S. Vincent's "Django for Beginners." In the project I am building I have a homepage, with a drop-down menu that includes, among other options, a "Change Password" selection. When I go directly to the URL 127.0.0.1:8000/users/password_change/ I arrive at the correct page, but clicking the "Change Password" option gives me the following error: "Using the URLconf defined in newspaper_project.urls Django tried these URL patterns in this order: 1. admin/ 2. users/signup/ [name='signup'] 3. users/login/ [name='login']...11. articles/ 12. [name='home']. The current path, users/password_change/{% url 'password_change' %}. didn't match any of these." Below are the relevant sections of code: /Desktop/news/templates/base.html {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu"\ data-toggle="dropdown" aria-haspopup="true" aria-expanded\ ="false"> {{ user.username }} </a> <div class="dropdown-menu dropdown-menu-right"\ aria-labelledby="userMenu"> <a class="dropdown-item" href="{% url 'article_list' %}">Entries</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'password_change' %}">Change password</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="{% url 'logout' %}"> Log Out</a> /Desktop/news/users/urls.py from django.urls import path from .views import SignUpView urlpatterns = [ path('signup/', SignUpView.as_view(), name='signup'), ] /Desktop/news/users/views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = …