Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't establish connection between django and MS SQL server
i have a django project that make a connection between django and MS SQL server the problem is that once the system run it display the below error : djago.db.utils.operationalError:('08001','[08001] [microsoft][odbc sql server driver]neither dsn nor server keyword supplied (0) (sqldriverconnect); [08001] [microsoft][odbc sql server driver] Invalid connection string attribute (0)') sql server credentials: server name : VSQLSERV authentication: windows authentication views.py from django.shortcuts import render import pyodbc # from .models import Artist # Create your views here. def connect(request): conn = pyodbc.connect( 'Driver={SQL Server};' 'Server=ip address;' 'Database=I-Base_beSQL;' 'Trusted_Connection=yes;' ) cursor = conn.cursor() c = cursor.execute('SELECT "first name" FROM Person WHERE id = 2 ') return render (request,'connect.html',{"c":c}) connect.html {% for row in c %} {{ row }} {% endfor %} -
Implement Forgot Password/Email Verification django rest with ReactJS
I want to implement forgot password or email verification with django and react, To implement forgot password I used django rest auth.Here below urls are: url( r'^rest-auth/password/reset/$', PasswordResetView.as_view(), name='password_reset', ), url( r'^rest-auth/password/reset/confirm/' r'(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), I have successfully hit the request to first url from my react js front end,and I also received the email with token and uid, but the link redirects me to django rest native UI however I want to be in react framework UI. So how can I implement this? is there any suitable way to implement forgot password with react and django as it is not done by django rest auth because the flow of react front end disturbs. -
Simple HTML forms Vs Django forms in django (Select in django forms not updating on refresh)
I have a drop down list of trainers. I am using this get the html form. class AssignTrainerForm(forms.Form): TRAINER = [] for use in User.objects.filter(Q(role='trainer') & Q(is_active=True)): opt = use.username + ' (' + use.first_name + ' ' + use.last_name + ')' TRAINER.append((opt, opt)) trainer = forms.CharField(widget=forms.Select(choices=TRAINER, attrs={'class': 'form-control'})) Problem is I have also a functionality of delete trainer or add trainer. If I delete or Add trainer, drop down is not updating when I refresh the page. I have to restart the server. But If I use simple HTML code (No django form) in html template like: <select class="form-control" name="trainer"> {% for trainer in trainers %} <option>{{ trainer.username }} ({{ trainer.first_name }} {{ trainer.last_name }})</option> {% endfor %} </select> this is giving expected result because on refresh list is coming from DB. Is there anyway I use django forms and get refreshed data every time I refresh page, -
Internal server error in ubuntu server running django and apache server
i have an Ubuntu server 18.04 with Apache service and Django. it was working fine till today that i get an error Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. i reboot the server and also update and upgraded it and i checked /var/log/apache2$ cat error.log and i have noticed the error: [wsgi:error] [pid 3321:tid 139988754757376] [client myfirewall ip:36250] Truncated or oversized response headers received from daemon process wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() can some one help me to solve this error thank you all -
Parallel request (Django rest framework)
Current I have 3 API's. Main one, and two supporting. Main makes request to both of them, then waits for response, then handles both responses when they are received. Receiving response from the first one takes 25 seconds. Receiving response from the second one takes 30 seconds. So it takes 55 seconds in total to receive response from both. response_1 = call_request_to_first( request_data ) response_2 = call_request_to_second( request_data ) handle_both_responses( response_1, response_2 ) As you can see, the handle_both_responses function will be called after 55 seconds since call_request_to_first called. That works but it's super inefficient. Goal I want to call to both API's in parallel. response_1, response_2 = call_concurrent_request_to_both( request_data ) handle_both_responses( response_1, response_2 ) So it would take 30 seconds in total instead of 55 seconds. What would be the best option for me to achieve my goal considering the context I provided above ? Thanks in advance !!! -
How to pass 'pk' or some id dynamically with api call in react
I'm tring to make a edit invoice button which when called opens a form in and let users edit its choices which further gets saved in database but I cannot figure out how to pass the 'pk' with my url. For example form with pk id 1 is of user 1 and when I call api it should specificly change the invoice of user ID 1. import { Button, Card, CardBody, CardHeader, Col, Form, FormGroup, Input, Label, Row, } from 'reactstrap'; import GooglePlacesAutocomplete from 'react-google-places-autocomplete'; import {editInvoice, getInvoiceDetails} from "../../../helpers/api"; export default () => { // // var len = window.location.href.length; // var id = window.location.href[len-1]; //TODO THIS IS NOT THE REACT METHOD TO FETCH ID FROM THE URLT const [form, setForm] = useState({ 'id': '', 'invoice_number': '', 'invoice_date': '', 'invoice_due_date': '', 'invoice_place_of_supply': '', 'invoice_destination': '', 'invoice_destination_address': '', 'invoice_destination_pincode': '', 'invoice_gst': '', 'invoice_salesperson': '', 'invoice_lr_number': '', 'invoice_vehicle_placement_date': '', 'invoice_vehicle_number': '', 'invoice_service_month': '', 'invoice_item_details': '', 'invoice_rate': '', 'invoice_tax': '', 'invoice_amount': '', 'invoice_quiz': '', 'invoice_owner': '', 'invoice_quantity': '', 'lr_number': '', 'billing_party_name': '', 'origin_address': '', 'origin_pincode': '', 'vehicle_placement_date': '', 'vehicle_number': '', 'item_details': '', 'item_quantity': '', 'total_amount': '', 'tax': '', }); useEffect(() => { const getNetwork = async () => { const invoice_details = … -
Media files wont show up with nginx, but static files will
I have a problem with configuring my nginx. My media files are not showing up. settings.py https://i.udemycdn.com/redactor/raw/2019-08-25_20-42-57-734501b7da3444cb1b19c6cf85436e1f.jpg nginx site config file: https://i.udemycdn.com/redactor/raw/2019-08-25_20-46-02-1c0e649125c7437ecfcfa6be26ad064b.jpg website: https://i.udemycdn.com/redactor/raw/2019-08-25_20-43-19-e5147293f6f71e071ace7ed5290ca109.jpg a part of nginx/error.log: 2019/08/25 20:28:10 [error] 28230#28230: *1 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184012.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184012.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/" 2019/08/25 20:28:10 [error] 28230#28230: *4 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184214.jpg" failed (2: No such file or directory), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184214.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/" 2019/08/25 20:28:10 [error] 28230#28230: *5 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184328.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184328.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/" 2019/08/25 20:28:20 [error] 28230#28230: *5 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184328.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184328.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/admin/web_data/photo_gallery/2/change/" 2019/08/25 20:31:39 [error] 28230#28230: *13 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184328.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184328.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/admin/web_data/photo_gallery/2/change/" 2019/08/25 20:41:29 [error] 28230#28230: *14 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184012.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184012.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/" 2019/08/25 20:41:29 [error] 28230#28230: *18 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184328.jpg" failed (13: Permission denied), client: 78.153.61.113, server: 104.248.83.156, request: "GET /media/image/20190816_184328.jpg HTTP/1.1", host: "104.248.83.156", referrer: "http://104.248.83.156/" 2019/08/25 20:41:29 [error] 28230#28230: *19 open() "/home/admin_aljaz/patricija_website/media/image/20190816_184214.jpg" failed … -
django slugfield support another language
I want to make support Django SlugField with another language like Bengali. But i find some problem my django slug field not taken another language. settings.py ALLOW_UNICODE_SLUGS = True models.py class Article(models.Model): slug = models.SlugField(max_length=255, unique=True, allow_unicode=True) My input is: আমার-সনার-বাংলা But Show this massage: Enter a valid 'slug' consisting of Unicode letters, numbers, underscores, or hyphens. Screenshot of django admin slug field -
Multiple join in django?
I have four models Quiz, Assignment, Question and Option in django 2.1. I want to retrieve Questions and options specific to a quiz. I tried with the code **a=Quiz.objects.all() print(a[0].assignment_set.all())** By using the above code am getting the assignment set [{'id': 1, 'questionValue': 1, 'Question_id': 1, 'Quiz_id': 1}, {'id': 2, 'questionValue': 1, 'Question_id': 2, 'Quiz_id': 1}] but i don't know how to get the respective options for the question. My models class Quiz(models.Model): class Question(models.Model): name = models.CharField(max_length=30) description=models.TextField() Category=models.ForeignKey(Category,on_delete=models.CASCADE) class Option(models.Model): name = models.TextField() Question=models.ForeignKey(Question,on_delete=models.CASCADE) value= models.IntegerField() class Assignment(models.Model): questionValue=models.IntegerField() Question=models.ForeignKey(Question,on_delete=models.CASCADE) Quiz=models.ForeignKey(Quiz,on_delete=models.CASCADE) I want to get in the following format "assignmentSet": [ { "Question": { "id": "1", "name": "Q 1", "optionSet": [ { "name": "option 1" }, { "name": "Option 2" }, { "name": "Option 3" }, { "name": "Option 4" } ] } }, { "Question": { "id": "2", "name": "Q 2", "optionSet": [ { "name": "Option 1" }, { "name": "Option 2" }, { "name": "Option 3" }, { "name": "Option 4" } ] } }] -
"what is the type of variable with single elements and followed by comma ?"
I'm trying to find the type of a variable and followed by comma,where i expected the output to be int or string but the result is tuple I'm trying to find the type of a variable and followed by comma,where i expected the output to be int or string but the result is tuple x=1, print(type(x)) I expected the output to be , but the actual output is -
django How to make a radio button form with fk relationship choiceset
In the django tutorial part 4, a form is written in the template. It is a collection of radio buttons which allow one to vote on a question. Its not a model form as neither the questions or choices (the 2 models for the app) are being modified/ added to, but both models are being used in the form. Questions, and their set of choices (choice_set). How does one implement this with forms instead of manually as in the tutorial? This is what I have as the starting point for my form: from django import forms from .models import Question, Choice class VoteForm(forms.Form): def __init__(self, *args, **kwargs): super(VoteForm, self).__init__(*args, **kwargs) question = Question.objects.get(pk=question_id) self.fields['choices'] = forms.ChoiceField( choices=[(c.id, str(c.choice_text)) for c in question.choice_set.all()] ) My view: def vote(request, question_id): form = VoteForm() if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): selected_choice = form.cleaned_data['choices'] return HttpResponseRedirect(reverse('polls:results', args = (question_id,))) My template: {% block content %} <h3>Question: {{ question.question_text }}</h3> <p>Vote for one of the following choices: </p> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-outline-info">Vote</button>&nbsp; </form> {% endblock %} I am unsure of: 1.) How to grab the Question model in the … -
getting undefined after ajax get call to fetch from postgres db in django
I am trying to fetch data from postgres table by clicking a button in the django template page and the fetched data from db should be populated into another div. For the same, I am using Ajax get call to fetch the data from DB, but I am facing problem that the value is shown as undefined. With the Ajax call if I populate the target div with the below, it is working. $('#childContainer').html(10 + Math.floor(Math.random()*91)); But when I try to fetch the data from table, I am getting undefined. Here is the code which I have written:- views.py:- def index(request): distinctenvapp = Env_app.objects.values('environment_name').distinct() return render(request, 'envconfigmgmt/index.html', {'distinctenvapp' : distinctenvapp}); def get(self,request, *args, **kwargs): if self.request.is_ajax(): return self.ajax(request) def ajax(self, request): response_dict= { 'success': True, } action = request.GET.get('action','') if action == 'get_appnames': env_id = request.GET.get('id','') if hasattr(self, action): response_dict = getattr(self, action)(request) envappname = Env_app.objects.get(environment_name='env_id') response_dict = { 'application_name':envappname.application_name } return HttpResponse(simplejson.dumps(response_dict), mimetype='application/json') index.html:- <div><center><table id="t1"><tr> {% for obj in distinctenvapp %} <td> <button id="{{ obj.environment_name }}"> {{ obj.environment_name }} </button> </td> {% endfor %} </tr></table></center></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $env_id = $(this).attr('id') $.ajax({ type: "GET", data: { action: "get_appnames", id: $env_id }, success: function(data){ $("#childContainer").html("<strong>"+data.application_name+"</strong>"); console.log(data); } … -
How to save new user data in admin after email confirmation?
I have a problem. Whenever someone new registers himself in my site, an email confirmation send to him. But before confirmation, his user information is adding in admin Users. I want it to add it in admin Users after confirmation not before. views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your Account.' message = render_to_string('users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/confirm_email.html') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() return render(request, 'users/confirmed_email.html') return HttpResponse('Activation link is invalid!') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils import six class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return ( six.text_type(user.pk) + six.text_type(timestamp) + six.text_type(user.is_active) ) account_activation_token = TokenGenerator() -
Django connect to MSSQL
Hi I am trying to connect from django to mssql server. I installed 1 : pip install django-mssql 2 : pip install pywin32 after that i changed the database inside setting.py => DATABASES = { 'default': { 'NAME': 'TMSWEB', 'ENGINE': 'sql_server.pyodbc', 'HOST': '192.168.72.1\MSSQLSERVER5', 'USER': 'sa', 'PASSWORD': 'pwd', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } } and then i check like that=> 2: python manage.py makemigrations django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') What i am still need to do? Please help me. my django version : 2.1.11 -
Pass additional context variable data into allauth views using class based views
Not sure how to pass additional context data into various allauth forms which includes my own templates. For my own views I'm using get_context_data() which is working fine. I'm including small templates into a master template such as a header, footer, side bar etc. Everything is working except when allauth kicks in such as login, logout, email confirmation window etc my context variables are not passed so images in my left side bar are not showing up but allauth works fine. I've tried a few things but I believe the ideal option is to inherit from allauth views for that function such as login, password reset, confirm email etc, supply my own context variable data. In my accounts.views.py, I'm expecting this to fail as the template doesn't exist but the form still shows up and the UserProfile image isn't being shown in the left side bar. from allauth.account.views import ConfirmEmailView class EmailViewExt(ConfirmEmailView): template_name = "account/signup_alternate1.html" def get_context_data(self, **kwargs): context = super(ConfirmEmailView).get_context_data(**kwargs) context['userprofile'] = UserProfile.objects.get(user=self.request.user) return context In my template left_bar_base.html which is included from my overridden allauth template. {% if userprofile.avatar_picture %} <img src="{{ userprofile.avatar_picture.url }}" class="card-img-top" alt="..."> {% else %} <img src="{% static 'placeholder.png' %}" class="card-img-top" alt="..."> {% endif … -
How can I make my Heroku hosted Dash only be seen when embedded in my site?
my company hosts its website in Rackspace. I've built a Dash app which we have embedded through an iframe in our site, for our own users. The problem is that they could get the iframe url and open it outside our website, how can I avoid that? Heroku is nice because it's easy and it provides heroku-redis which we use. We looked into AWS and, even not knowing if AWS would help, apparently those are not managed servers and we don't want to manage them ourselves. Heroku Private Spaces is just too expensive for us. We already used jQuery and Ajax to make the access to the url harder, but that's not enough. Making an IPs whitelist apparently is not secure enough. I could make just a Flask or Django app instead of a pure Dash if it helped. I thought of making a dummy user and the logging in sending a POST request from our site. Would that be secure enough? Could the users see the dummy username and password? How about a token. I've been doing some research and I'm still not sure if a JWT would help here. Thank you in advance -
Use jwt authentication for Django view?
I see many blogs prefering jwt over session based authentication. However, django is still session based, and doesn't have option to switch to jwt auth backend. I think it can be achieved by defining custom JwtMiddleware (whose job is to populate request.user) But there's too little online resources describing the process (How add Authenticate Middleware JWT django? is only thing I found) Is it a frowned upon to do jwt authentication for django views? -
Why deleting session record in django server cache doesn't make me logout?
I store session in redis cache SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default" I delete the record from cache, the key is "django.contrib.sessions.backends.cache"+the session key. But I am still logged in after I reload the page, just got a new session. Why I am not logged out after I remove the session from the cache? -
Cannot print image full path because of django.core.exceptions.SuspiciousFileOperation
I want to print / get the full path of an ImageField in django photos = Photo.objects.all() for photo in photos: print(settings.MEDIA_ROOT + photo.image.path) break Bu I get this: print(settings.MEDIA_ROOT + photo.image.file) File "/home/juan/Desktop/juan/dev/yas/yas_django/venv/lib/python3.6/site-packages/django/db/models/fields/files.py", line 43, in _get_file self._file = self.storage.open(self.name, 'rb') File "/home/juan/Desktop/juan/dev/yas/yas_django/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 36, in open return self._open(name, mode) File "/home/juan/Desktop/juan/dev/yas/yas_django/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 224, in _open return File(open(self.path(name), mode)) File "/home/juan/Desktop/juan/dev/yas/yas_django/venv/lib/python3.6/site-packages/django/core/files/storage.py", line 323, in path return safe_join(self.location, name) File "/home/juan/Desktop/juan/dev/yas/yas_django/venv/lib/python3.6/site-packages/django/utils/_os.py", line 46, in safe_join 'component ({})'.format(final_path, base_path)) django.core.exceptions.SuspiciousFileOperation: The joined path (/images/photos/2013/3/image_1) is located outside of the base path component (/home/juan/Desktop/juan/dev/yas/yas_django/media) What is going on here? This is in my settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' The same happens if I print image.url or image.file. What I want to get is the full path to the image in order to open it with a third party lib. -
Django: Building Regions with django-countries with a function?
I try to figure out how to build or form groups by using django-countries - so far it seems convenient. However i would like to build individual Regions by providing a list. For instance to group all countries in the EU. In my Example is use a small list named eu_list. My idea was whenever something matches to this list add country.region to my model context. However it seems i have the wrong approach to my function def region. models.py class Person(models.Model): name = models.CharField(max_length=40) country = CountryField() def region(self): incoming = self.country.code eu_list = ['DK','CZ','DE','ES'] eu_match = ['EU', ('European Union')] for incoming in eu_list: print('EU') return eu_match def __str__(self): return self.name def get_absolute_url(self): return reverse("datainput:person_detail", kwargs={"id": self.id}) -
CORS error calling AWS API Gateway from Django
I built a simple RESTful endpoint using AWS Lambda and API gateway. API Gateway has CORS enabled, and the client is sending the proper headers as described here The client app was built in Django and uses JQuery: $.ajax({ type: 'GET', url: baseUrl, crossDomain: true, contentType: 'application/json' }) Also, the Lambda function itself returns the following payload: return { 'statusCode': 200, 'headers': { 'Content-Type': 'application/json', "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" }, 'body': json.dumps(json_response) } Chrome is still throwing a CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource Am I missing something? -
Celery cannot retrieve active tasks on Heroku
I am trying to deploy an app on Heroku and I am using Celery and Redis to manage background tasks. I currently have a background task that collects data via FTP and puts it in the database. I also have a loading page that periodically refreshes until the task completes. However, I cannot retrieve the list of active tasks (inspect from celery.task.control returns None). This problem only occurs on Heroku, but everything works on my personal machine. Earlier, this was also occuring on my machine, but I fixed this by downgrading Kombu to 4.5.0. However, changing requirements.txt did not make a difference on Heroku. I also tried checking the value of os.environ['REDIS_URL'], and looks correct. relevant code from settings.py CACHES = { "default": { "BACKEND": "redis_cache.RedisCache", "LOCATION": os.environ['REDIS_URL'], } } CELERY_BROKER_URL = os.environ['REDIS_URL'] CELERY_RESULT_BACKEND = os.environ['REDIS_URL'] CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery.py: from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'genome.settings') os.environ.setdefault('REDIS_URL', 'redis://localhost:6379/0') app = Celery('genome_app') app.conf.update(BROKER_URL=os.environ['REDIS_URL'], CELERY_RESULT_BACKEND=os.environ['REDIS_URL']) app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) requirements.txt django<=2.2.2 gunicorn<=19.6.0 requests>=2.22.0 celery==4.3.0 kombu==4.5.0 redis>=3.2.1 django-redis-cache>=2.0.0 django-celery-beat>=1.5.0 django-celery-results>=1.1.2 (in the app's views.py) from celery.task.control import inspect ... i = inspect() … -
why my static file is not loading in django?
I paste a pdf file in my static folder and the file is not getting loaded. name of the file is np.pdf. previously I had resume.pdf and it was working fine. but after trying np.pdf(which is not working) i edited the code to resume.pdf again but when i'm clicking the resume link- the browser opens a pdf download pop up. again i edited to np.pdf- run the server again- not showing any error again a pop up of resume.pdf's download. notes: I am new to django. html code- <a class="nav-item nav-link" href="{% static 'np.pdf' %}">Resume</a> -
Can I pass a context variable in a URL pattern for django.contrib.auth views?
The official docs for Django LoginView states that: This template gets passed four template context variables: form: A Form object representing the AuthenticationForm. next: The URL to redirect to after successful login. This may contain a query string, too. site: The current Site, according to the SITE_ID setting. If you don’t have the site framework installed, this will be set to an instance of RequestSite, which derives the site name and domain from the current HttpRequest. site_name: An alias for site.name. If you don’t have the site framework installed, this will be set to the value of request.META['SERVER_NAME']. For more on sites, see The “sites” framework. I know I can pass attributes like template_name and redirect_field_name in the URL pattern, but can I pass/change the above context variables sent too? path('login/', auth_views.LoginView.as_view( template_name='accounts/login.html', redirect_field_name='next'), name='login'), -
Removing All Packages With Defunct Dependees in PIP
I am wondering if there is a way to uninstall packages in PIP including those that are not listed in the requirements.txt but which were installed as dependencies of those that are. For example, suppose I have Django==2.1 line in requirements.txt. When running pip install -r requirements.txt, the above will instruct PIP to install many extra packages on which Django depends. However, if I then execute pip uninstall -r requirements.txt, the Django package will be uninstalled, but PIP will retain many of its now unused dependencies. My question is how to go about cleaning those up nicely. Is there a way to make PIP preserve and consider history explicitly? If the thing which forced PIP to install a package is being uninstalled, it appears that we should also be able to flag it to wipe its now defunct dependencies.