Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python multiple inheritance only working for one parent's method but calling method from both parents
I have a Python/OOP question. You are all familiar with diamond problem in C++ right? This is something similar. I have the following classes class BaseAuth(TestCase): def setUp(self): # create dummy user and client, removing code of that for simplicity. self.user.save() self.client.save() def _get_authenticated_api_client(self): pass class TokenAuthTests(BaseAuth): def _get_authenticated_api_client(self): super()._get_authenticated_api_client() print("I AM IN TOKEN AUTH") api_client = APIClient() # do stuff with api_client return api_client class BasicAuthTests(BaseAuth): def _get_authenticated_api_client(self): super()._get_authenticated_api_client() print("I AM IN BASIC AUTH") api_client = APIClient() # do stuff with api client return api_client class ClientTestCase(BasicAuthTests, TokenAuthTests): def test_get_login_response(self): api_client = self._get_authenticated_api_client() # login test code def test_get_clients(self): api_client = self._get_authenticated_api_client() # get client test code def test_get_client_by_id(self): api_client = self._get_authenticated_api_client() # get client by id test code def test_update_client_by_id(self): api_client = self._get_authenticated_api_client() # update client test code def test_add_client(self): api_client = self._get_authenticated_api_client() # add client test code def test_delete_client_by_id(self): api_client = self._get_authenticated_api_client() # delete client test code Now, when I run the code, I can see that this is printed out: I AM IN TOKEN AUTH I AM IN BASIC AUTH .I AM IN TOKEN AUTH I AM IN BASIC AUTH .I AM IN TOKEN AUTH I AM IN BASIC AUTH .I AM IN TOKEN AUTH I … -
How can I detect that my code is running through the Django shell?
In some cases, we do manual cleanup for our app via the Django shell (python manage.py shell). Of course this should be done with care but in this particular internal app it's just the most effective way to do the work. When running in the Django shell, I'd like to disable some behavior that otherwise would be triggered. How do I detect that my code is running through the shell? I'm imagining something like: if not django.SHELL: # Don't notify chat when running from the shell notifications.send(dev_user, ...) -
How to pass parameters to a mixin on a per-view basis
I have an app for managing test cases, which are organised into various projects. I'm trying to set permissions on a per project basis, i.e. every user has different permissions for each project. Here's what I've come up with so far: class TestProjectMember(models.Model): """Per project permissions - a role can be set for each user for each project""" member_name = models.ForeignKey(User, on_delete=models.SET_NULL) project = models.ForeignKey(TestProject, on_delete=models.CASCADE) member_role = models.CharField(choices=Choices.roles) class TestCase(models.Model): """Test cases""" tc_title = models.CharField(max_length=500, unique=True) tc_project = models.ForeignKey(TestProject, on_delete=models.CASCADE) class TestProject(models.Model): """Projects""" project_name = models.CharField(max_length=200) project_desc = models.CharField(max_length=500) class TestCaseEditHeader(View): def get(self, request, pk): case = get_object_or_404(TestCase, id=pk) if self.get_perm(case.tc_project, request.user, 'TA'): form = TestCaseHeaderForm(instance=case) context = {'case': case, 'form': form} return render(request, 'test_case/tc_header_edit.html', context) else: return redirect('case_list') def get_perm(self, curr_project, curr_user, perm): model_perm = TestProjectMember.objects.filter(member_name=curr_user, project=curr_project).values_list('member_role', flat=True) if perm in model_perm: return True return False It works, but it's a bit clunky. I'd have to call the get_perm() method from every get() or post() method from each view. A better solution would probably be a mixin. What has me stumped is how to pass the required role to the mixin for each view. For each view there is a required role that the user has to have … -
django result of annotate doesn't include in serializers
Django 2.2 I'm serializing a Queryset to use AJAX. This is my simple code def datatables_ajax_test_api(request): users_object = User.objects.filter(created_gte=today).annotate(user_points=Sum('pointlog__point_money')) users = serializers.serialize('json', users_object) return HttpResponse(users, content_type="text/json-comment-filtered") This code passes json data very well its own objects. But not include 'user_points' which is from annotate. How can I include it? -
django upload image to S3, (work on localhost but gives access denied error on server)
error: an error occurred (accessdenied) when calling the putobject operation access denied I am having problem in uploading image to s3 from django, it works fine on local host, but gives access denied error on server with same credentials. here are my settings DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', 'JFHKSF*&^SFJKSF') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', 'asdkl8e8/Qnakisfd89598er7fd') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', 'my-static-files') AWS_S3_FILE_OVERWRITE = os.environ.get('AWS_S3_FILE_OVERWRITE', False) note: I only want to upload image to s3 not all of my static files -
Create .json file from .env file and define as global var
I want to use authenticate the Google Cloud API. So far that's only possible through a .json file. My application is hosted on Heroku. Now I don't want to push that .json file in my GitHub repository. I found a buildpack that actually works. However, I don't want to rely on external buildpacks and wonder if there is another solution. My idea similar to the buildpack: Defining GOOGLE_CREDENTIALS in .env with: { "type": "service_account", "project_id": "natural-language-254706", "private_key_id": "XXX", "private_key": "-----BEGIN PRIVATE KEY-----\nXXXXX\n-----END PRIVATE KEY-----\n", "client_email": "abc@natural-language-254706.iam.gserviceaccount.com", "client_id": "12345", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/starting-account-5yzg5dipgu01%40natural-language-254706.iam.gserviceaccount.com" } Take GOOGLE_CREDENTIALS and write google-credentials.json file with Python <<< here I need help Define GOOGLE_APPLICATION_CREDENTIALS=google-credentials.json I am not struggling with 2. How can I create a .json file out of the credentials in 1. I will add this second step (2.) then as part of the release-tasks in Heroku python manage.py create_json_for_google_credentials -
Django store attachment in Data Lake
I have a Django application, I have written the API to handle files uploads with Django-Rest-framework. I have tested everything and it works with storing the attachments in my local laptop. However, I want the attachment to be store in a data lake, and I have tried to search what I should put in the settings, or what should be done so that instead of creating a local folder in our laptop and store the attachment, the attachment will be stored in the data lake. Does anyone have any experience with it? -
Why isn't the User information appending the mysql database using django?
I am having issues with a django-ajax project in which whenever I try to register a user, it does not append the user information to the mysql database and instead I get this in the terminal when I run the server: Not Found: /sign-up/ajax-sign-up [Time of request] " POST /sign-up/ajax-sign-up HTTP/1.1" 404 2430 Furthermore, I get this error that does not go away on VScode regarding the User class on the forms.py: Class 'User' has no 'objects' member I have added the pylint add-on to remove the error assuming is the Class 'User' error is the issue and I have rewriting the views.py but nothing has worked. Here is my forms.py script: from django import forms from django.contrib.auth import authenticate from django.db.models import F from project.models import User from django.contrib.auth.hashers import make_password, check_password from urllib.request import urlopen from random import randint import json, re class Ajax(forms.Form): args = [] user = [] def __init__(self, *args, **kwargs): self.args = args if len(args) > 1: self.user = args[1] if self.user.id == None: self.user = "NL" def error(self, message): return json.dumps({ "Status": "Error", "Message": message }, ensure_ascii=False) def success(self, message): return json.dumps({ "Status": "Success", "Message": message }, ensure_ascii=False) views.py script: from django.shortcuts import … -
Authenticated API call to AWS with requests
I am running a django application with some data in an AWS bucket. Data is mostly files (powerpoint, word etc..). When I create a new file I get a link attached to it which I show in my REST list view like: "store_file": "https://mybucketname.s3.amazonaws.com/media/private/myfile?AWSAccessKeyId=XXXX&Signature=XXXXXExpires=1571731023" I would like to get this file by doing an authenticated request to the endpoint with the library requests and I don't get it to work. I get a 200 when doing this: def get_data(method='get'): endpoint = "https://mybucket.s3.amazonaws.com/pathtomyfile?AWSAccessKeyId=XXX&Signature=XXXExpires=1571731023" r = requests.request(method, endpoint) return r.status_code get_data() But it doesn't download my file What works is doing it with the AWS CLI like aws s3 cp s3://pathtomyfileinbucket /pathtomysavelocation/filename.pptx Even though this works it's not good for my use case, since I want to use it on different machines and with tests etc... I was also trying to use aws_requests_auth like: auth = AWSRequestsAuth(aws_access_key='...', aws_secret_access_key='...', aws_host='restapiid.execute-api.eu-west-1.amazonaws.com', aws_region='eu-west-1', aws_service='execute-api') response = requests.get('https://restapiid.execute-api.us-east-1.amazonaws.com/stage/mybucket.s3-eu-west-1.amazonaws.com/pathtomyfile', auth=auth, headers=headers) Is there a way to do what I want to do?? I am grateful for any help. Thanks so much in advance! -
PasswordResetConfirmView is not working proeprly?
Here I am not using PasswordResetView because i am sending email through my dynamic email configuration so for this I made my own view which generates the token using PasswordResetTokenGenerator and it also sends the email to the user. the password reset link in my email looks like this http://127.0.0.1:8000/password-reset/confirm/NQ/5as-b3502199950ff028a6ef/ But after click in that link it redirect to the password_reset_confirm which is good but in this view the {{form.as_p}} is not working.It is only displaying the button but before using auth-views.PasswordresetView the form was working but now the form is not being passed in the template. How can i solve this? urls.py path('password-reset/',views.send_password_reset_email,name='password_reset'), path('password-reset/done/',auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'),name='password_reset_done'), path('password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html', success_url=reverse_lazy('password_reset_complete'),),name='password_reset_confirm'), views.py def send_password_reset_email(request): form = CustomPasswordResetForm() if request.method == 'POST': form = CustomPasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] user = get_user_model().objects.get(email__iexact=email) site = get_current_site(request) mail_subject = "Password Reset on {} ".format(site.domain) message = render_to_string('organization/password_reset_email.html', { "user": user, 'domain': site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': activation_token.make_token(user) }) config = EmailConfiguration.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) email = EmailMessage(subject=mail_subject, body=message, from_email=config.email_host_user, to=[user.email], connection=backend) email.send() return redirect('password_reset_done') return render(request, 'password_reset.html',{'form':form}) password_reset_email.html {% block reset_link %} http://{{domain}}{% url 'password_reset_confirm' uidb64=uid token=token %} {% endblock %} password_reset_confirm.html <form action="" method="post"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn … -
How to make simple web application which will display data which i pass dynamically using Django?
I am very new to Django just started learning using RealPython website through which i just understood the basics of it. I wanted to create a simple we application which will display data in a table format like in a HTML table format with some data displayed, this data is dynamic. What i wanted to achieve using Django is the following: Dynamic data is retrieved from a rest api The API provide me data in a JSON format I'll convert into a required table format Pass this table data stream to the view -> Html dummy template created When i open the application or the page the given API in the code should get called and the data should be displayed What i wanted to know: Can you please let me know: How to achieve the above requirement using Django? I kindly request you to please provide the details or guide or steps or any kind of material which will help me to achieve the above functionality. Please try to provide me detailed steps as detailed as it may be as i tied to explain initially i am very new to Django. I have read the blogs on how to … -
How to disable automatic decompression for gzipped image data
I am creating a django web app for viewing and processing of medical images that are stored in a .gz format. The web app has a single model (Post) and form that collects metadata from users as well as one .gz file with a models.FileField call. In my views.py file, I can render a response and feed the path to the medical image to a javascript viewer as well as all the metadata about the image (e.g., type of patient, body part, etc.) that is simple plain text fields. The javascript viewer expects a compressed image (interacting with .gz files is standard in the field). Django seems to only serve these media files decompressed and the javascript viewer (someone else's project) does not like the decompressed data. So far, I have played around with ['Content-Encoding'] options, but I can't get anything working. Maybe I need separate view functions for the metadata and image data? In views.py: def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) rendered = render(request, 'maps/post_detail.html', {'post': post}) # rendered['Content-Encoding'] = 'gzip' return rendered @login_required def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) #, instance=profile) if form.is_valid(): post = form.save(commit=False) post.contributor = request.user post.published_date = timezone.now() post.save() … -
Page not redirecting after form submit
I have a form which creates a new category. Previously, the form was in a different template which worked fine but since it's only a simple form I have decided to render it in modal form instead of redirecting to a different page. The user can add a new category, however the success message and the page rendering after the form submit is not shown. It only shows up if you refresh the page. The response message is 302. I've done similar method with other forms which worked perfectly fine. forms.py class CategoryModelForm(forms.ModelForm): def clean_name(self): print(self.cleaned_data['name']) name = self.cleaned_data['name'] try: Category.objects.get(name__iexact=name) except ObjectDoesNotExist: return name raise forms.ValidationError('Category Name already exists.') class Meta: model = Category fields = ['name'] views.py @method_decorator(login_required, name='dispatch') class CategoryView(TemplateView): template_name = 'content/category_list.html' def get_context_data(self, **kwargs): context = super(CategoryView, self).get_context_data(**kwargs) categories = Category.objects.all() user = self.request.user category_list = [] for category in categories: article_count = category.article_count(user) include = category.show or user.usertype_is_staff() or user.is_superuser requested_by = category.requested_by if category.requested_by else '' cat = { 'reference': category.pk, 'name': category.name, 'show': category.show, 'article_count': article_count, 'has_articles': article_count > 0, 'requested_by': requested_by, 'requested_by_name': requested_by.profile.full_name if requested_by and requested_by.profile.full_name else '-' } include and category_list.append(cat) context['categories'] = category_list context['form'] = CategoryModelForm(self.request.POST or None) … -
how to pass value from html to view in django?
i have code in html like this your major is {{user.userprofile.major}} this will correctly showing the major on webpage, but I want to use this string to get something from another table in view. How would I pass this string to view? -
How to Send Email to Django Oscar Registered Partners about Order Placed for there Products?
I want to Notify Django Oscar Partners through an Email stateing that there products has Order from customers. here Customers might place order from multiple Partners for multiple product. how can i send list of order placed for particular Partner and send Email. -
NOT NULL constraint failed: adminside_event.event_data
I have problem with my code which is i try to submit my Event form in the models. But when i run the form it will show the whole form (and another thing is that it will not show the values in the select box of the rounds) and when i click on the the submit button it will through an error.Please help me out this. VIEW SIDE CODE:-- def addevents(request): if request.method=="POST": name=request.POST['events'] est=request.POST['starttime'] eet=request.POST['endtime'] s=Event() s.ename=name s.event_start_time=est s.event_end_time=eet s.save() cats = request.POST.getlist('cats') for i in cats: s.categories.add(Category.objects.get(id=i)) s.save() roundd = request.POST.getlist('rround') for j in roundd: s.rounds.add(Round.objects.get(id=j)) s.save() return render(request,'adminside/addevents.html') else: rounds = Round.objects.all() categories = Category.objects.all() return render(request,'adminside/addevents.html',{'categories':categories,'rounds':rounds}) MODELS SIDE:- class Event(models.Model): ename=models.CharField(max_length=200) categories = models.ManyToManyField(Category) event_data = models.DateField() event_start_time = models.TimeField() event_end_time = models.TimeField() rounds = models.ManyToManyField(Round) EVENT PAGE FORM:- {% extends 'adminside/master.html' %} {% block content %} <div class="col-12"> <div class="card"> <div class="card-body"> <h4 class="card-title">Events</h4> <p class="card-description"> All fields are Compulsory </p> <form class="forms-sample" method="POST"> {% csrf_token %} <div class="form-group"> <label for="exampleInputEmail1">Add Event</label> <input type="text" class="form-control" name="events" id="exampleInputEmail1" placeholder="Enter Event"> </div> <div class="form-group"> <label>Categories:</label> <select class="form-control" multiple name="cats"> {% for i in categories %} <option value="{{ i.id }}">{{ i.cname }}</option> {% endfor %} </select> </div> <div … -
Send Only Current Page object to the template (django)
I am learning django from MDN.And i was working on locallibrary.There i got one problem. I want to send only books on author page but not all book,only current page's author book. If url is /author/1 then sent only book of author id 1, not all In AuthorDetailView i tried context['books']=Book.objects.filter(author__exact=Author.id). but it give error **TypeError at /catalog/author/1** **int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'** When i write context['books']=Book.objects.filter(author__exact=1) then it send only authorid 1's book on all page. on author/2. so i want to send authorid 2's book on author/2. 3's book on author/3. But not all books on everypage. It doesn't make sense to send all objects when needed few. {% for book in books%} {% if author.id is book.author.id %} <li> <a href="{{ book.get_absolute_url }}">{{ book.title }}</a> ({{book.author}}) </li> {% endif %} This code do what i wanted but by sending all objects. I hope you understand what i want. Here is my models,views https://pastebin.com/yY6M5LUA -
Update Contacts using Python, Django and Graph
I'm trying to update contacts using Python and Microsoft Graph within a profile page I've created using Django. I can access contacts and get all the data I need, however I can't work out how to update the fields. The only information I can find is on the Graph website, however I can't work out how to translate this into usable code: PATCH PATCH https://graph.microsoft.com/beta/me/contacts/ Content-type: application/json { "title": "Mr", "givenName": "Steve" } I assume there is a way to just put this together as a simple link but I cannot work it out. I've tried the following: PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/Mr PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title:Mr PATCH https://graph.microsoft.com/beta/me/contacts/{id}/title/$value==Mr but they all produce errors There are no tutorials for doing this with Python on the Microsoft site and it's proving very difficult to find any info on it. So hopefully someone can help out. Cheers! -
Module Not Found Error after moving directory and back
After moving my directory back and forth, I am recieving the below error. Not sure how to resolve this. The files are currently sitting in the directory they originated from. What seettings should I be looking at when I get an error like this. C:\Users\Nathan\AppData\Local\JetBrains\Toolbox\apps\PyCharm-P\ch-0\192.6817.19\bin\runnerw64.exe C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\Scripts\python.exe C:/Users/Nathan/PycharmProjects/DJANGO_TemplateApp/manage.py runserver 8000 Traceback (most recent call last): File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Nathan\PycharmProjects\DJANGO_TemplateApp\venv\lib\site-packages\django\conf\__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\Nathan\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'DJANGO_TemplateApp' -
How to use less database look-ups during filter?
I have a section of code that makes several db calls and I am trying to optimize it. Is there a way to get rid of/combine: username = users.models.User.objects.filter(groups__name=group) or.. user_obj = users.models.User.objects.get(username=user) or combine them so that I am only making one database lookup during this transaction instead of two? for group in groups: username = users.models.User.objects.filter(groups__name=group) for user in username: form.instance.unread.add(user) user_obj = users.models.User.objects.get(username=user) user_obj.send_sms('memo') user_obj.send_email(user, 'memo') Also, I am new to web development; is this something I should worry about? -
Django request is loop when request take long time
I have an issue when making an ajax POST request. Sometimes My request is being looped when it takes a long time to respond. Somehow a new request similar to the previous request is made, and I don't know where is it from? I have tried to debug, create traceback, but have no idea where is it called. It usually happens when the request is made from the Chrome Browser on macOS. Do you guys have any idea why does it happen? Django version 1.11.17 -
I`m creating a calendar-app using django. Calendar must be vertical
For now I have realized this django-calendar . But i need vertical calendar(sorry, haven`t found any in English) On the left we have weekday headers and month names on the top. I started overriding python-calendar HTMLCalendar methods. I thought to write formatweekdayrow method, which would generate row of mondays, tuesdays .... sundays. But i got stuck as i dont fully understand how these all methods work. So the question is should i think over my idea of writing formatweekdayrow, or is it not possible to make vertical calendar like that? Or may be there is some simple and smarter way to do that? -
Pulled my docker django project but don't run
I create a dockerized version of my Django project in this fashion: create my Dockerfile create my docker-compose.yml create my .dockerignore on my machine all done, if i run docker-compose up all start. Then i build the project docker-compose build . and push to my hub repo docker push myrepo/myproject well, at this point i connect from another machine and i do: docker pull myrepo/myproject as you can see it download the image: but when i run it nothing appen: docker run d080812784c6 in my docker-compose file, into my web service i specify the command: command: python /Code/core/manage.py runserver 0.0.0.0:8000 ...how can i start my pulled docker image correctly? So many thanks in advance -
How to remove slashes inside hashed key in DRF API Key or is there any way to accept slashes in urls.py?
I created an API Endpoint in Django to generate an API Key with DRF API Key Module. The problem occurs sometimes. If the generated key has slashes in it, it can't be fetch by the other API Endpoint. There's no problem if I create it in Django admin side. I have tried to override the methods in the module so that it can be generated through the serializer. I can't trace the problem. #models.py class UserCompanyAPIKeyManager(BaseAPIKeyManager): key_generator = KeyGenerator(prefix_length=32, secret_key_length=32) class UserCompanyAPIKey(AbstractAPIKey): objects = UserCompanyAPIKeyManager() #some fields @classmethod def generate_prefix(self) -> str: key_generator = UserCompanyAPIKey.objects.key_generator try: key, prefix, hashed_key = key_generator.generate() except ValueError: # Compatibility with < 1.4 key, hashed_key = self.key_generator.generate() # type: ignore pk = hashed_key prefix, hashed_key = split(hashed_key) else: pk = concatenate(prefix, hashed_key) return pk, prefix, hashed_key #serializers.py class UserCompanyAPISerializer(serializers.ModelSerializer): def create(self, validated_data): pk, prefix, hashed_key = self.Meta.model.generate_prefix() validated_data['prefix'] = prefix validated_data['id'] = pk validated_data['hashed_key'] = hashed_key return super().create(validated_data) class Meta: model = UserCompanyAPIKey fields = ['id', 'name', 'expiry_date', 'user', 'company'] Working output us5z0Faxg2zEPDo99NmAOgEsf70MpHVb.pbkdf2_sha256$150000$RmkU1OFLKEtW$2YIEK7cZztwVjbqAEoQRLDzxujfTlQ2Fwx4skp2o1nk= Problem ( with slash ) eKi7lj4AvTEgorF7iKiFrzxQZlVD196C.pbkdf2_sha256$150000$ri39ifY6bmDj$DKQHFhTYQOzpEph6v8BUwbdxO/FcLjqDZa/nzq+ujJY= -
Strategy for serving Django Admin static files in k8s environment
Been messing with this most of the day and have been stumped. nginx-ingress isn't designed to serve static files per this Github issue. gunicorn isn't either per documentatoin WhiteNoise works locally with gunicorn, but doesn't seem to like nginx-ingress and just returns a: Resource interpreted as Stylesheet but transferred with MIME type text/html I've tried a few things, one of which: Was FROM python:3.7-slim, copying the app over and then installing nginx into the image. Doesn't seem like a good practice and couldn't get it working. The only other thing I can think of trying is a deployment and service just for the static files. However, not sure how to set that up, particularly the routing. Any suggestions, or guidance, on how to serve static files (particularly Django Admin) in a k8s setup?