Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a function for organising objects on the template
I am trying to create a template for a blog landing page. While the politics object is less than four, I want the first for loop to be executed. **political.html {% extends 'index.html' %} {% block content %} {% for politics in politics %} <div class="post-entry-1 col-lg-4 box mx-1"> <a href="single-post.html"><img src="{{politics.image.url}}" alt="" class="post_img"></a> <div class="post-meta"><span class="date">{{politics.category}}</span> <span class="mx-1">&bullet;</span> <span>{{politics.created_at}}</span></div> <h2 class="mb-2"><a href="single-politics.html">{{politics.title}}</a></h2> <span class="author mb-3 d-block">Ole Pundit</span> <p class="mb-4 d-block">{{politics.body|truncatewords:75}}</p> </div> {% if politics > 4 %} {% for politics in politics %} <div class="post-entry-1 border-bottom"> <div class="post-meta"> <span class="date">Culture</span> <span class="mx-1">&bullet;</span> <span>Jul 5th '22</span> </div> <h2 class="mb-2"> <a href="single-post.html">How to Avoid Distraction and Stay Focused During Video Calls? </a> </h2> <span class="author mb-3 d-block">Jenny Wilson</span> </div> {% endfor %} {% endif %} {% endfor %} {% endblock %} But once the count of the political posts exceeds 4 I want the second for loop to be executed. Ideally, the function is supposed to help me organise where the posts appear on the landing page. **view.py from django.shortcuts import render from .models import Post, Politics from django.views.generic import DetailView # Create your views here. def index(request): return render(request, 'index.html') def allposts(request): posts = Post.objects.all() return render(request, 'allposts.html', {'posts':posts}) def … -
UWSGI - Different Flask UPLOAD_FOLDER for each worker/process running
Is it possible to have a different UPLOAD_FOLDER for every UWSGI worker? app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 8 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 10 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 9 (default app) app-python | >>> Files will be uploaded in: /app-python/upload app-python | WSGI app 0 (mountpoint='') ready in 16 seconds on interpreter 0x558d526ffae0 pid: 1 (default app) To explain further, I would like each worker to have a separate upload folder, app-python/upload1 , app-python/upload2 and so on. The reason I'm asking for this request is I think this is causing some files to be overwritten and the output I get from the app doesn't make any sense, and the only logical reason is that the workers are overwriting each other's files. Please let me know if I'm right, and if I am, please tell me if I can set a different upload folder for each worker. I'm also going to … -
How do I increase database variable by 1 using put method is JS?
I am making a web app similar to twitter that allows users to like a post. In order to make changes to the database, I created an API that allows one to use GET, PUT, or POST methods in order to access or make changes to the database. I am using a Django Framework database and am using javascript to send fetch requests to the API. My problem is that I am trying to use a put method to set the "likes" attribute of a post equal to 1 more than the previous number of likes the post had. I don't know how to do this. Below is my javascript function that runs once a post is liked. I tried to access the number of likes a post has and set it equal to a variable. However, that is not working. function likePost(postID){ var postLikes; fetch('/posts/' + postID) .then(response => response.json()) .then(post => { postlikes = post.likes }) fetch('/posts/'+postID, { method: 'PUT', body: JSON.stringify({ likes: postLikes++, liked: true }) }) console.log(postLikes) } For some reason, the console.log returns NotaNumber, meaning that postlikes is not set equal to post.likes and is never instantiated. Thus, "likes" is never set equal to postLikes++ … -
how to make the same button in a django html page turn on different LEDs
I have built a web application using django framework and put it in a raspberry pie 3 b+ in order to controle LEDs to indicate the location of specific products in the stock and make finding them easy and more efficient. my problem is that right now the button used to light up the LEDs is hadcoded with the url of a single LED, this the only way that I managed to make it work. I want to make the button dynamically change the LED that is going to light up for example based on the the Refrences id. html page list_references.html <div class="jumbotron"> <div class="header">{{header}}</div> <form method='POST' action=''>{% csrf_token %} {{form|crispy}} <input type="submit" value='Search'/> <br><br> <a href="/Ajouter_references"><div class="btn btn-primary mybutton">Ajoute Référence</div></a><br><br> </form> <br> <table class='table'> <thead> <tr> <th>REF</th> <th>DESIGNATION</th> <th>INDICE</th> <th>EMPLACEMENT</th> <th>NUM</th> <th>CLIENT</th> <th>LOCATION</th> <th>ETAT</th> <th>SUIVI</th> <th>SUPPRIMER</th> </tr> </thead> {% for instance in queryset %} <tr> <td><a href="{% url 'update_ref' instance.id %}">{{instance.Ref}}</a></td> <td>{{instance.Designation}}</td> <td>{{instance.Indice}}</td> <td>{{instance.Emplacment}}</td> <td>{{instance.Num}}</td> <td>{{instance.Client}}</td> <td><a href="{% url 'led1' %}"><BUTTON onclick="",>INDIQUER POSITION</BUTTON></a></td> <td>{{instance.Statut}}</td> <td><a href="{% url 'suivi_ref' %}"><BUTTON>SUIVI L'ECRAN</BUTTON></a></td> <td><a href="{% url 'delete_ref' instance.id %}"><img src="{% static 'img/del.png' %}"></a></td> </tr> {% endfor %} </table> </div> </main> views.py led1,led2,led3= 3,5,7 rpi.setwarnings(False) rpi.setmode(rpi.BOARD) rpi.setup(led1, rpi.OUT) rpi.setup(led2, rpi.OUT) rpi.setup(led3, rpi.OUT) … -
How to set xframe options properly to display a pdf
So I get this error when trying to render a pdf in html with Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. I already tried Setting X_FRAME_OPTIONS = 'SAMEORIGIN' Using @xframe_options_sameorigin as decorator to my view Removed the xframe package in the settings nothing seems to work so I don't know what to do anymore. -
Django test with fixtures gives ForeignKeyViolation or IntegrityError
I am trying to write test cases for the Django RestAPI that we have but I have an issue with the fixtures loading. Everything works correctly when I have only one TestCase but when I add a second TestCase in a second django app I get django.db.utils.IntegrityError. My original intention was to create a general TestCase where I set up the most used objects in the setUpTestData function and make the other tests inherit from that one. Things I have tried: Using APITestCase from rest_framework and TestCase from django Not using inheritance, and having both files using TestCase from django Using setUp method instead of setUpTestData Using call_command from django.core.management in the setUpTestData method instead of creating the fixtures in each class in the class variable Declaring the fixtures only in the TestCase that is executed first (this makes the other TestCase have an empty DB, so it it clear that for each TestCase info is recreated) Changed the order of the files in the fixtures variable When I comment one of the test files the other works and vice-versa. When I used the call_command with verbose=2, the fixtures in the first file executed work perfectly, and it breaks just … -
How to I get the path to a file with Django?
I am currently using Django's forms to create a FileField that allows the user to upload a file. However, after I select the file, it creates an object of type django.core.files.uploadedfile.InMemoryUploadedFile, which is a copy of the original file. How would I go about to get the original path of this file so I can either modify or replace it? # forms.py class UploadFile(forms.Form): file = forms.FileField(label="Select File: ", required=True) # views.py def get_path(response): context = {} if response.method == "POST": form = UploadFile(response.FILES) if form.is_valid(): file = form.cleaned_data["file"] # Is there a way to get the original file path or should I just not use FileField? print("The File Path Here") -
How to query objects from parent table along with data from related model
I have a model 'Product' to upload products. class Product(BaseModel): ... ... class Meta: db_table = TABLE_PREFIX + "product" I have another table with product as foreignkey. class ProductImage(BaseModel): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(upload_to='product') class Meta: db_table = TABLE_PREFIX + "product_image" In home page i want to display these products. I have the home view as def home(request): category_obj = Category.objects.all() product_obj = Product.objects.all().order_by('-id') context = { "title": "Home", "product_obj": product_obj, "category_obj": category_obj, } return render(request, "home/index.html", context) In the template I want to display the products along with the images. I am able to display all the details in the template except images. <div class="dFlex product-list-wrap"> {% for product in product_obj %} <div class="img-wrap"> <img src="" alt="Product Image"> </div> <h4>{{ product.name}}</h4> <p>{{ product.description}}</p> {% endfor %} </div> How do i display images on my template? How can I query images also while querying products? Thank you -
How to test two django forms that are in the same view
So I have a view that handles two different forms in the same POST request. Previously the testing was easy because i had only one form so it would be something like: def test_post_success(self): response = self.client.post("/books/add/", data={"title": "Dombey and Son"}) self.assertEqual(response.status_code, HTTPStatus.FOUND) self.assertEqual(response["Location"], "/books/") If i have a second form with a 'prefix' how would i construct the data object of the request. Im thinking of: form_1_data = {foo} form_2_data = {bar} response = self.client.post("/books/add/", data={form_1_data, form_2_data) But it clearly does not work -
Trigger events in dropdowns using "Select2" library from Django Forms
I'm using the "select2" library to work with model-bound, related and dependent dropdowns and I want to handle various events like: change, click, blur and focus; however, only the change event is executed, but, when I use a regular dropdown, all four events work properly. How can I handle the dropdown events, noted above, in conjunction with the "select2" library? The idea is populate "Office" drop-down with previous selection of "Corporation" and "Division" drop-down, and those dropdowns obey the four events. dropdowns: coporation > division > office # forms.py class NewEmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__' widgets = { 'coporation': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), 'division': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), 'office': forms.Select( attrs={ 'class': 'form-control select2', 'style': 'width: 100%', }, ), # template.html <!-- form --> <form method="post" id="empleado_form" data_offices_url="{% url 'employees:ajax_get_offices' %}" novalidate> <fieldset> {% csrf_token %} <div class="col-sm-4 form-group {% if form.corporation.errors %}has-error{% endif %}"> {{ form.corporation.label }} {{ form.corporation }} <div class="text-danger"> {{ form.corporation.errors }} </div> </div> <div class="col-sm-4 form-group {% if form.division.errors %}has-error{% endif %}"> {{ form.division.label }} {{ form.division }} <div class="text-danger"> {{ form.division.errors }} </div> </div> ... </form> <script> $(function() … -
how to fix "can't compare offset-naive and offset-aware datetimes" in python
Here I'm using Django and comparing timing. But I'm unable to do that. In the following code. wts value which is time value coming as a string. If it comes in string type then first I convert that in regular time after that I subtract 5 hours from it. and then compare if it is less than current or not.. if not wts: raise ValueError('When to send(wts) require ') if type(wts) is str: wts_compare = parser.parse(wts) print("wts time type ->>>" ,type(wts_compare),wts_compare) wts = wts_compare - timedelta(hours=5) if wts_compare <= timezone.now(): raise ValueError('when to send (wts) must be a future date-time') else: wts = wts-timedelta(hours=5) if wts <= timezone.now(): raise ValueError('when to send (wts) must be a future date-time') -
Django app doesn't validate JWT token or doesn't see JWT token from microsoft Azure via React-front
There is an application - front on React, back on Django. There is also an application on Microsoft Azure for user authentication. I use this tutorial to validate the token: Validating JSON web tokens (JWTs) from Azure AD, in Python Following it, 2 files are created. demo.py: import jwt from jwksutils import rsa_pem_from_jwk # To run this example, follow the instructions in the project README # obtain jwks as you wish: configuration file, HTTP GET request to the endpoint returning them; jwks = { "keys": [ { "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk", "nbf": 1493763266, "use": "sig", "kty": "RSA", "e": "AQAB", "n": "tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmLiWZizpb-h0qup5jznOvOr-Dhw9908584BSgC83YacjWNqEK3urxhyE2jWjwRm2N95WGgb5mzE5XmZIvkvyXnn7X8dvgFPF5QwIngGsDG8LyHuJWlaDhr_EPLMW4wHvH0zZCuRMARIJmmqiMy3VD4ftq4nS5s8vJL0pVSrkuNojtokp84AtkADCDU_BUhrc2sIgfnvZ03koCQRoZmWiHu86SuJZYkDFstVTVSR0hiXudFlfQ2rOhPlpObmku68lXw-7V-P7jwrQRFfQVXw" } ] } # configuration, these can be seen in valid JWTs from Azure B2C: valid_audiences = ['d7f48c21-2a19-4bdb-ace8-48928bff0eb5'] # id of the application prepared previously issuer = 'https://ugrose.b2clogin.com/9c2984ff-d596-4e5c-8e74-672be7b592e3/v2.0/' # iss class InvalidAuthorizationToken(Exception): def __init__(self, details): super().__init__('Invalid authorization token: ' + details) def get_kid(token): headers = jwt.get_unverified_header(token) if not headers: raise InvalidAuthorizationToken('missing headers') try: return headers['kid'] except KeyError: raise InvalidAuthorizationToken('missing kid') def get_jwk(kid): for jwk in jwks.get('keys'): if jwk.get('kid') == kid: return jwk raise InvalidAuthorizationToken('kid not recognized') def get_public_key(token): return rsa_pem_from_jwk(get_jwk(get_kid(token))) def validate_jwt(jwt_to_validate): public_key = get_public_key(jwt_to_validate) decoded = jwt.decode(jwt_to_validate, public_key, verify=True, algorithms=['RS256'], audience=valid_audiences, issuer=issuer) # do what you wish with decoded token: … -
How to filter ForeignKey choices in a Django admin inline form (TabularInline)?
I have these 4 models: class Model_A(models.Model): ... class Model_B(models.Model): model_a = models.OneToOneField("Model_A", primary_key=True) model_c_fk = models.ForeignKey("Model_C") model_d_fk = models.ForeignKey("Model_D") class Model_C(models.Model): choice_c = models.CharField() class Model_D(models.Model): model_c_fk = models.ForeignKey("Model_C") choice_d = models.CharField() In the admin form of the Model_A I want to filter the choices on Model_D based on the selected ForeignKey model_c_fk on Model_B_Inline. class Model_B_Inline(admin.TabularInline): model = Model_B def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "model_d_fk": kwargs["queryset"] = Model_D.objects.filter(model_c_fk=1) # Should be model_c_fk="Model_B.model_c_fk" return super().formfield_for_foreignkey(db_field, request, **kwargs) @admin.register(Model_A) class Model_A_Admin(admin.ModelAdmin): inlines = [Model_B_Inline] It works with the formfield_for_foreignkey method if I pass just the id as an integer for testing purpose, but I don't know how I could access the value of the selected ForeignKey model_c_fk on Model_B. How could I achieve that? -
How to login to Django Admin panel with user I created in this panel? User model was extended
the model itself: from django.db import models from django.contrib.auth.models import AbstractUser class UserModel(AbstractUser): class UserType(models.TextChoices): MANAGER = 'm', 'Manager' CUSTOMER = 'c', 'Customer' first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) type = models.CharField(choices=UserType.choices, max_length=1) USER_MODEL is registered in setting in admin.py it's registered as: from django.contrib import admin from .models import UserModel admin.site.register(UserModel) I can create new model in the panel with existing superuesr I have. i.e. - it works. I can add new super users with manage.py and they appear in the same place in the panel. But later on I can't login with users I created in that panel. saff status - checked. The problem might be with passwords, because those created with createsuperuser shown hashed in the panel. or idk even. If I did smth completely wrong - let me know, I only need to extend users to have a couple of additional fields. django version 3.2 -
How to add new fields in custom user model?
I made a custom user model and It works perfectly. But Problem is, I tried many times to add new fields like first_name, last_name, phone_number, and so on but not working. It shows an error. What will be the relevant solution for it, how can I fix this and add new fields to the custom user model? models.py: class User(AbstractUser): email = models.EmailField( max_length=150,unique=True,error_messages={"unique":"The email must be unique."}) REQUIRES_FIELDS = ["email"] objects = CustomeUserManager() def __str__(self): return str(self.pk) + "." + self.username form.py: from django import forms from .models import User class UserRegistrations(forms.ModelForm): class Meta: model = User fields = ("username", "email", "password",) def clean_username(self): username = self.cleaned_data.get('username') model = self.Meta.model user = model.objects.filter(username__iexact=username) if user.exists(): raise forms.ValidationError( "Ther User already exist with the given username") return self.cleaned_data.get('username') def clean_email(self): email = self.cleaned_data.get('email') model = self.Meta.model user = model.objects.filter(email__iexact=email) if user.exists(): raise forms.ValidationError( "The email already exist with the given email") return self.cleaned_data.get('email') def clean_password(self): password = self.cleaned_data.get('password') confirm_password = self.data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Password do not match!") return self.cleaned_data.get('password') manager.py: from django.contrib.auth.base_user import BaseUserManager class CustomeUserManager(BaseUserManager): def create_user(self, username, email, password, **extra_fields): if not username: raise ValueError("The user must be set") if not email: raise ValueError("The email … -
How to add multiple rows of data to a single column of an existing instance of a model? Django
view linked to a form, to a model. I'd like to make it so that when I update one of those fields (current-command). It adds that data to another field (Executed_Commands). So then when I add another command later to that models via the form, which will update the Current_Commands field. It will simply add another row entry to the Executed_commands column. Rather then delete the data already in that column and replace it. models.py (relevant section) CHOICES = [ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ] class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) current_commands = models.CharField(choices=CHOICES, max_length=50, null=True), Executed_Commands = models.CharField('Executed_Commands', max_length=2000, null=True) def __str__(self): return str(self.host_id) forms.py (relevant section) class Command_Form(ModelForm): class Meta: model = Command_Node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) views.py (relevant section) def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): form.save() return redirect('home') return render (request, 'update.html', {'host_id':host_id,'form':form}) Any idea on how I would do this?. As I can find … -
Docker permissions issue with Django Tutorial. RUN pip throws error
I am following a Docker / Django tutorial. I am getting an error with RUN pip install -r requirements.txt . from within the Dockerfile. The error is: The command '/bin/sh -c pip install -r requirements.txt .' returned a non-zero code: 1 Here is my docker file: #Set enviornment variables ENV PIP-DISABLE_PIPVERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #Set work directory WORKDIR /code #Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt . #Copy project COPY . . -
How to show subcategories under category type
I need to get the child list under the parent list as a group. class ServiceSerializer(serializers.ModelSerializer): cleaning_type = serializers.CharField(source='cleaning_type.cleaning_type_name') class Meta: model = Service fields = ('id', 'cleaning_type','service_name') class ServiceTypeViewSet(ModelViewSet): serializer_class = ServiceSerializer http_method_names = ["get"] queryset = Service.objects.all() def get_queryset(self): """ This view should return a list of all the service types. """ servicename_list = Service.objects.all() return servicename_list It shows: [ { "id": 1, "cleaning_type": "Lite service", "service_name": "Floors", }, { "id": 2, "cleaning_type": "Lite service", "service_name": "Bathrooms", }, { "id": 3, "cleaning_type": "Lite service", "service_name": "Kitchen", } ] I want this to be in the following format: [ { id: 1, cleaning_type: 'Lite service', service_name: ['Floors', 'bathroom', 'kitchen'], }, { id: 2, cleaning_type: 'Moving cleaning', service_name: ['Kitchen Including All Appliances And Cabinets'], }, ] That means all child elements will be under a separate parent list. Not separate by separate. models.py is here: Cleaning Type Model: class CleaningType(models.Model): cleaning_type_name = models.CharField( _("Select Cleaning Type"), blank=True, null=True, max_length=255) price = models.DecimalField(default=0,max_digits=6, decimal_places=2) def __str__(self): return self.cleaning_type_name Service Model: class Service(models.Model): cleaning_type = models.ForeignKey( CleaningType, on_delete=models.CASCADE) service_name = models.CharField( _("Service Name"), blank=True, null=True, max_length=255) #string type added def __str__(self): return str(self.service_name) I want sub categories under parent caterories. Here cleaning_type … -
django get URL of ImageField
I have model with ImageField: class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=True) icon = models.ImageField(upload_to='images/', blank=True, null=True) In settings.py initialized 2 variables: MEDIA_ULR = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'skyeng/media') in views.py get method: def get(self, request): query_set = Category.objects.all() items_data = [{ 'id': item.id, 'name': item.name, 'icon': item.icon.url} for item in query_set] return JsonResponse(items_data, safe=False) It should return the response as in the example: [ { "id": 1, "name": "Category1", "icon": "http://icon/url" } ] So how i need change my code that icon.url in get method was like in response example? -
how to view page only if the user pass another page first?
what I want to do is when the user wants to access the update and delete View he must to verify his identity by passing his right password if was right will open the views else won't but my problem is how to know if the user has verified himself in the update and delete views urls: app_name = "users" urlpatterns = [ path("login/", UsersLoginView.as_view(), name="login"), path("logout/", UserLogoutView.as_view(), name="logout"), path("register/", UserRegisterView.as_view(), name="register"), path("<str:username>/", UserAccountDetailView.as_view(), name="account"), path( "<str:username>/verify/edit", UserAccountEditView.as_view(), name="verify-edit" ), path( "<str:username>/verify/delete", UserAccountEditView.as_view(), name="verify-delete", ), path("<str:username>/edit/", UserAccountEditView.as_view(), name="edit"), path("<str:username>/delete/", UserAccountDeleteView.as_view(), name="delete"), ] mixins: from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.http import Http404 from django.contrib.auth import get_user_model from django.views.generic import FormView from django.urls import reverse_lazy from django.contrib import messages from django.shortcuts import redirect # Local Imports from . import forms User = get_user_model() class UserPassesHimselfMixin(LoginRequiredMixin, UserPassesTestMixin): """Test if the User who Sent the Reqeust he is the Logged in User""" def test_func(self): return self.request.user == self.get_object() def get_object(self, queryset=None): username = self.kwargs.get("username") qs = User.objects.filter(username=username) if qs.exists(): return qs.first() else: raise Http404("User Not Found") class VerifyUserIdentity(UserPassesHimselfMixin, FormView): """Verify User Identity By Form and Redirect to another Page - provide Form that has ```verify()``` mehtod that return bool value - else Raise … -
What limits are there on the number of fields on a Django model?
What practical limits are there on the number of fields a Django model can have? I'm thinking both at the code level, and at the database level (particularly both Sqlite and Postgres). If the specific version of anything is required then let's say we are talking about the latest LTS version (or nearest equivalent) of everything running on Ubuntu Server. -
Display index of each item of a sorted list in view Django DRF
I am developing an application with a Django backend and the DRF framework for my api. At a given url I would like to display the index (the rank) of each user once the list is sorted on my view. I can't explain it very well so I put two examples at the end of my message. I have not found anything on the internet about how to do this without modifying the template to add a field (I cannot use this solution). Would you have an idea? Thanks ! Below my view : class RankBestPurchaserViewset(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = RankUserAllPurchaseSerializer(queryset, many=True) sortedList = sorted(serializer.data, key=itemgetter( 'amount'), reverse=True) return Response(sortedList) Below my serializer : class RankUserAllPurchaseSerializer(serializers.BaseSerializer): def to_representation(self, instance): return { 'id': instance.id, 'username': instance.username, 'surname': instance.surname, 'amount': float(SaleProduct.objects.filter(sale__sender__username=instance.username).aggregate(Sum('price'))['price__sum'] or 0), 'qty_amount': SaleProduct.objects.filter(sale__sender__username=instance.username).count(), } Below the result : [ { "id": 3, "username": "An20", "surname": "Khalvin", "amount": 426.7, "qty_amount": 110 }, { "id": 1, "username": "AA_ENS", "surname": "gum", "amount": 0.0, "qty_amount": 0 }, { "id": 4, "username": "in22", "surname": "gum", "amount": 0.0, "qty_amount": 0 } ] desired result [ { "index":1, "id": 3, "username": "An20", "surname": "Khalvin", "amount": 426.7, "qty_amount": 110 }, { "index":2, "id": 1, … -
Django admin broken template when using uwsgi
When I start my application using python3 manage.py run server 0.0.0.0:8000 I can access Django admin just fine. However, when I run it using uwsgi the Django admin template is broken. The application works fine, but the website is displayed as simple text, no templates at all. For instance, here's the login page: How can I fix this? This my uwsgi.ini: [uwsgi] chdir = ./src http = :8000 enable-threads = true #harakiri = 300 master = true module = config.wsgi:application #processes = $(UWSGI_PROCESSES) #threads = $(UWSGI_THREADS) #max-worker-lifetime = $(UWSGI_MAX_WORKER_LIFE) workers = 32 thunder-lock = true vacuum = true workdir = ./src add-header = Connection: Keep-Alive http-keepalive = 65000 max-requests = 50000 max-requests-delta = 10000 max-worker-lifetime = 360000000000 ; Restart workers after this many seconds reload-on-rss = 2048 ; Restart workers after this much resident memory worker-reload-mercy = 60 ; How long to wait before forcefully killing workers # Increment the timeout to reach the target app. # http-timeout = 60 lazy-apps = true single-interpreter = true ignore-sigpipe = true ignore-write-errors = true http-auto-chunked = true disable-write-exception = true This is the settings.py for my app: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.2.7. For more … -
Problems with if statement and _set.all Django
I tried two ways to make a filter in the django template, but neither worked for me, I don't know if I'm sending the arguments wrong or if I'm missing something. I need to show a part of the template only if the 'user' is also part of the 'teacher' model (teacher has FK to User). My template: {% if user in user.teacher_set.all %} <tr> <td class="table-text typo-grey"><label class="float-left">Rol</label></td> <td class="rol centered"> <div class="ui input"> <select type="text" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}"> {% for rol in form.rol.field.queryset %} <option value="{{rol.pk}}">{{rol.name}}</option> {% endfor %} </select> </div> </td> </tr> {% endif %} This brings a empty queryset. I also tried creating a templatetag: @register.simple_tag def get_teachers_user(user): teacheruser = models.Teacher.objects.filter( user=user, active=True ) return {'teacheruser': teacheruser.latest('pk')} And then in template: {% get_teachers_user user as teacher_user %} {% if not user in teacher_user.teacheruser %} <tr> <td class="table-text typo-grey"><label class="float-left">Rol {{teacher_user.teacheruser}}</label></td> <td class="rol centered"> <div class="ui input"> <select type="text" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}"> {% for rol in form.rol.field.queryset %} <option value="{{rol.pk}}">{{rol.name}}</option> {% endfor %} </select> </div> </td> </tr> {% endif %} Doesn't work either. Please if you have any advice please comment, also this template is for a FormView. Thanks -
Django/Apache2 CORS Error with CORS_ALLOWED_ORIGINS and Header in apache conf defined
I have my apache conf below: <VirtualHost *:80> Header set Access-Control-Allow-Origin "*" ServerAdmin ... ServerName semanticspace.io ServerAlias www.semanticspace.io ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/cuneyttyler/knowledgebase/knowledge-base-django/static <Directory /home/cuneyttyler/knowledgebase/knowledge-base-django/static> Require all granted </Directory> Alias /media /home/cuneyttyler/knowledgebase/knowledge-base-django/media <Directory /home/cuneyttlyer/knowledgebase/knowledge-base-django/media> Require all granted </Directory> <Directory /home/cuneyttyler/knowledgebase/knowledge-base-django/knowledgebase_python> <Files wsgi.py> Require all granted </Files> </Directory> WSGIPassAuthorization On WSGIDaemonProcess knowledge-base-django python-path=/home/cuneyttyler/knowledgebase/knowledge-base-django python-home=/home/cuneyttyler/knowle> WSGIProcessGroup knowledge-base-django WSGIScriptAlias / /home/cuneyttyler/knowledgebase/knowledge-base-django/knowledgebase_python/wsgi.py </VirtualHost> And my CORS_ALLOWED_ORIGINS in settings.py : CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080', 'http://semanticspace.io', 'http://www.semanticspace.io' ] Despite these, my requests from semanticspace.io results with CORS error. What's the cause of that?