Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to perform put/patch method for a model with an extended user(onetoone field) relationship django rest framework
I have an account model generic to all user types, and when user signs up, they chose a particular role, and with post.save method the schema for that role is automatically created. I want the user to be able to update their profile(specific to their roles) after sign up. the problem is that I try using the put or patch method, it raises error that {user: {this field is required}} models.py class Specialist(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE, default=1, blank=True) description = models.TextField(blank=True) profile_picture = models.ImageField(upload_to='doc_image/', blank=True, null=True) def __str__(self): return f'{self.user}' serializer.py class Meta: model = Specialist optional_fields = ['user', ] fields = ['user', 'hospital', 'description', 'profile_picture'] extra_kwargs = { 'user': {'read_only': False}, 'user': {'validators': []}, } def update(self, instance, validated_data): instance.user = validated_data.get('user', instance.user) instance.hospital = validated_data.get('hospital', instance.hospital) instance.description = validated_data.get('hospital', instance.description) instance.profile_picture = validated_data.get('profile_picture', instance.profile_picture) instance = super().update(instance, validated_data) return instance views.py class SpecialistUpdateView(APIView): def get(self, request, doctor_id): try: model = Specialist.objects.get(user_id = doctor_id) except Specialist.DoesNotExist: return Response(f'doctor with the id {doctor_id} is not found', status=status.HTTP_404_NOT_FOUND) serializer = SpecialistUpdateSerializer(model) return Response(serializer.data) def patch(self, request, doctor_id): model = Specialist.objects.get(user_id=doctor_id) serializer = SpecialistUpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE) I think … -
Can't get my serializer to read my nest list of objects
I am still new to Django and I'm ripping my hair out with this issue. I am receiving a JSON object from an external API. That I'm trying to save to our DB from Django. Here is an example of the JSON object. { "A bunch of Keys": "and values", "Units": [ "Year": "2020", "Make": "Jay Flight SLX", "ETC" : "ETC" "Parts": [ { "DealerId": "", "MajorUnitPartsId": 10187618, "PartNumber": "06-0544", "SupplierCode": "672", "Qty": 1, "Cost": 37.95, "Price": 0.0, "Retail": 37.95, "SetupInstall": "I", "Description": "20# PROPANE COVER BLACK", "dealstate": 5, "internaltype": 2 }, { "DealerId": "", "MajorUnitPartsId": 9637201, "PartNumber": "0274320", "SupplierCode": "JAY", "Qty": 1, "Cost": 0.92, "Price": 4.99, "Retail": 4.99, "SetupInstall": "I", "Description": "BATTEN,HENDRIX BEACH .88X8' CP2", "dealstate": 5, "internaltype": 4 }, ] "Trade": [ { "DealerId": "", "StdMake": "COBRA", "StdModel": "31", "StdYear": "1993", "StdCategory": "", "allowance": 3000.0, "acv": 500.0, "payoff": 0.0, "lienholder": "", "modelname": "", "unitclass": "C", "color": "", "odometer": 0, "manufacturer": "PASSPORT", "note": "", "unittype": "CLASS C" } { Now the issue I am running into is when my serializer kicks in I want to pop each list and then save them to their own modules. The main table works, The Unit table works and the Trade table works. … -
How can I save the user model "id" Automatic
class User(AbstractUser): last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) email = models.CharField(max_length=100) to verify the login password class Summaries(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) extended model class Student(models.Model): user = models.ForeignKey(Summaries, related_name = "student", on_delete = models.CASCADE) pub_date = models.DateTimeField(auto_now_add=True) last_name = models.CharField(max_length=100, verbose_name="Фамилия") create data within a personal data class additional(models.Model): student = models.ForeignKey(Student, related_name = "marks", on_delete=models.CASCADE) class_name = models.CharField(max_length=100) additional data is stored def create_resume(request): context = {} additionalFormset = modelformset_factory(additional, form=additionalForm) form = StudentForm(request.POST or None) formset = additionalFormset(request.POST or None, queryset= additional.objects.none(), prefix='additional') if request.method == "POST": if form.is_valid() and formset.is_valid(): try: with transaction.atomic(): student = form.save(commit=False) student.save() form.save_m2m() for guar in formset: data = guar.save(commit=False) data.student = student data.save() except IntegrityError: print("Error Encountered") return redirect('summary_vacancy:meine_biografiess') context['formset'] = formset context['form'] = form return render(request, 'summary_vacancy/create_resume.html', context) I saved an additional model I have to add the "id" myself when I create new data How can I save the User model "id" transaction.atomic(): i don't understand for 3 modules -
Setting custom pagination in Django
I'm trying to set a custom pagination for my API endpoint, where if there is a filter in the URL, Django must return a specific amount of records, and another amount of records if there isn't any filter. I have the following code: valid_filters = {'Name', 'Date'} def _has_valid_filters(iterable): return not valid_filters.isdisjoint(iterable) class MyPagination(LimitOffsetPagination): def get_page_size(self, request): if _has_valid_filters(request.query_params.items()): return 15 else: return 30 class MyView(viewsets.ModelViewSet): pagination_class = MyPagination http_method_names = ['get'] serializer_class = My_Serializer def get_queryset(self): valid_filters = { 'Name': 'Name', 'Date': 'Date__gte', } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} queryset = Model.objects.filter(**filters) return queryset The problem with this code is that the pagination is always the same. While MyPagination is called, it looks like get_page_size is never called. Can anyone help me out on this? -
Django-3.1/DRF/React: Unable to save nested images (linked through GenericRelation)
I am building a Django+DRF/React app (simple blog app) and i am facing difficulties saving nested images Model Structure Model: Post Children: details: ContentType Model ( DRF: save is successfull ) images: ContentType Model ( DRF : save is not successfull ) Process Send images from <input type="file" multiple /> Process data through FormData Catch request.data and process it class PostFormView(generics.RetrieveUpdateDestroyAPIView): queryset = Post._objects.is_active() serializer_class = PostModelSerializer permission_classes = (IsOwnerOr401,) parser_classes = (parsers.MultiPartParser,parsers.JSONParser, parsers.FormParser, parsers.FileUploadParser) lookup_field = 'slug' lookup_url_kwarg = 'slug' def get_queryset(self): return super().get_queryset().annotate(**sharedAnnotations(request=self.request)) def update(self, request, *args, **kwargs): data = request.data _images = data.getlist('images') images = [] for _ in _images: if isinstance(_, dict): images.append(images) continue images.append({'image': _, 'object_id': self.get_object().pk, 'content_type': self.get_object().get_content_type().pk}) data['images'] = images print(data) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): instance._prefetched_objects_cache = {} return Response(serializer.data) Save images (FAIL): class MediaModelSerializer(ContentTypeModelSerializer): # inherits object_id & content_type fields just to avoid writing them over and over alongside (create & update fns) class Meta: model = Media fields='__all__' class PostModelSerializer(WritableNestedModelSerializer): is_active = serializers.BooleanField(default=True) path = serializers.HyperlinkedIdentityField( view_name="api:post-detail", lookup_field='slug') images = MediaModelSerializer(many=True) details = DetailModelSerializer(required=False, many=True) # annotated fields is_author = serializers.BooleanField(read_only=True, default=False) class Meta: model = Post … -
Proper URL for Django Translation
I have two flag icons and I am willing to give them URLs to determine which language should be displayed using Django translation. Though, I am kind of confused about this. How may I do such a thing? HTML: <ul class="navbar-nav d-block d-lg-none ml-auto mr-3"> <li class="nav-item"> <a href="{% url 'products'%}"><div class="ukflag mr-1"></div></a> <a href="fa-ir/{% url 'products' %}"><div class="irflag"></div></a> </li> </ul> Products.Views.py: from django.shortcuts import render from django.views.generic import TemplateView class ProductPageView(TemplateView): template_name = 'products.html' URLs.py: from django.contrib import admin from django.urls import include, path from home.views import HomePageView from products.views import ProductPageView from django.conf.urls.i18n import i18n_patterns from django.utils.translation import gettext_lazy as _ urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path("", HomePageView.as_view(), name='home'), path(_('products/'), ProductPageView.as_view(), name='products'), prefix_default_language = False ) -
ModuleNotFoundError: No module named 'useracc' When deploying to heroku
Actually I m deploying my project to heroku to check how its working. I have created an app for user registrations and login management. App is working fine in the development server. I have registered the app in the settings installed app. When i am trying to deploy the app in the heroku, it's failing continuously with the same error module not found. below is my traceback of the error. Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 971, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'useracc' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for … -
django Page not found (404), map cannot be found
I was working on this django project where I keep getting this error when I am trying to access sightings/map Error Message: Page not found (404) Request Method: GET Request URL: http://35.188.51.159/sightings/map/ Raised by: sightings.views.detail" And the terminal is prompting: Not Found: /sightings/map/ [20/Oct/2020 15:43:07] "GET /sightings/map/ HTTP/1.1" 404 1742 Here is my sightings/views.py file which gives the map: def show_map(request): sightings = Squirrel.objects.all()[:100] context = { 'sightings': sightings } return render(request, 'sightings/map.html', context) And the sightings/urls.py from django.urls import path from . import views app_name = 'sightings' urlpatterns = [ path('', views.index, name='index'), path('add/', views.add, name='add'), path('stats/', views.stats, name='stats'), path('<squirrel_id>/', views.detail, name='detail'), path('map/', views.show_map, name='show_map'), ] All my other functions work just fine, the only issue is map. -
Django view for Stripe Payment Intent
I am trying to make a Django REST view which creates a PaymentIntent object for Stripe and send the client the client-secret. This is the code for this handler in javascript, how would It look for a Django View? : import Stripe from "stripe"; const stripe = new Stripe(process.env.SECRET_KEY); export default async (req, res) => { if (req.method === "POST") { try { const { amount } = req.body; // Psst. For production-ready applications we recommend not using the // amount directly from the client without verifying it first. This is to // prevent bad actors from changing the total amount on the client before // it gets sent to the server. A good approach is to send the quantity of // a uniquely identifiable product and calculate the total price server-side. // Then, you would only fulfill orders using the quantity you charged for. const paymentIntent = await stripe.paymentIntents.create({ amount, currency: "usd" }); res.status(200).send(paymentIntent.client_secret); } catch (err) { res.status(500).json({ statusCode: 500, message: err.message }); } } else { res.setHeader("Allow", "POST"); res.status(405).end("Method Not Allowed"); } }; I basically just want to convert the above handler into a Django view but I don't know what the correct syntax is. -
How do i access my webcam with python (Django) from the browser with the help of HTML and Javascript?
I am trying to create a web-app and I need to get video input from the webcam into Javascript or HTML and pass it to Python (Django) where I can use OpenCV with each frame. -
custom context_processor gives empty queryset
I have added a simple context_processors as follows, even though data is there, its output is empty, could anybody see something missing? context_processorys.py from .cms_models import Logo def custom_logos(request): return { 'obj': Logo.objects.all() } template config TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'client_apps.context_processors.custom_logos', ], }, }, ] client_apps is the name of my app, and if I do {{obj}} in base template it gives empty queryset -
passing model attributes to URL in Django
I am new to Django. I have a model with 2 fields called id (as pk) and region.I have a page to return objects in each region.There are 10 regions and I need to pass region number to url to retrieve data from db filtering that region. Here is my code : views.py def render_pdf_view(request, *args, **kwargs): pk = kwargs.get('pk') *********here i need to get region from clicked button instead of pk************* data = MyModel.objects.filter(region=pk) template_path = 'pdf/Pdf.html' context = {'data':data} return response urls.py path('pdf/<pk>/', render_pdf_view, name='pdf-data') ***I need to pass region instead of pk*** template <a href="{% url 'application : pdf-data' ? %}"> export pdf </a> I don't know how to pass the region from clicked button to view and then pass it to url. Any help would be appreciated. -
API for delevery of fodd
The component provides an API for communicating with other components: Accepts and saves zones as a set of coordinates; Accepts the data of Couriers with reference to the delivery area; Accepts the coordinates of the delivery location and returns the Courier data and the delivery area ID. Not quite sure what models I should make and how it should work, would be grateful for a couple of tips -
Django registraton error appearing as one string
I have a registration page and I and trying to display the validation error message to the user. When I try to pass the error message to an alert is appears as a single alert with the list as a single string. I cannot get it to appear as multiple alerts. views.py def register_page(request): form = CreateUserForm() context = {'form': form} if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('dashboard:login') else: errors = dict(form.errors.items()) error_messages = [] for i in errors.keys(): for j in errors[i]: error_messages.append(j) messages.info(request, error_messages) return render(request, 'main/register.html', context) register.html {% for message in messages %} <div class="error-message alert alert-danger bottom" role="alert"> <div> <a class="close" href="#" data-dismiss="alert">×</a> {{ message }} </div> </div> {% endfor %} screenshot -
How to override Django admin delete_selected_confirmation.html
In my Django admin. If I delete anything in superadmin or inside an user created by superadmin it shows a confirmation page. I have delete_confirmation.html in my templates under my admin and in my another app. if i change anything in it or add a line it doesn't change plus it shows objects in my page which i don't want. i don't know how to override it.Plese refer to the image.My delete confirmation page -
Uncaught TypeError: Cannot read property 'sWidth' of undefined using jquery datatable
I am trying generate a dynamic table using. Table's header is dynamic on the basis of month. When I load the page an error is showing. Error: Uncaught TypeError: Cannot read property 'sWidth' of undefined When i inspect the table, I see there is two table header. I dont how there is two header. how can i solve this error? HTML: <table id="monthly-attendance-status-table" class="table table-bordered table-sm" cellspacing="0" width="100%"> <thead style="color: #73879C;" > <tr id="monthly-attendance-status-table-header"></tr> </thead> <tbody id="monthly-attendance-status-table-rows"></tbody> </table> Ajax function: function fetchMonthlyAttendanceStatus(){ var dateSelected = $("#selected-month").html(); array = yearMonthArr($("#selected-month").html()); year = array[0]; month = array[1]; $.ajax({ type: 'GET', url: '{% url "attendance:ajax-monthly-attendance-status" %}', data: { 'month': month, 'year': year }, dataType: 'json', success: function (data) { $("#monthly-attendance-status-table-header").empty(); $("#monthly-attendance-status-table-rows tr").remove(); $("#monthly-attendance-status-table-header").append(`<th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">ID</th> <th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">Name</th>`); var monthS = month.slice(0, 3); var dayLst = data.day_lst; for (var i = 0; i < dayLst.length; i++) { if (dayLst[i] < 10) { dayLst[i] = '0' + dayLst[i]; } var date = dayLst[i] + '-' + monthS; $("#monthly-attendance-status-table-header").append(`<th class="text-center" style="border-bottom: 2px solid #EAEAEA; font-weight:normal;">${date}</th>`); } var employeeIdLst = data.employee_id_lst; var employeeNameLst = data.employee_name_lst; var employeeStatusLst = data.employee_attendance_status_lst; for (var i = 0; i < employeeIdLst.length; i++) … -
alternative to webapp2.WSGIApplication after migrating to google cloud ndb
I migrated from google.appengine.ext.webapp and ran into an issue with webapp2.WSGIApplication. I am using Django as the backend the main part looks like this application =webapp2.WSGIApplication([ ('/warmup', warmupHandler) ('/api/layer', LayerService), debug=False) def main(): google.appengine.ext.webapp.util.run_wsgi_app(application) if __name__ == '__main__': main() I have tried using this code snippet provided by google cloud as a replacement and it did no help. def wsgi_middleware(app): client = ndb.Client() def middleware(request): with client.context() return app(request) return middleware They also have code snippits but i think this is for Flask, and i use django def ndb_wsgi_middleware(wsgi_app): def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware -
Why I can't customize templates in Django-Oscar?
I'm trying to customize the base template by following the documentation. But the template doesn't respond to my changes in any way. What am I doing wrong? My template's path from location(): .../django_shop/frobshop/frobshop/templates My structure of project: My settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ location('templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.contrib.messages.context_processors.messages', # Oscar specific 'oscar.apps.search.context_processors.search_form', 'oscar.apps.communication.notifications.context_processors.notifications', 'oscar.apps.checkout.context_processors.checkout', 'oscar.core.context_processors.metadata', ], 'debug': DEBUG, } } ] My base.html: {% extends 'oscar/base.html' %} {% load i18n %} {% block title %} {% trans 'test title' %} {% endblock %} test -
How can I download the most recent uploaded file from the django admin?
I'm trying to create a efficient way to download the most recently uploaded file from the django admin. The idea is that every month or so, I go in the django admin and upload a excel file. That file will later be downloaded using a button (easy stuff). But what I have now (which isn't efficient), is that every month I upload a file and change the path from the button. This requires understanding of basic html and django, which my users wont understand. To summarize the idea, here is a list: Upload a file every month or so Have the button in html download the most recent file added (automatically) I have thought of many things, like for example having a timestamp set when uploading the file, and have the button download the file with the most recent "date created". But, I couldn't get that to work, and even if I did, would that be an easy/recommended way of doing this? I have also thought of the ability for one to rename the file, but again, you'd need to have a basic understanding of the django admin, which isn't what I want my users to have to do. Is … -
how to add a course to user courses list after payment in django
Imagine you have a store selling training courses. You want to add a course to the list of user-purchased courses. Assuming the purchased course ID is 3, how should we add it to the list of purchased user courses? What method should be used? I tried these code: purchased_course = Course.objects.get(id=3) # for example user_courses_list = request.user.profile.courses.all() user_courses_list.append(purchased_course) but this code didnt work... -
Is it right way to make a copy of instance in Django rest framework?
The main aim is to create a duplicate of the existing document with the same content but different titles. To achieve this, I decided to implement another serializer with the custom create method. I have to modify the view class and dynamically determine what kind of endpoint was called to choose the appropriate serializer. My solution works for me, but I doubt that the solution is correct. If you have any idea about this please tell me. Thank you in advance for sharing your experience. I had the following at the beginning (before modification): model.py ... class Document(models.Model): title = models.TextField('name', unique=True) content = models.TextField('content', default='') view.py ... class DocumentViewSet(viewsets.ModelViewSet): queryset = Document.objects.all() serializer_class = DocumentSerializer serializer.py ... class DocumentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Document fields = ['id', 'url', 'title', 'content'] url.py ... router = SimpleRouter() router.register(r'documents', views.DocumentViewSet, basename='document') My current solution is to modify the following files like these: serializer.py ... # add new serializer class DuplicateDocumentSerializer(serializers.HyperlinkedModelSerializer): parent = serializers.HyperlinkedRelatedField(view_name='document-detail', queryset=Document.objects.all(), write_only=True) content = serializers.ReadOnlyField() def create(self, validated_data): title = validated_data.get('title') parent_doc = validated_data.get('parent') content = parent_doc.content doc = super().create({ 'title': title, 'content': content, }) doc.save() return doc class Meta: model = Document fields = ['id', 'url', 'title', 'content', … -
If I have two Django projects that need to be hosted in separate locations, what is the simplest way to share database information?
A client wants a CMS and a website, both for handling customers (client handles customers onsite as well as online). Here's the tricky part. He wants the CMS onsite, as only employees will be using it, and he wants the website to be hosted online (such as namecheap). Since both of these will have a lot of common information (such as items, prices, customer information), what is the best way to handle this at the database level? Is it ridiculous to sync every 15-30 minutes for example if I put two separate databases? Is it best to have one database and have the other system connect to it? How secure can I make that? -
Updating ManyToMany of a custom user DRF best practice
I've been struggling to understand how one would update a M2M-field in the django rest framework that is between a custom user and some random field. I should mention I'm using Djoser as authentication. Lets say I have a custom user Models: class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) paying_user = models.BooleanField(default=False) subscribed_companies = models.ManyToManyField('myapp.Company') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserAccountManager() def __str__(self): return f"{self.email}' account" class Company(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class Meta: ordering = ['name'] My serializers Imports - serializers.py: from django.contrib.auth import get_user_model from djoser.serializers import UserCreateSerializer from rest_framework import serializers from apartments.models.company_model import Company User = get_user_model() class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ('email','password', 'paying_user', 'subscribed_companies') class UserCompanyListSerializer(serializers.ModelSerializer): #Is this a reasonable way to serialize a M2M-field? subscribed_company_ids = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=Company.objects.all(), source='subscribed_companies') class Meta: model = User fields = [ 'subscribed_company_ids' ] class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name',) As you can see, I've attached a M2M-field on the custom user itself, instead of using a OneToOne-field where I store custom data. I'm not sure this is the best way to do it. The idea is that a user should … -
Redirects behind Apache ReverseProxy
My Setup I have an apache2 (2.4 on ubuntu server) webserver which should serve a django and a ruby webapplication on: Ruby: localhost:7000 Django: localhost:8000 Django static files: localhost:9000 All requests are passed to the ruby application, but those with /django/ in front. Another server is serving the static files under /static/. My basic VirtualHost settings <VirtualHost *:443> ServerAdmin some@email ServerName example.com DocumentRoot /var/www/html # Logging SSLEngine On # SSL Certificates SSLOptions +StdEnvVars RequestHeader set X_FORWARDED_PROTO 'https' ProxyPass /django/ http://localhost:8000/django/ ProxyPassReverse /django/ http://localhost:8000/django/ ProxyPass /static/ http://localhost:9000/static/ ProxyPassReverse /static/ http://localhost:9000/static/ ProxyPass / http://localhost:7000/ ProxyPassReverse / http://localhost:7000/ <Location /> ProxyHTMLURLMap "http://localhost:7000" "/" ProxyPassReverse "/" </Location> </VirtualHost> Excuse I had to include the ProxyHTMLURLMap, because when my ruby application got a POST I was redirected to localhost:7000, which is not reachable from the outside. I seems to do what I want it to do, but I am quite unsure about it. The problem My Django application does redirect to an external website, with https://externalsite.com/somesite.php?added=load which is now redirected to https://example.com/somesite.php?added=load I would really appreciate if someone shed a bit of light on the subject. -
Django - order_by multiple related fields doesn't work
I am trying to order a qs by multiple related fields. I have a User and Credits model. Every User has a related Credits object. I want to rank/order a list of Users based on multiple fields in the Credits object: credits (amount) games_played_count (amount) last_game_credits (amount) Hence, if two players have an equal amount of credits the one with the highest games_played_count wins. If that is the same the one with the highest last_game_credits wins. Models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) username = NameField(max_length=25, unique=True) class Credits(models.Model): credits = models.IntegerField(default=1000) year = models.IntegerField(default=date.today().isocalendar()[0]) week = models.IntegerField(default=date.today().isocalendar()[1]) games_played_count = models.IntegerField(default=0) last_game_credits = models.IntegerField(null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="credits", on_delete=models.CASCADE) class Meta: unique_together = ('year', 'week', 'user') View: def get_queryset(self): year = self.request.query_params.get('year', None) week = self.request.query_params.get('week', None) if week and year is not None: prefetchCredits = Prefetch('credits', queryset=Credits.objects.filter(year=year, week=week)) rankings = User.objects.prefetch_related(prefetchCredits) \ .annotate(creds=Max('credits__credits'), \ gpcreds=Max('credits__games_played_count'), \ lgcreds=Max('credits__last_game_credits')) \ .order_by('-creds', '-gpcreds', 'lgcreds) return rankings The ordering on a single related field works but not on multiple related fields in order_by().