Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django jwt "detail": "Authentication credentials were not provided."
I am trying to implement jwt token authentication in my Django Rest Framework application. I am able to receive a token from the django server as you can see POSTMAN request but when I try to get user profile, I got this error. Does anyone have idea?? { "detail": "Authentication credentials were not provided." } I could get access token as you can see. This is SIMPLE_JWT setting in settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=3), 'AUTH_HEADER_TYPES': ('JWT', ), 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken', ) } This is app/urls.py urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("user.api.urls")), path('api/auth/', include('djoser.urls')), path('api/auth/', include('djoser.urls.jwt')), ] This is app/user/urls.py router = DefaultRouter() router.register("api/auth/users/", TraineeRegisterApiView) urlpatterns = [ path('profile/', TraineeProfileApiView.as_view({'get': 'retrieve'})) ] -
Including custom Python module with heroku app?
I've included my python module in my app as follows -myapp -mymodule -__init__.py -setup.py -migrations -template -etc... and to the requirements.txt file. During build, the module is installed along with everything else in requirements, which I believe puts mymodule in brython_stdlib.js, because I am also using brython. The logs confirm the module is installed, but not where. Successfully built mymodule However, when I go to import the module, I get an error. According the the logs I can see that the client is making ajax calls looking for the file. Not Found: /mymodule.py Not Found: /mymodule/__init__.py Not Found: /static/django_brython/js/Lib/site-packages/mymodule.py ... and so on. (I've edited out a lot of lines here, but you get the idea!) So what I think is happening is that the client is not finding the module, and is asking for it from the server. But I can put a mymodule.py in my app and it still does not find it. Of course I would rather not serve ajax calls for this since it should already be installed along with everything else in the requirements file. Please help! I feel really close to getting this to work, but also now it's been feeling that way for … -
Displaying Data in Django using HighCharts
I have text data in a example.txt file in the following format [[Date.UTC(1970, 10, 25), 0], [Date.UTC(1970, 11, 6), 0.25], [Date.UTC(1970, 11, 20), 1.41], [Date.UTC(1970, 11, 25), 1.64], [Date.UTC(1971, 0, 4), 1.6]] Which I am reading in django view.py file as follows filepath = os.getcwd() f = open(filepath+"/main/static/main/data/example.txt", "r") dataset = f.read() def home(request): context = {'dataset': dataset} return render(request, 'main/home.html', context) Loading it in the template as follows <script src="https://code.highcharts.com/highcharts.js"></script> <div id='dataset' data-dataset={{ dataset }} style="width:100%; height:500px;"></div> <script type="text/javascript" src="{% static 'main/js/main.js' %}" ></script> And javascript main.js file with highchart code as follows const app_control = (function() { var sdata; var init_charts; /* VARIABLES INITIALIZATIONS */ /* DEFINE THE FUNCTIONS */ /* Initialize Functions */ init_charts = function(sdata){ const chart = Highcharts.chart('container', { chart: { type: 'spline' }, title: { text: 'Example Data from ' }, xAxis: { type: "datetime", title: { text: 'Date' } }, yAxis: { title: { text: 'Data in Y Axis' } }, colors: ['#06C'], series: [{ name:'Visualized Data', data: sdata }] }) } /* PUBLIC INTERFACE */ public_interface = {}; /* RUN THE FUNCTIONS */ $(function(){ sdata = $('#TimeSeries').data('dataset'); init_charts(sdata); }); return public_interface; }()); The question is, why is the data not visualizing? If … -
last_updated date and time keeps updating everytime the user logs into the system but doesn't update any of their details in Django
In my model for user profile, the profile_last_updated = models.DateTimeField(auto_now=True) keeps updating every time the relevant profile owner logs in but doesn't update any of their details. Is there a way to fix this? I found this on SO django last updated keeps updating when there is no new information but it's a bit confusing. Appreciate any help - thanks! views.py def user_profile_detail_view(request,pk): try: myprofile = get_object_or_404(User, id=pk) except ObjectDoesNotExist: return redirect('handler404') -
Problem Generating Azure ADLS Gen2 SAS Token for Container with Python?
From azure.storage.blob I'm using the function generate_container_sas. I'm trying to generate a SAS token for a container in an ADLS Gen2 storage account in Azure. I can go into azure portal and generate a working SAS token using an account key with no issues. The token works just fine. However, when I do what I think is the same thing in python I get a token back but when I load it into storage explorer it says "Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.". I have validated all the inputs appear to be correct. The token that is generated looks like: https://<STORAGE_ACCOUNT>.blob.core.windows.net/<CONTAINER_NAME>?se=2022-02-19T05%3A41%3A26Z&sp=rwdlac&sv=2020-10-02&sr=c&sig=jCd8AAatl5o9QsbMHtlca6oNnnRdKqtcOnWN3sZa1c8%3D sas_token = generate_container_sas( account_name=account_name, container_name=container_name, account_key=account_key, permission=AccountSasPermissions(read=True, list=True, write=True, delete=True, create=True, add=True), expiry=datetime.utcnow() + timedelta(hours=expiry_hours) ) -
Django messages multiple extra tags
I was trying to pass multiple extra tags in the messages.add_message() as a list. It seemed to work fine while using render, but when I'm trying to use redirect, it passes the extra_tags as a string and I can't get my objects by indexing as it considers the whole list as a string. Is there a way to solve this or pass multiple extra tags? Here is the code- def handleSignup(request): if request.method == 'POST': username = request.POST['signup_username'] name = request.POST['name'] password = request.POST['signup_password'] email = request.POST['email'] if User.objects.filter(username=username).exists(): messages.add_message(request, messages.INFO, 'Please try another username.', extra_tags=['danger', 'Username already taken!']) elif User.objects.filter(email=email).exists(): messages.add_message(request, messages.INFO, 'An account with the email already exists.', extra_tags=['danger', 'Email already in use!']) else: user = User.objects.create_user( username=username, email=email, password=password) user.name = name user.save() messages.add_message(request, messages.INFO, 'Account created.', extra_tags='success') else: return HttpResponse('404 - Not Found') return redirect('/') -
no module name 'django'(already installed django)
I get this error when I run "python3 manage.py runserver" from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' but I already installed and activated django in the virtual environment... I really don't know how to fix it because it worked well before -
Illegal instruction: 4 While running "python manage.py runserver"
Getting the error Illegal instruction and Python stopin macbook pro (os 12.2) -
I created a Django form that is working fine but when i try to update then it's not saving the data into database
When i post data through django model form it is working fine but when i update the data by using same form its not working. Please help me on this and also when i update form, every field is prefilled but not image field. It was working fine when i last updated few days back but it's not working now. I deleted migrations and database too but still not working. Waiting for your help, Thanks in advance. here is my code: views.py(for creation) def dashboard_employees_create(request): if not (request.user.is_authenticated and request.user.is_superuser and request.user.is_staff): return redirect('/') if request.method == 'POST': form = EmployeeCreateForm(request.POST,request.FILES) if form.is_valid(): instance = form.save(commit = False) user = request.POST.get('user') assigned_user = User.objects.get(id = user) instance.user = assigned_user instance.title = request.POST.get('title') instance.image = request.FILES.get('image') instance.firstname = request.POST.get('firstname') instance.lastname = request.POST.get('lastname') instance.reporting_to = request.POST.get('reporting_to') instance.startdate = request.POST.get('startdate') instance.employeetype = request.POST.get('employeetype') instance.employeeid = request.POST.get('employeeid') instance.dateissued = request.POST.get('dateissued') instance.save() messages.success(request,'Account Created Successfully!!',extra_tags = 'alert alert-warning alert-dismissible show') return redirect('dashboard:employees') else: messages.error(request,'Trying to create dublicate employees with a single user account ',extra_tags = 'alert alert-warning alert-dismissible show') return redirect('dashboard:employeecreate') dataset = dict() form = EmployeeCreateForm() dataset['form'] = form dataset['title'] = 'Register Employee' return render(request,'dashboard/employee_create.html',dataset) views.py for updation: (result is "Form Data not Valid") … -
metadata error showing when installing allauth
When iam trying to install authall package in django , its showing metadata-generation-failed.. Collecting django-allauth Using cached django-allauth-0.48.0.tar.gz (658 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [14 lines of output] Traceback (most recent call last): File "", line 2, in File "", line 34, in File "C:\Users\Svalia\AppData\Local\Temp\pip-install-tn0ujcx9\django-allauth_6b3b0a5ab58d495fa2ebbbd50cccbf59\setup.py", line 173, in setup(**METADATA) File "c:\users\svalia\desktop\yezwe-main\yezwe-main\venv\lib\site-packages\setuptools_init_.py", line 154, in setup install_setup_requires(attrs) File "c:\users\svalia\desktop\yezwe-main\yezwe-main\venv\lib\site-packages\setuptools_init.py", line 143, in install_setup_requires dist = MinimalDistribution(attrs) File "c:\users\svalia\desktop\yezwe-main\yezwe-main\venv\lib\site-packages\setuptools_init.py", line 135, in init super().init(filtered) File "c:\users\svalia\desktop\yezwe-main\yezwe-main\venv\lib\site-packages\setuptools\dist.py", line 456, in init for ep in metadata.entry_points(group='distutils.setup_keywords'): TypeError: entry_points() got an unexpected keyword argument 'group' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
Next.js dynamic routes don't update when django database is updated
The frontent is Next.js, the backend is Django, and we're using the django admin to update information. The info updates just fine on static pages, but on dynamic routes it won't update. This is what the code looks like on the dynamic route pages on the getStaticPaths and getStaticProps in Next.js: export async function getStaticPaths() { const response = await fetch( `${process.env.NEXT_PUBLIC_BASE_CMS}/api/events/all`, ); let events; if (response.status === 200) { events = await response.json(); } const paths = events?.map((event) => ({ params: { id: `${event?.id}` }, })); return { paths, fallback: false, }; } export async function getStaticProps({ params }) { const response = await fetch( `${process.env.NEXT_PUBLIC_BASE_CMS}/api/events/one/${params.id}`, ); let event; if (response.status === 200) { event = await response.json(); } return { props: { event: event?.event || null }, revalidate: 10 }; } I thought adding the 'revalidate:10' would fix the issue, but so far it seems to be continuing, and in order for the changes to show up we have to redeploy every time changes are made to the backend, which isn't ideal. Any help would be appreciated, thank you! -
Django how to display foreign key in admin as list of links?
Say I have two Django models Room and User. I'll leave the models generic open here. At User I have a one-to-many-relationship with Room, so that one Room may be used by many users but its usage is optional: room = models.ForeignKey(Room, blank=True, null=True, on_delete=models.SET_NULL, related_name='users') How do I show at Room admin page a section with all its users? I already tried admin.TabularInline and it shows all the user fields as editable, but I'd like to have a list of link to users (e.g. user name) with the possibility to add an existing user to the list. I also tried adding the related_name users to the Room ModelAdmin list_display attribute, but nothing happend :D -
postgres column name ending with "_id" not possble?
I am using django and postgres for my app. I was trying to make a postgres table containing columns ending with "_id" to mimic relation table. Postgres made the column name the one without "_id". For example, class Math(models.Model): student_id = models.IntegerField() teacher_id = models.IntegerField() test_time = models.DateTimeField() test_id = models.CharField(max_length=255, unique=True) In postgres table, it turned out to be the column names of School table changed to; student teacher test_time test_id I guess postgres does not allow me to assign column name ending with "_id" at least for the IntegerField(). Is there any way to get around of this limitation? Thanks in advance. -
Django RTSP İp Camera to Browser
I want to publish ip Camera images on my web page, but I couldn't find a source.It works when I run it with the python cv2 library, but I haven't made any progress in my django project yet. Python code I found on the internet; import cv2 cap=cv2.VideoCapture('rtsp://admin:123456@192.168.1.216/H264?ch=1&subtype=0') while True: ret, frame = cap.read() cv2.imshow("Capturing",frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() -
How to use django forms
currently when I run my app, am promoted to enter data from the terminal which i dont want eg Enter Loan Ammount from .forms import BasicForm def signup(request): if request.method == 'POST': form = BasicForm(request.POST) if form.is_valid(): # Entering the loan amount isCorrectAmount = True while isCorrectAmount: enteredLoanAmount = request.POST.get(float(input("Enter Loan amount (Min - 1,000,000): "))) if enteredLoanAmount < 1_000_000: print("Minimum Loan amount is 1,000,000") enteredLoanAmount = float(input("Enter Loan amount (Min - 1,000,000): ")) else: isCorrectAmount = False # Entering the age isCorrectAge = True while isCorrectAge: enteredAge = int(input("Enter Age (18 - 50 years): ")) if enteredAge < 18 or enteredAge > 50: print("Sorry, age does not meet criteria!") enteredAge = int(input("Enter Age (18 - 50 years):")) else: isCorrectAge = False # Entering the loan term isCorrectTerm = True while isCorrectTerm: enteredTerm = int(input("Enter Loan term (3 - 35 years): ")) if enteredTerm < 3 or enteredTerm > 35: print("Sorry, loan term does not meet criteria!") enteredTerm = int(input("Enter Loan term (3 - 35 years):")) else: isCorrectTerm = False # Entering the gender enteredGender = input("Enter Gender (MALE or FEMALE): ") I would like to stop this and enter data using my form not the terminal and my form … -
Django email is giving error ''list' object has no attribute 'splitlines''
This is my email sending code in my view: def send_email(): if dasa == 1: send_mail( 'Test available', available_tests, 'from_email', ['to_email'], fail_silently=False, ) When I run my website I get this error: AttributeError at /tests/ 'list' object has no attribute 'splitlines' How can I fix it? I can't find anything, and I am following the format on how to send an email with django. -
How to associate steam account to a registered Django account through SteamOPENID? I'm using Python Social Auth (or should I use allauth?)
As said on the title, I'm having difficulty trying to associate a steam account to a registered Django account. I'm using Python Social Auth library for django I have a steam API key and it works. Using this code works: <p> <a href="{% url 'social:begin' 'steam' %}?next={{ request.path }}">Login with Steam</a> </p> It redirects me to the steam page and asks me to login, then if successful, redirects me back to my website. However, I don't know what to do after that? I see in the terminal that I get sent back a bunch of info about the player from Steam. -
Use of tokens in Django for validation in URLs
I need to e-mail visitors (not registered users) a link to view a page on my website. The page will have an ID that corresponds to a certain record in the database. However, I would like to ensure that the users indeed got the link from the e-mail and didn't just manually enter a database ID. To do so, adding a token to the URL seems a good way to go. Unless I have to, I prefer to NOT store additional information (the token) in the database, but instead use the existing ID to create the token (using some sort of a salt), and re-generate the token based on the ID and check if this is valid. My question is: what is a good way to generate this token in Django? Is it a good idea to use the make_password function? Or do I use say SHA1 encryption of the string? What trade-offs should I take into account and is there a specific route that would be preferred for this situation? -
Forwarding to another view swallows one argument
I have a ListView that checks for a user right and forwards a queryset or redirects to another view depending on the user's rights: class SelectRegisterListView(StoreMixin, ListView): template_name = f"{TEMPLATE_ROOT_SHELF}/select_register.html" def get_queryset(self): registers = Register.objects.filter(store = self.store) print(registers, registers.first().pk) ## works ... and 4 if check_custom_registers_allowed(self.request) == True: return registers return redirect("select-quality", ins_id = self.kwargs["ins_id"], pg = self.kwargs["pg"], reg = registers.first().pk) I have this in my urls.py: path("selectquality/<int:ins_id>/<int:pg>/<int:reg>", views.SelectRegisterListView.as_view(), name = 'select-quality'), which fails with a NoReverseMatch error: Reverse for 'select-quality' with keyword arguments '{'ins_id': 1849332, 'pg': 3, 'reg': ''}' not found. I now tried different values instead of registers.first().pk and I need help understanding this: when adding an int -> reg stays empty - also happens when adding str(4) return redirect("select-quality", ins_id = self.kwargs["ins_id"], pg = self.kwargs["pg"], reg = 4) Reverse for 'select-quality' with keyword arguments '{'ins_id': 1849332, 'pg': 3, 'reg': ''}' not found. when adding a str -> reg has value, but fails return redirect("select-quality", ins_id = self.kwargs["ins_id"], pg = self.kwargs["pg"], reg = "test") Reverse for 'select-quality' with keyword arguments '{'ins_id': 1849332, 'pg': 3, 'reg': 'test'}' not found. The last case is obvious, reg needs to be of type int, not str. But why does the first approach … -
Django Rest Framework 500 status, but still creates an instance (not-null constraint)
I have this very weird bug which i cannot debug since a few hours. I keep getting an error on my post request creating an instance of a liked product in database. django.db.utils.IntegrityError: null value in column "product_id" of relation "ecommerce_like" violates not-null constraint DETAIL: Failing row contains (31, null, null). What's weird is that it creates this instance and works perfectly, yet gives status.500 and i have no idea how to remove it. So i have this model: class Like(models.Model): product = models.ForeignKey('ProductInStore', on_delete=models.PROTECT) user = models.ForeignKey('users.CustomUser', on_delete=models.PROTECT) class Meta: unique_together = ('product', 'user',) class ProductInStore(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=200) And the code for creating an instance of Like is like this: class LikeProductApi(generics.CreateAPIView): queryset = Like.objects.all() serializer_class = LikeSerializer def create(self, request, *args, **kwargs): product_id = self.kwargs['pk'] product = ProductInStore.objects.get(id=product_id) if Like.objects.filter(user=self.request.user, product=product).exists(): raise ValidationError("This user already likes this product") else: Like.objects.create(user=self.request.user, product_id=product_id) return super().create(request, *args, **kwargs) class LikeSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) product = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Like fields = ('user', 'product',) Do you have any idea what's wrong? -
How can I update a value in the db from a template Django?
I'm new to django, javascript, and development in general. But when creating a web application, I had the task of making it possible to change the statuses in the database records on the page. Unfortunately, my technical skills are not enough to sort out this issue. I need help Here is my model.py (simplified) class aplicationSend(models.Model): status = [ ('1', 'In store'), ('2', 'In warehouse'), ('3', 'Send'), ] DOC_TYPE = [ ('1', 'Doc1'), ('2', 'Doc2'), ] date = models.DateTimeField(verbose_name='Date', default=now) doc_type = models.CharField(verbose_name='Document type', choices=DOC_TYPE, max_length=100, default=1) status_select = models.CharField(verbose_name='Status', choices=status, default=1, max_length=100) The task is to display the select in the template and, when it changes, immediately send a request to the database to update the record in the model views.py @login_required def aplication(request): search = request.GET.get('search') model = aplicationFilter(request.GET, queryset=aplicationSend.objects.all()) if search: model = aplicationFilter(request.GET, queryset=aplicationSend.objects.filter(phone_num__icontains=search) | aplicationSend.objects.filter(invoice_num__icontains=search)) form = aplicationSendForm if request.method == "POST": form = aplicationSendForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.staffer = request.user instance.fromTT = request.user.profile.location instance.save() messages.success(request, 'Success') else: messages.error(request, 'Error') return redirect(request.path) HTML <form action="" method="post"> {%csrf_token%} <table style="width: 100%; text-align: center;" class="out_model"> <tbody> {% for qs in model.qs %} <tr> <td><input type="checkbox" name="select" id="selectel"></td> <td style="width: 150px;">{{qs.get_status_select_display}}</td> <td>{{qs.get_doc_type_display}}</td> <td>{{qs.date}}</td> <td>{{qs.phone_num}}</td> <td>{{qs.invoice_num}}</td> <td>{{qs.fromTT}}</td> … -
How can i make this nested Django Query?
How can i make this django query? Models: class Card(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=255, null=True, blank=True) description = models.TextField(null=True, blank=True) cover = models.CharField(max_length=255, null=True, blank=True) member = ArrayField(models.CharField(max_length=255, null=True, blank=True), null=True, blank=True) label = ArrayField(models.CharField(max_length=255, null=True, blank=True), null=True, blank=True) subscribed = models.BooleanField(default=False) due = models.DateTimeField(auto_now_add=False, null=True, blank=True) class Checklist(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=255, null=True, blank=True) class CardChecklist(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE, null=True) checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE, null=True) class Checkitem(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=255, null=True, blank=True) checked = models.BooleanField(default=False) class ChecklistCheckitem(models.Model): checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE, null=True) checkitem = models.ForeignKey(Checkitem, on_delete=models.CASCADE, null=True) Expected Example Query Result (All Checklists of an indicated Card with its related checkitems): [{'id':'1', 'name':'checklist1', 'user':'1', 'CheckItems': [{'id': '1', 'user':'1', 'name':'Checkitem 1', 'checked':True}, {'id': '2', 'user':'1', 'name':'Checkitem 2', 'checked':False}]}, {'id': '2', 'name':'checklist2', 'user':'1', 'CheckItems': [{'id': '3', 'user':'1', 'name':'Checkitem 3', 'checked':True}, {'id':'4', 'user':'1', 'name':'Checkitem 4', 'checked':False}]}] Closest Attempt cardChecklists = list( Checklist.objects .filter(cardchecklist__card=cardId) .values('id', 'name', 'user', CheckItem = F('checklistcheckitem')) ) [{'id':'1', 'name':'checklist1', 'user':'1', 'CheckItems': 1}, {'id':'1', 'name':'checklist1', 'user':'1', 'CheckItems': 2}, {'id': '2', 'name':'checklist2', 'user':'1', 'CheckItems': 3}, {'id': '2', 'name':'checklist2', 'user':'1', 'CheckItems': 4}] -
Why does "django-bootstrap-v5" exist?
I've been following a tutorial "https://youtu.be/0mCZdemSsbs" and others (some Bootstrap 4 others v5), that do not use "django-bootstrap-v5" (see https://django-bootstrap-v5.readthedocs.io/en/latest/ ). I'm wondering if / why it exists, and should I use it? -
Efficient Way of Creating Dynamic URL's from a Global Nav? Django
I'm developing a Task management platform in which users can register a Project and then create tasks for their Project. Currently my url structure is as follows: example.com/customer/project_name/ example.com/customer/project_name/tasks/ example.com/customer/project_name/task-creation/ etc. project_name comes off of the Project model and I'm using slug matching to return the appropriate Project. The problem is, I can't think of a way of passing the project_name slug without duplicating my navigation across all pages or making my views unnecessarily complex. For instance, I have both DetailViews and ListViews so object.slug won't work across the board. The second problem is that on child pages the slug variable changes from 'slug' to 'project_main'. If I'm not mistaking I believe this change is necessary for proper hierarchy. My urls.py app_name = 'projecthome' urlpatterns = [ path('invite-registration/', views.invite_registration, name='invite-registration'), path('team/', views.team, name='team'), path('<slug:slug>/', ProjectDetailView.as_view(), name='project_main'), path('<slug:project_main>/tasks/', TaskListView.as_view(), name='tasks'), path('<slug:project_main>/tasks/create-task/', CreateTaskView.as_view(), name='task- creation'), ] Showing just a few for brevity. So object.slug would only work from project_main view, object.project_main or object_list.project_main would have to be used for the other views. Although, I'm not sure if the slug is inherently in the context for subsequent views as I've only been to get it to work from project_main. What's the best way … -
How can I access my static files from my Django app?
I have a Django app running in a Docker container. I am using Nginx to serve as the production server with a docker-compose file putting the app, Nginx and Postgres together in a network of containers. I set up my Dockerfile as follows: FROM python:3.9.6-buster ENV HOME=/home/app/ ENV APP_HOME=/home/app/web RUN mkdir -p "${APP_HOME}/staticfiles" # Create user ENV PYTHONBUFFERED=1 WORKDIR $APP_HOME COPY requirements.txt $APP_HOME RUN pip install -r requirements.txt COPY . $APP_HOME which as you can see sets a staticfiles directory. However, following normal Django principals my file structure is /home/app/web/quote_checklist/static/quote_checklist when I exec into the web container. I'm using the following in my settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") When I access the index page I am getting an error that the directory/file /home/app/web/staticfiles/quote_checklist/css/base.css is not found, suggesting my app is looking in this staticfiles directory, which has nothing in it. I tried removing the /staticfiles/ bit from my static volume as well but then the system just looks in /home/app/web/static/quote_checklist/css/base.css rather than following the normal Django path, which would be to look in quote_checklist/static/quote_checklist/css/base.css. Does anyone have suggestions?