Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Background image does not want to load in css
I am creating a website in Django. I downloaded a html homepage template design on the internet that I want to improve upon and use for my website. since its been designed it came with a CSS file. now when I try to make the improvements specifically add a background image in one of the elements. it refuses to do so. the other elements respond to the CSS style but the background image refuses too. since I'm using Django i had to set up the static files and 'collect static' which I did but when I set that those pics to my background image in my CSS it refuses. here is the html file & css. html <!DOCTYPE html> <!-- Created by CodingLab |www.youtube.com/c/CodingLabYT--> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> Home </title> <link rel="stylesheet" href="{% static 'style.css' %}"> <!-- Boxicons CDN Link --> <link href= 'https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'> <meta name="viewport" content="width=device-width, initial- scale=1.0"> </head> <section class="home-section"> <div class="main" > </div> the class="main" is where I'm trying to add the background-image too. CSS .home-section .main{ background-image: url('https://www.pexels.com/photo/singer- singing-on-stage-beside-guitar-player-and-bass-player- 167636/'); padding: auto; margin: auto; background-size: 50pc; } @media (max-width: 700px) { .sidebar li .tooltip{ display: none; } } I've tried everything but … -
how to create table with dynamically rows and columns with number field in template django
i want to create dynamically rows and columns table in django with number. like the picture below <table border="1"> {% for i in row %} <tr> {% for x in columns %} <td>????</td> {% endfor %} </tr> {% endfor %} </table> -
No idea where I'm getting NoSuchMethodError: '[]'
I am making a demo login app using python framework-django, graphql, flutter like below. This is a very simple app for a test but I'm getting "NoSuchMethodError='[]'", and I'm already spending a number of hours on this issue. Error messages I am getting are below. The user wants to create an account with dsafds@asdfasd.com and dasdfadsf dart_sdk.js:28087 There was an error! Uncaught (in promise) Error: NoSuchMethodError: '[]' Dynamic call of null. Receiver: null Arguments: [0] at Object.throw_ [as throw] (:58141/dart_sdk.js:5348) at Object.defaultNoSuchMethod (:58141/dart_sdk.js:5793) at Object.noSuchMethod (:58141/dart_sdk.js:5788) at callNSM (:58141/dart_sdk.js:5521) at Object._checkAndCall (:58141/dart_sdk.js:5523) at Object.callMethod (:58141/dart_sdk.js:5601) at Object.dsend (:58141/dart_sdk.js:5604) at main._LoginPageState.new._createAccountPressed (:58141/packages/auth_frontend/main.dart.lib.js:1003) at _createAccountPressed.next (<anonymous>) at :58141/dart_sdk.js:39230 at _RootZone.runUnary (:58141/dart_sdk.js:39087) at _FutureListener.thenAwait.handleValue (:58141/dart_sdk.js:34073) at handleValueCallback (:58141/dart_sdk.js:34633) at Function._propagateToListeners (:58141/dart_sdk.js:34671) at _Future.new.[_completeWithValue] (:58141/dart_sdk.js:34513) at async._AsyncCallbackEntry.new.callback (:58141/dart_sdk.js:34536) at Object._microtaskLoop (:58141/dart_sdk.js:39374) at _startMicrotaskLoop (:58141/dart_sdk.js:39380) at :58141/dart_sdk.js:34887 Flutter doctor result is below Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel stable, 2.2.3, on Microsoft Windows [Version 10.0.19043.1165], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 31.0.0) [√] Chrome - develop for the web [√] Android Studio (version 4.1.0) [√] VS Code (version 1.60.0) [√] Connected device (2 available) • No issues found! My flutter project … -
How to solve Django form redirect not working?
I created a form. I want to when the user fills the form and then sends it, redirect a specific page. But in my case, the form is saving successfully but does not redirect the page. How can I solve it? views.py def setup_wizard(request): form = SetupForm(request.POST or None) if request.method == 'POST': if form.is_valid(): setup = form.save() setup.user = request.user setup.save() redirect('dashboard') else: form = SetupForm() context = { 'form': form, } return render(request, 'setup_wizard.html', context) dashboard.urls.py urlpatterns = [ path('', dashboard, name="dashboard"), path('setup', setup_wizard, name="setup"), ] mainproject.urls.py urlpatterns = [ path('admin/', admin.site.urls), path('dashboard/', include('dashboard.urls')), ... ] -
How to fix the "detail":"Invalid Token" issue in django_rest_framework
I tried to implement a simple login/register API with django_rest_framework using DRF authToken module and here's my code : models.py class User(AbstractUser): username =models.CharField(max_length=100) email =models.EmailField('email address', unique=True) first_name =models.CharField('First Name', max_length=255, blank=True, null=False) last_name =models.CharField('Last Name', max_length=255, blank=True, null=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from django.contrib.auth import get_user_model, password_validation from django.contrib.auth.models import BaseUserManager User = get_user_model() class UserLoginSerializer (serializers.Serializer): email = serializers.CharField(max_length=300, required=True) password = serializers.CharField(required=True, write_only=True) class AuthUserSerializer(serializers.ModelSerializer): auth_token = serializers.SerializerMethodField() class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name', 'is_active', 'is_staff') read_only_fields = ('id', 'is_active', 'is_staff') def get_auth_token(self, obj): token = Token.objects.create(user=obj) return token.key class EmptySerializer(serializers.Serializer): pass class UserRegisterSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'password', 'first_name', 'last_name') def validate_email(self, value): user = User.objects.filter(email=value) if user: raise serializers.ValidationError("Email is already taken ...") return BaseUserManager.normalize_email(value) def validate_password(self, value): password_validation.validate_password(value) return value class PasswordChangeSerializer(serializers.Serializer): current_password = serializers.CharField(required=True) new_password = serializers.CharField(required=True) def validate_current_password(self, value): if not self.context['request'].user.check_password(value): raise serializers.ValidationError('Current password does not match ...') return value def validate_new_password(self, value): password_validation.validate_password(value) return value views.py from django.contrib.auth import get_user_model, logout from django.core.exceptions import ImproperlyConfigured from rest_framework import viewsets, status from rest_framework.decorators import action from rest_framework.permissions import AllowAny, … -
Django add a list of other model for cart and product
i am trying to create a shop where users can add products on sale and other users can add them to their cart i can't figure out how can i make a cart contain multiple products and their quantities. class Product(models.Model): name = models.TextField() description = models.TextField() price = models.FloatField() quantity = models.FloatField() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Cart(models.Model): #list of products #list of quantities user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
autogenerate form for function based view
i would like to generate a form using my serializer fields for the browsable api. I've checked and i have seen a way to do it for the class based view(Here is an example for class based view), i am currently using a function based view, i want to the same thing done in that link with a function based api_view. Here is my serializer and my views.py @api_view(["POST"]) def store_notice(request): serializer = CreateNoteV2Serializer(data=request.data) if serializer.is_valid(): response = Database.save("Test_notice", notice_data=serializer.data) if response and response.get("status_code") == 201: return Response( data=response, status=status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST) class CreateNoticeV2Serializer(serializers.Serializer): creator=serializers.CharField(max_length=100) title = serializers.CharField(max_length=100) text = serializers.CharField(max_length=250) photo_url = serializers.CharField(max_length=50) video_url = serializers.CharField(max_length=50) audio_url = serializers.CharField(max_length=50) published = serializers.BooleanField(default=False) date_added = serializers.DateTimeField(default=timezone.now()) last_modified = serializers.DateTimeField(default=timezone.now()) viewed_by = serializers.CharField(max_length=5000, allow_blank=True) def __str__(self): return f"{self.title}-{self.creator}" -
Use multiple JavaScript package in a script tag(mainly bootstrap 5)
hi this is probably a stupid question but I cant find an answer, I am using vanilla js, without any bundler I need to use the Toast bootstrap class, how do I load a js package into a tag script? <script type="text/javascript" src="../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> If I write my script tag as in the code above, I can use the Bootstrap Toast class in the code inside the script tag, but I can't use any other js package, knowing that I can't use an import statement, I am lost but I'm pretty sure it's basic knowledge. What I need is how to use bootstrap5 inside a script tag without using src, there is no bootstrap object on the window object. Keep in mind that I have already import bootstrap5 css and Js elsewhere on the page, I just need to access objects from the package. -
Updating select dropdowns in Bootstrap modal view
I have tried creating a dynamic modal form where a donation type is dependent on an organisation. I am trying to write up my Javascript so that when an organisation is selected the donation types are modified to match this value. Another thing I should mention is I'm working in Django and have template tags attached to both html and javascript. Here are snippets of my code: Javascript window.addEventListener('load', function() { document.getElementById("id_organisation").onchange = function () { var orgs = document.getElementById("id_organisation"); var dTypes = document.getElementById("id_donation_type"); if (orgs[orgs.selectedIndex].value == '-----') { dTypes.disabled = true; dTypes.options.length = 0; dTypes.value = "-----"; return null; } else { dTypes.disabled = false; var orgNames = orgs.getElementsByTagName("option"); var dTypeNames = eval('{{ donation_types|safe }}'); dTypes.options.length = 0; dTypes.options[0] = new Option("-----", "-----"); for (let i=0; i < dTypeNames.length; i++) { if (dTypeNames[i][0] == $(this).val()) { dTypes.options[dTypes.options.length] = new Option(dTypeNames[i] [1],dTypeNames[i][1]); } } console.log(dTypes); return dTypes; } }); HTML Template <div class="row mb-3"> <label for="id_organisation" class="col-md-4 col-form-label text-end"><strong>{{language.forms.organisationLabelName}}</strong></label> <div class="col-md-7"> <select id="id_organisation" name="organisation" class="form-select {{form_values.errorlist.organisation}}" aria-label="Default select example" value="form.fields.organisation.initial" required> <option value="-----" selected>-----</option> {% for id, organisation in form.fields.organisation.choices %} {% if form.fields.organisation.initial == organisation %} <option value="{{ organisation }}" selected>{{ organisation }}</option> {% else %} <option value="{{ organisation … -
Shared authentication across multiple django sites
I have 3 django sites and they are deployed in 3 subdomains let's say like this: a.example.com b.example.com c.example.com They all have 95% things in similar just uses 3 different database and have user login. Problem is I need to login to all 3 of them, why can't I login to one and share it with other 2 sites? I tried using multiple database/routing as described in Django documentation but I cannot share User model across multiple database. So how does sites like google does it? I login to one of their services and all others automatically log me in. Can someone give me proper guideline how to achieve this? -
What is the difference between 'defs' and 'classes' in views?
I wanted to start a new Django project And when I wanted to create my view section, the question came to me which one should I use now? I want to know when we use defs and classes. -
create function for copy object in django model
i need create function to copy object of my model my code: class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title = models.CharField(max_length=250) body = models.CharField(max_length=None) author = models.ForeignKey(Author ,on_delete=models.CASCADE) data_created = models.DateTimeField(auto_now_add=datetime.now) def copy(self): new_post = BlogPost.objects.get(id=self.id).update(data_created=datetime.now) new_post.save() return new_post.id class Comment(models.Model): blog_post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) text = models.CharField(max_length=500) def copy in BlogPost class for copy obejcts and create new object and update data_created to now Which after that i have 2 objects but dosent work what can i do? -
Django rest framework how to change: "This field may not be blank." error message
When I am trying to create a new user model, I am getting the following validation error response: HTTP 400 Bad Request Allow: POST, OPTIONS Content-Type: application/JSON Vary: Accept { "phone": [ "This field may not be blank." ], "name": [ "This field may not be blank." ] } What I want to do is how to change the error message to a custom one. Here is my user serializer code: from rest_framework import serializers from django.contrib.auth import get_user_model class UserSerializer(serializers.ModelSerializer): class Meta: model = get_user_model() fields = '__all__' read_only_fields = ('last_login',) I already override the validate method but that didn't work neither using this solution: extra_kwargs = {"phone": {"error_messages": {"required": "A valid phone number is required"}}} views.py: class UserList(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer (Custom user) User.py: class User(AbstractBaseUser): """ Custom user model based on phone number as the only identifier """ phone = models.CharField(max_length=10, unique=True) name = models.CharField(max_length=50, blank=False) password = None USERNAME_FIELD = 'phone' objects = UserManager() def __str__(self): return self.name User manager.py: class UserManager(BaseUserManager): """ Custom user model manager where the phone is the unique identifier """ def create_user(self, phone, name, **extra_fields): """ Create and save a User using the given phone number and country … -
Django set random password for user once
I have created an extended User model and a form to register it. Since the form is filled out by an admin and not a user, the UserCreationForm has a random password generator to fill out password1 and 2, then set new password. This is great for a new user, but every time an admin edits the user profile, it will set a new password. I've looked at a few dozen examples here and on big G but can't seem to find a usable solution to know if the user has a password set. I am re-using this form for update view, which is where I don't want the random password to be generated again. I tried doing the same if statement check as the username but it doesn't work the same way as the auth\form.py user.set_password is looking for password1. class EmployeeRegistrationForm(UserCreationForm): email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Email address'})) first_name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'First name'})) last_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control mb-2', 'placeholder': 'Last name'})) password1 = None password2 = None class Meta: model = User fields = ['email', 'first_name', 'last_name'] def clean(self): password = User.objects.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789') self.cleaned_data['password1'] = password self.cleaned_data['password2'] = password return super().clean() def … -
django-mptt: Unknown column 'goods_category.lft' in 'where clause'
After updating django-mptt from 0.11.0 to 0.13.3, I getting an error Unknown column 'goods_category.lft' in 'where clause' goods/models.py class Category(MPTTModel): ... class Product(models.Model): category = TreeForeignKey(Category, null=True, blank=True, on_delete=models.CASCADE) ... goods/views.py categories = Category.objects.add_related_count( Category.objects.filter(is_public=True), Product, 'category', 'count', cumulative=True ) goods/templates/goods/sidenav.html {% recursetree categories %} <li> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}> {{ node.name }} </a> {% if not node.is_leaf_node %} <ul class="nested vertical menu {% if node.slug not in path %}display-none{% endif %}"> <li class="hide-for-large"> <a href="{{ node.get_absolute_url }}"{% if node.get_absolute_url == path %} class="active" {% endif %}>Show all </a> </li> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} manage.py makemigrations - No changes detected manage.py migrate - No migrations to apply -
Django Celery, App import error only on production
I have a file structure like this: myapp artist_applications tasks.py tasks celery.py # settings.py INSTALLED_APPS = [ 'myapp.artist_application', ... # celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings.production') app = Celery("tasks") app.config_from_object('django.conf:settings', namespace="CELERY") app.autodiscover_tasks() # tasks.py from tasks.celery import app as celery_myapp from django.apps import apps from django.conf import settings import requests @celery_esns.task(name='sample_task') def sample_task(): print('TESTING CELERY') @celery_esns.task(name='publish_artist_task') def publish_artist_task(payload, artist_id): r = requests.post(settings.PUBLISH_URL, json = payload) if r.status_code == 200: apps.get_model('artist_application', 'Artist').objects.filter(unique_id=artist_id).update(published=True) else: raise Exception("Error publishing artist with id: " + artist_id) On development all is running fine when I start Celery with: celery -A myapp.tasks worker -Q celery -l info But on production I run the command (in a virtualenv) and I get the error: django.core.exceptions.ImproperlyConfigured: Cannot import 'artist_application'. Check that 'myapp.artist_application.apps.ArtistApplication.name' is correct. Any ideas where to look? I don't get how 'runserver' is loading the apps differently then wsgi? -
category_id expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager
Looks like error is because of obj.category_id in serializer have something to do with many to many relationship. Error: TypeError: Field 'category_id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager..ManyRelatedManager object at 0x0000025BB1C23EE0 Here is my code: modles.py: class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) category_icon = models.CharField(max_length=500, null=True, blank=True) category_image = models.CharField(max_length=500, null=True, blank=True) category_description = models.CharField(max_length=1000, null=True, blank=True) active_status = models.BooleanField(default=True) def __str__(self): return str(self.category_id) +" -"+ str(self.category_name) class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) # parent_id = models.ForeignKey("Services", on_delete=models.CASCADE, default=0) # parent_id = models.IntegerField(default=0) service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) def __str__(self): return str(self.service_id) +" -"+ str(self.service_name) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) views.py: class ServicesList(viewsets.ViewSet): def retrieve(self, request, pk=None): queryset = Category.objects.get(category_id=pk) querysetSerializer = CategoryServiceListSerializer(queryset) return Response({"status":200,"message":"Success","data":querysetSerializer.data}) serialziers.py: class ServiceListSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class VariantServiceSerialzier(serializers.ModelSerializer): # service_id = ServiceListSerializer(many=True) # Getting all service data, #i want only data for perticular … -
Redirect to next post after form submit
I am building a Blog App and I am trying to implement a feature - In which a user can rate blogs in one page and after user click Save Rate then user will redirect to next review blog page and user will ratenext blog. But it is not redirecting to next rate blog page. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=500) Rating_Choice = [('1','1'), ('2','2')] class Rate(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) ratings = models.CharField(max_length=1, choices=Rating_Choice) views.py def rate_blog_post(request, blog_id): obj = get_object_or_404(Blog, pk=blog_id) next_blog = Question.objects.filter(rate__ratings=None) if request.method == 'POST': form = Form(data=request.POST) if form.is_valid(): post= form.save(commit=False) post.user = request.user post.blog = data post.save() # redirect here return redirect('rate_blog_post', pk=data.id) else: form = Form() context = {'obj':obj, 'form':form} return render(request, rate_blog_post.html', context) Form is working fine, it is saving the ratings What have i tried so far ? : I have tried using a next_blog like :- return redirect('rate_blog_post', rate_blog_post=question_id) But it showed Reverse for 'rate_blog_post' with keyword arguments '{'pk': 2}' not found I have tried many times but did't worked for me. I will really appreciate your Help. Thank You So, i made a choices of reviews. And User will redirect … -
Overrding get_queryset in the model file without having to create a new model manager in django?
I have a model and I have used it at multiple places now and changing it all places is cumbersome. Could you please let me know how to do that? I already know the I can create a custom model manager but it's not feasible to change the model manager at all places. class Slot(models.Model): state = models.CharField(max_length=20, choices=SLOT_STATE, default=SLOT_STATE[0][0]) According to the docs- # First, define the Manager subclass. class DahlBookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(author='Roald Dahl') # Then hook it into the Book model explicitly. class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) objects = models.Manager() # The default manager. dahl_objects = DahlBookManager() # The Dahl-specific manager. I want to retain the same default manager but I want to exclude all the NULL slot. P.S. slot can have null state. -
how to update field with django rest if post uniqueness fails?
I'm new to django rest and I've been stuck here for some time. I've a table with four fields (gtin,shop,expirydate,quantity) I also made it that the first 3 are unique with each others I've created 2 methods inside my views, the get and post but since I've the uniqueness if I tried to add the same field with different quantity I get The fields gtin, shop, expirydate must make a unique set. so I tried to work on a patch method so I can increase the current quantity with the new one, but couldn't get it to work this is my views from django.http import HttpResponse,JsonResponse from rest_framework.parsers import JSONParser from .models import Stock from .serializers import StockSerializer from django.views.decorators.csrf import csrf_exempt # Create your views here. @csrf_exempt def stock_list(request): if request.method == "GET": gtin = request.GET['gtin'] shop = request.GET['shop'] queryset = Stock.objects.all().order_by('expirydate') if gtin is not None and shop is not None: queryset = queryset.filter(gtin=gtin) queryset = queryset.filter(shop=shop) queryset=queryset.first() serializer = StockSerializer(queryset) return JsonResponse(serializer.data,safe=False) elif request.method == "POST": data = JSONParser().parse(request) serializer = StockSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data,status=201) return JsonResponse(serializer.errors,status = 404) elif request.method == 'PATCH': queryset = Stock.objects.all() data = JSONParser().parse(request) serializer = StockSerializer(data=data) queryset.perform_update(serializer) if serializer.is_valid(): … -
How can I successfully run django private chat2?
I installed django private chat2, as in this tutorial: https://github.com/Bearle/django_private_chat2 But, on the site it shows me like this: eror How do I view messages differently? How do I get to an html page? -
I have to find pmtlist and pmtid with service id in python
File contents: serviceid=2251:tsid=6:orignetwid=99:access=clear:pids=3:clearpids=3:scrambledpids=0:packets=2315:bitrate=1745711:bitrate204=1894282:servtype=1:pmtpid=3251:pcrpid=5251:pidlist=3251,5251,6251 Code: file = open('t5001.txt','r') file1 = file.read() file2 = file1.split(":") Input = input("Enter The student ID :- ") for i in file2: if Input in i: print(i) file.close() I have written this code but not getting answer i am doing just silly mistake not getting that one can anyone will help me -
Manytomanyfields through table data list_diplay repeating grouped data
screendata I have Django model manytomany through table: bridge_qual_id, bridge_uoc_id, sequence_id bridge_qual_id is only one record where units in the qualification are attached with sequence extra field for delivery order. I want qualification to display only once and listing all units for it. I tried format_html_join in models class method and calling in list_display but may be doing correct. At the moment admin.ModelAdmin code is just listing table column names: list_display = ['bridge_qual', 'bridge_uoc', 'uoc_sequence'] I can not do order_by on field in MySql in backend so tried following to change queryset but no effect. @admin.register(tp_uoc_sequence, site=pg_site) class tpuocAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super(tpuocAdmin, self).get_queryset(request) qs.extra(where= ["""bridge_uoc_id IN ( SELECT bridge_qual_id FROM tp_uoc_sequence WHERE bridge_qual_id=1) as modified group by bridge_qual_id ORDER BY bridge_qual_id""" ]) return qs list_display = ['bridge_qual', 'bridge_uoc', 'uoc_sequence'] -
Using a Deserialized Django Object Directly
I have found a lot of documentation about serializing a queryset in django, and i found out that to serialize a single object or instance of a model you simply needed to wrap that instance in a list '[]'. But here is my Issue, I serialized an object in one view passed it into session and deserialized said object in another view and it work just fine... but what i get is a python generator, how can i get the initial object with the generator? -
Django - [Errno 2] No such file or directory after compresing image
have a blog where users can upload and edit posts. I wanted to resize any uploaded image to a max. of 500*500px. For this purpose I created an if statement before save models.py def _upload_path(instance, filename): return instance.get_upload_path(filename) class Post(models.Model, HitCountMixin): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) image = models.ImageField(blank=True, null=True, upload_to=_upload_path) def __str__(self): return self.title def get_upload_path(self, filename): return "posts/images/" + str(self.user.username) + "/" + filename def save(self, *args, **kwargs): # resize image if self.image: img = Image.open(self.image.path) # Open image using self if img.height > 500 or img.width > 500: new_img = (500, 500) img.thumbnail(new_img) img.save(self.image.path) # saving image at the same path return super(Post, self).save(*args, **kwargs) Unforunalty the image path gets not recognized and I get an error [Errno 2] No such file or directory: '/Users/vic/Desktop/django_project/media/postimage1.jpg' This path is wrong! The upload-path is defined within the get_upload_path() function and should lead to /Users/vic/Desktop/django_project/media/posts/images/username/postimage1.jpg I tried to change the open path to img = Image.open(str(settings.MEDIA_URL) + self.get_upload_path(self.image.name)) or to hardcoded URL with localhost:8000... but nothing worked. If I remove the if statement the file gets uploaded in the correct path so the error must be at img definition.