Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
With Apache's ProxyPassMatch, how do I pass on only part of my URL?
I'm running Apache 2.4 with a Python 3 / Django 3 app, both in Docker containers. If my Apache container gets a request with "/api", I would like to redirect that request to the Python container. So if my Apache request is http://localhost:9090/api/states/US I would like to redirect to the Python container using the URL http://web:8000/states/US In my virtual host file I have <VirtualHost *:80> ServerName directory.example.com ProxyPassMatch ^/api http://web:8000/(.*) ProxyPassReverse ^/api http://web:8000/(.*) But when I make the request for "http://localhost:9090/api/states/US", I get this in my Docker logs maps-web-1 | Not Found: /(.*)/api/states/US maps-apache-1 | 172.23.0.1 - - [30/Jun/2022:20:23:49 +0000] "GET /api/states/US HTTP/1.1" 404 6128 So evidently my ProxyPassMatch is not correct. How do I set that up properly? -
In a Django Forms drop-down list, how do I show text accessed via a foreign key?
I have code to edit a table "instruments", which has a foreign key to another table 'instrumenttype'. I'd like to show a drop-down list showing the text values from the instreumenttype table. My problem is that the drop-down list shows "InstrumentType object(n)" instead of the instrument type description from the other table. The update works fine; when I get the selected value and update the instruments table, the correct key id is put in. Here is the form: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from instruments.models import Instrument from instrumenttypes.models import InstrumentType # Form used to edit the data pertaining to a specific instrument class EditInstrumentForm(forms.ModelForm): instrumenttype = forms.ModelChoiceField(queryset=InstrumentType.objects.all()) class Meta: model = Instrument fields = ('instrument', 'dateAdded', 'dateRemoved', 'nickname', 'serialNo', 'status', 'instrumenttype') Here is the view snippet: def update_instrument_view(request, id=id): instrument = get_object_or_404(Instrument, id=id) if request.method == 'POST': form = EditInstrumentForm(request.POST, request.FILES, instance=instrument) if form.is_valid(): instrument.instrument = form.cleaned_data.get('instrument') instrument.dateAdded = form.cleaned_data.get('dateAdded') instrument.dateRemoved = form.cleaned_data.get('dateRemoved') instrument.nickname = form.cleaned_data.get('nickname') instrument.serialNo = form.cleaned_data.get('serialNo') instrument.status = form.cleaned_data.get('status') instrument.instrumenttype = form.cleaned_data.get('instrumenttype') instrument.save() messages.success(request, 'Your instrument has been updated.') return redirect('instrument_details', instrument.id) else: form = EditInstrumentForm(instance=instrument) messages.error(request, 'Issue updating data.') return render(request, 'instrument_update.html', {'form': form, 'instrument':instrument}) else: form = … -
Is it possible to change the title of a Django group?
In the django admin when one adds groups to a user, if one hover over the group ("Freelander" in the image below), it has a toole tip (html title) that just says "Freelancer". Is it possible to add some custom text explaining what the group is for (i.e. change the title of the option element)? Here the HTML of an the option: <option value="1" title="Freelancer">Freelancer</option> The best I can come up with is to extends the django admin template and add some JavaScript to change it by looking for the string and replacing them, but this is very "hacky" -
Django static CSS file not linking to html document
I am trying to link a css file to my html inside a django project but it does not seem to be linking. base.html <head> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'myApp/styles.css' %}"> </head> my folder structure [1]: https://i.stack.imgur.com/3nuwE.png -
Execute gcloud commands from python API
How can I send gcloud commands through python, I have been researching about the connection that can be made through python but I have not been able to find clear information about the process. For example what to send the command: gcloud info What it would do is to receive the information and display it in an interface but I have not been able to make the connection with the project created in google. At the moment the way to make the connection to the google shell is through subprocesses in python, here is an example: import subprocess def hello_world(request): if request.method=='GET': data = subprocess.call('gcloud info',shell=True) print(data) return true *In the case of the command presented, it is only to show that I am looking for a response from different commands, since the list of commands that will be executed are for the configuration of vlan attachments. The main idea is to be able to send the execution of commands to the google shell through an API created with python (Django) and access it from a user interface but I have not been able to connect to the specific project to be able to execute those commands. How can I … -
Unable to upload a file using Reactjs, apollo, django
Hello Im' trying to upload a file using django for the back and reactjs for the front and graphql with apollo for reactjs, graphene for django. Here is part of my code : Let's begin with the front files : index.js : import React from 'react'; import ReactDOM from 'react-dom'; import { ApolloClient, InMemoryCache } from '@apollo/client'; import { ApolloProvider } from '@apollo/client/react'; import { createUploadLink } from 'apollo-upload-client'; import App from './App'; const cache = new InMemoryCache(); const uri = 'http://localhost:8000/graphql/'; const link = createUploadLink({ uri }); const client = new ApolloClient({ cache, link }); ReactDOM.render( <React.StrictMode> <ApolloProvider client={client}> <App /> </ApolloProvider> </React.StrictMode>, document.getElementById('root') ); App.js import React from 'react'; import { gql, useMutation } from '@apollo/client'; const MUTATION = gql` mutation ($file: Upload!) { imageUpload(file: $file) { success } } `; function App() { const [mutate] = useMutation(MUTATION); function onChange({ target: { validity, value } }){ if (validity.valid) { const file = new Blob([value], { type: "text/plain" }); file.name = "text.txt"; mutate({ variables: { file: file } }); } } return <input type="file" onChange={onChange} />; } export default App; And now for the back : import graphene from .models import Todo from graphene_django import DjangoObjectType, DjangoListField from graphql_jwt.decorators … -
Avrage rating calculation not working after migration django
My code was doing what it should before the migration of calculating the avrage rating. After a migration it just dident calculate the avrage rating. It seems like the migration dident notice the code i had in choices= RATINGS) . Anyone got any idea how i can fix it and get the code to notice the choices again? Since it worked fine when testing it just before migrations. **code from model.py** class Review(models.Model): product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField(default=3) content = models.TextField() created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) RATINGS = (('1 ',1),('2 ',2), ('3 ',3),('4 ',4),('5 ',5)) rating = models.CharField(max_length=7,choices= RATINGS) def __str__(self): return '%s - %s' % (self.product.name, self.created_by) code in the migration file: class Migration(migrations.Migration): dependencies = [ ('products', '0004_review'), ] operations = [ migrations.AlterField( model_name='review', name='rating', field=models.CharField(choices=[('1 ', 1), ('2 ', 2), ('3 ', 3), ('4 ', 4), ('5 ', 5)], max_length=7), ), ] And this a snippet of the migration after i notice the avrage rating was gone even tho the code was same after migration in models.py: -
how to pass a list of dictionary in chartjs labels and data?
I'm trying to show my data into chart js graph, my data format is this: > {length: 3, objects: Array(3)} length: 3 objects: Array(3) 0: {counter: 1, date: '2022-06-01 00:00:00', income: '233.000', …} 1: {counter: 2, date: '2022-05-01 00:00:00', income: '1000.000', …} 2: {counter: 3, date: '2022-04-01 00:00:00', income: '89.000', …} length: 3 [[Prototype]]: Array(0) [[Prototype]]: Object here is what i tried in my js: function listChartMonOutcome(){ $.ajax({ type:'GET', url:'/listcharts/data/', success:function(data){ var totalMonthCanvas = $('#listChart').get(0).getContext('2d') var totalMonthData = { labels: [ data ], data:{ datasets:[{ data:[{ data }] }] } } var totalMonthOptions = { responsive : true, maintainAspectRatio : false, datasetFill : false, parsing: { xAxisKey: 'income', yAxisKey: 'date' } } var totalMonthChart = new Chart(totalMonthCanvas, { type: 'bar', data: totalMonthData, options: totalMonthOptions }) } }) } listChartMonOutcome() } <div class="card-body"> <div class="chart"> <canvas id="listChart" style="height:250px; min-height:250px"></canvas> </div> </div> but it shows nothing, in the console as well. and also tried this in the data : labels = [data.map(({datE}) => date) ] datasets: [ { data: [ data.map(({income}) => income) ], } ] but raise this error: Uncaught TypeError: data.map is not a function is there any solution for this problem please? Thank you for helping -
Directing to nested URL with react router from server
I am building an app with django3.2 and React 17 using react-router-dom. My react app is served at https://www.example.com/ And if I navigate within the app to https://www.example.com/auth/signup I get the form, however, if I input the url directly into the browser I am taken to a blank page. In my django.urls, I have a catch all that should send the path down to my react app, and in local development it works great. urlpatterns = [ ..., re_path(r'^(?:.*)/?$', homepage), ] PROBLEM: In production I am taken to a blank page. I suspect it has to do with relative paths in production. I've followed these questions: Django static file serving in conflict with React Router React router not loading dynamic url in production And so far have tried: Adding "homepage": "https://www.example.com/" to my package.json. Adding <base href="/" /> to index.html Adding "homepage": "." to package.json But so far nothing has worked, and I need this feature, particularly for email verification. Happy to clarify anything or share front end code. -
What to do if queryset is none
I have a News model, where each instance has a unique date. Which means that every day has exactly one News-instance related to it. I am redirecting to the detail-view of the News-instance from the navbar. To achieve this am I using a context_processor. The context_processor.py file looks like this: from news.models import TodayNews import datetime def todays_news(request): todays_news = TodayNews.objects.get(date=datetime.date.today()) return {'news': todays_news} This works completely fine as long as the News model has an instance on that particular date. Otherwise it returns the following error (which is very logical): TodayNews matching query does not exist. My question is, how can I do something different if the query is empty, for example if one particular date does not have a news-instance? What should I return instead of 'news': todays_news? -
Django python GET http://localhost:8000/topics 404 (Not Found)
I am learning Django using "Python Crash Course" by Eric Matthes ch.18- 20. I am trying to run the get request of my topics.html and I'm getting the error below... GET http://localhost:8000/topics 404 (Not Found) File urls.py /learning_log # from django.conf.urls import include, url OUT_OF_DATE from django.urls import include, re_path as url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('learning_logs.urls', namespace='learning_logs')), ] File urls.py /learning_logs """Defines URL patterns for Learning_logs.""" # from django.conf.urls import url from django.urls import re_path as url from learning_logs import views app_name = 'learning_log' urlpatterns = [ # Home Page url(r'^$', views.index, name='index'), # Show all topics. url(r'^$', views.topics, name='topics'), ] File views.py from django.shortcuts import render from learning_logs.models import Topic def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topic': topics} return render(request, 'learning_logs/topics.html', context) -
Nested Serializer for Foreign Keys
I have two models - Users and UserAccessLogs: class Users(AbstractUser): email = models.EmailField() name = models.Charfield() etc. class UserAccessLogs(AbstractUser): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) anotherField = models.Charfield() etc. with serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' def validate_email(self, value): # validations here def update(self, instance, validated_data): instance.email = validated_data['email'] etc. instance.save() return instance class UserAccessLogsSerializer(serializers.ModelSerializer): class Meta: model = UserAccessLogs fields ='__all__' In my views function I would like to retrieve the actual user class when fetching UserAccessLogs i.e. I would like: UserAccessLogs = { user : { email: myEmail, name: myName, etc. } } instead of UserAccessLogs = { user : 1 } in my views: access_logs = UserAccessLogs.objects.all() serializer = UserAccessLogsSerializer(access_logs, many = True) return Response(serializer.data, status.HTTP_200_OK) I tried adding user = UserSerializer() to UserAccessLogsSerializer class. It works, but then when I try and save a new instance of the UserAccessLogs I get errors related to User model from the validators. If I set read_only = True then it leaves user = null in the database. The below works in my views class but it doesn't seem efficient and needs to be repeated every time I want to get full UserAccessLogs. for data in … -
django to change the value of varible in template based on the number
there is a model books where i want to fetch all the objects and display it to user using django templates books=books.objects.all() and with django template tag im able to fetch the values in the model and display them but is there any way where django can change the variable values based on the number for example this part : {% for b in books %} <tr> <td>{{b.books_id}}</td> </tr> {% endfor %} this will display all the id's but is there any way to override this in django Lets say for instance ,if the b.books_id for any object is 1 then it should display something like "completed" if its 2 then it should display something like "no" is there any possibility to do that ?? using if or for loops in django template tags or through views -
Vertically centering text in a bootstrap card that is being used as a button
As the title says, im trying to vertically align text inside a bootstrap card. I can center it horizontally just fine, just not vertically. I've tried different ways. I would use a button but you can't store links in them I guess. Here is some code <div class="col-sm-4"> <a href="{% url 'manufacturing:view_sections' %}" class="btn btn-primary lift lift-sm h-100 w-100 text-center" style="width: 100vw;" role="button" aria-disabled="true"><h1 class="text-light"><strong>Primary link</strong></h1></a> </div> Here is what it looks like right now The whole card is being used as a button which when pressed it's sent to a different page. -
Is separating django frontend and backend with API viable?
I'm used to Django and already developed website with a whole Django or with Django API + React. For a side project, I'm thinking about creating a Django project with 2 apps: Django API 2) Django Front. I absolutely want to decouple front/back to be able to reuse the API in the future, and I like the view system from Django. Is my idea making sense? -
How i can make the number of page start display the number of page from the second page using wkhtml2pdf
on a django application, using the library wkhtml2pdf to generate a pdf , How i can make the number of page start display the number of page from the second page(2/ total number of pages). this is my parametres in settings.py: WKHTMLTOPDF_CMD = '/usr/local/bin/wkhtmltopdf' WKHTMLTOPDF_CMD_OPTIONS = { 'quiet': True, 'disable-smart-shrinking':True, 'enable-local-file-access':True, 'page-size': 'A4', 'margin-right': '0', 'margin-top': '15', 'margin-bottom': '10', 'margin-left': '3', 'encoding': "UTF-8", 'no-outline': None, "zoom":1, 'javascript-delay':1000, 'footer-center' :'[page]/[topage]', "no-stop-slow-scripts":True, } if is it possible how i can do that ? THANKS IN ADVANCE. -
How to use django-allauth username validation methods in a user update form
I'm using django-allauth system to register users and log them in. My app should allow users to change their usernames if needed. If I use a custom view or form to change a username, no allauth validation happens whatsoever (because default views and forms are not triggered). Thus users can easily set whatever username they wish, ignoring all restrictions specified in settings (like "preserve casing" or "minimum length restriction"). Is there any way to use default validations built in allauth outside signup/login forms? Right now I have to manually create a custom form and use its cleaning methods for validation, which seems to be repetitive and error-prone: def clean_username(self): username = self.cleaned_data.get('username') if username: username = username.lower() if len(username) < settings.ACCOUNT_USERNAME_MIN_LENGTH: raise ValidationError(_("Error text")) if username in settings.ACCOUNT_USERNAME_BLACKLIST: raise ValidationError(_("Error text")) # I need something that works like the code below and validates a username from allauth.account.adapter import DefaultAccountAdapter DefaultAccountAdapter.clean_username(username) return username -
In Django, whitenoise does not show static files
This is my first time using whitenoise. While DEBUG=FALSE, I can't see the images even after doing python manage.py collectstatic. All the static files are transferred to the directory specified in the STATIC_ROOT directory after collectstatic but it shows a Not Found error in the website. My settings.py: BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = False INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'phonenumber_field', 'ramrobazar.account.apps.AccountConfig', 'ramrobazar.dashboard.apps.DashboardConfig', 'ramrobazar.inventory.apps.InventoryConfig', 'ramrobazar.drf.apps.DrfConfig', 'ramrobazar.demo.apps.DemoConfig', 'mptt', # 'django_elasticsearch_dsl', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_simplejwt.token_blacklist', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = 'images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') My root urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('ramrobazar.drf.urls')), path('api-auth/', include('rest_framework.urls')), path('demo/', include('ramrobazar.demo.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) When I run 'collectstatic', all the static files are transferred to BASE_DIR/'staticfiles' as that is the path specified in STATIC_ROOT in settings.py. But when I run python manage.py runserver --nostatic and try to access the images in the website, it shows Not Found The requested resource was not … -
how can i create unit tests a view that returns data in json in django
I was wondering how I can create unit tests for a view like this. I have several of these in my project. def json_list_user(request): data = list(Us.objects.values()) return JsonResponse(data, safe=False) -
Django: Handle migrations created in site-packages for a custom Group field
I require a description field added to the django.contrib.auth.models.Group, so I used this solution (if there is a better way please let me know): from django.contrib.auth.models import Group Group.add_to_class('description', models.TextField(max_length=250, default="")) Unfortunately this creates a migration in: site-packages/django/contrib/auth/migrations/0013_group_description.py This is the migration: class Migration(migrations.Migration): dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.AddField( model_name='group', name='description', field=models.TextField(default='', max_length=250), ), ] This can't be checked into source code since it's in the python site-packages location. I managed to find the MIGRATION_MODULES setting, but unfortunately I don't wish to move all of the auth app's migration to a new dir (django comes with 12 migrations already for auth, and may ship more in the future. No idea how to solve this problem. It really makes deployment a nightmare. -
ModuleNotFoundError when starting celery in Django project
I have a Django project structure like this (not showing all the files/folders): myproj/ ├── __init__.py ├── config/ │ ├── __init__.py <-- imports `celery_app` as per docs │ ├── settings/ │ │ ├── __init__.py │ │ └── base.py │ ├── celery.py <-- defines `app = Celery("myproj")` │ └── wsgi.py ├── myapp1/ └── myapp2/ I have a docker-compose.yml that sets up web and worker services, and the worker service is something like: worker: build: context: "." target: "app" command: celery -A config worker -l info entrypoint: [] But whatever I try for the -A when starting celery I get ModuleNotFound. I've tried config, myproj.config and myproj. I've tried adding --workdir=/path/to/myproj, but no joy. -
difficulties in python and django integration
Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mypackage' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 22, in <module> main() File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module … -
using request.user shows the data that user is created in a application How can i show those data to others user's
I created q and a platform for university students and successfully implemented like functionality in it, and now i want to shows the number of like in the user profile, I also successfully added the number of likes to every user profile, but the problem was only the user that get likes from the answer model can see the number of likes in his profile, How can i allowed other's user's to see the number of likes in his profile, when someone likes his answer in a application, i knew using request.user shows only the content that user own in the application, but does'nt how to shows those likes to other. user profile template: <br> <br> <div class="container"> <div class="row justify-content-center"> <div class="col"> <div class="text-center"> <span class="badge bg-secondary">{{number_of_likes}}</span> <br> <br> <a href="" class="btn btn-primary"> Number Of Votes: </a> <br> </div> </div> </div> </div> my views: def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) number_of_likes = Like.objects.filter(post__user=request.user).count() context = { 'profile':profile, 'number_of_likes':number_of_likes } return render(request, 'public_profile.html', context) def like_answer(request, pk): answer = get_object_or_404(Answer, pk=pk) Like.objects.get_or_create(post=answer, user=request.user) return redirect('view-Question', answer.post.slug) my models: class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return … -
Why am I getting this error when using collectstatic?
settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'StaticFiles') ] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Assets/res') ... When I run py manage.py collectstatic. I get the following message in the terminal:- You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: no CommandError: Collecting staticfiles files cancelled. (debsoc) C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite>py manage.py collectstatic You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: The message in the terminal just doesn't matches with my settings.py configuration of static files. What's the fix for it? -
Django Viewset ADD header to requests
I have two APIs that talk to each other. One API is on DRF, where it needs to take a one-time generated token and pass it with every request to the second API. I can find ways to add headers to the response, but I don't see anyway with a Viewset to pass a token into the header of ALL my requests. I can only find default_response_headers but default_request_headers doesn't exist. I'm also only finding how to respond with a token and take in a request with a token. To clarify, I do not need to get a request header, I need to add a request header with every request on my Django project. Django REST API ---- request w/ token ----> other system