Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku cannot read '/etc/secret_key.txt', No such file or directory:
I successfully deployed a django app to heroku with my settings.py as such: SECRET_KEY = 'the_real_long_secret_key_itself', which of course is not recommended, but that was find for me just in this scenario as it is just a test and can be changed. Now back to my local environment, I decided to hide the key without changing it yet and according to django documents like this: # on settings.py with open('/etc/secret_key.txt') as s: SECRET_KEY = s.read().strip() And it works when I run server locally. But now when I try to commit & push like this: (herokuvirtualenv)tester1@test:~/$ git add -A (herokuvirtualenv)tester1@test:~/$ git commit -m "some editing" (herokuvirtualenv)tester1@test:~/$ git push heroku master It runs but ends up with this error message: remote: with open('/etc/secret_key.txt') as s: remote: FileNotFoundError: [Errno 2] No such file or directory: '/etc/secret_key.txt I have used search engines and there seems to be many ways to do this and it point that this should work, but there seems to be something I am omitting here. Could someone please help out? -
Django change choice before validation
I am trying to update a choice field before it is validated in Django. The reason for this is the choice field in question value is the Id of a model that i want to update. def fuelLogSystemOne(request): entries = FuelLogSystemOneMod.objects.all().order_by('date') products = productsMod.objects.all() if request.method == 'POST': form = forms.AddFuelLogOneForm(request.POST, request.FILES) productid = form['product'].value() product = productsMod.objects.get(id=productid) product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] if form.is_valid(): bucketsRemoved = form['buckets_added'].value() product.stock -= bucketsRemoved product.save(['stock']) instance = form.save(commit=False) instance.staff = request.user instance.save() return redirect('home') else: form = forms.AddFuelLogOneForm() return render(request,'systems/fuellogsystemone.html',{'form':form,'entry':entries,'products':products}) The below part is where i am trying to change the form data before it gets validated so it doesn't say 'Select a valid choice. 1 is not one of the available choices' product_id = request.POST.get('product') form.fields['product'].choices = [(product.product_type, product.product_type)] But when I first submit the form it is still saying 'Select a valid choice.' At what point does Django validate the form because I am changing the form before the is_valid() method and it still hits this error? -
Django REST Framework - cookies not being set via Response.set_cookie() call...?
I have the following standard Response setup in my DRF application: response = Response(data=response, status=status.HTTP_200_OK) I'm then attempting to add a split JWT header.payload and signature to the response headers with a response.set_cookie() call, as follows: max_age = 365 * 24 * 60 * 60 expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) response.set_cookie( key='JWT_ACCESS_HEADER_PAYLOAD', value=header_payload, httponly=False, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) response.set_cookie( key='JWT_ACCESS_SIGNATURE', value=signature, httponly=True, expires=expires.strftime("%a, %d-%b-%Y %H:%M:%S UTC"), max_age=max_age ) return response I can't see anything wrong with what I have done thus far: Yet, for some reason, the only cookies set on the client side are as follows: What have I done wrong here?? The actual output in the headers seem to be a valid SetCookie value: JWT_ACCESS_HEADER_PAYLOAD=aSasas; expires=Sat, 03-Apr-2021 10:24:31 GMT; Max-Age=31536000; Path=/ JWT_ACCESS_SIGNATURE=asaSasaS; expires=Sat, 03-Apr-2021 10:24:31 GMT; HttpOnly; Max-Age=31536000; Path=/ -
Manage models inheritance in Django admin
I'm developing with my team a Django webapp which provides authentication and users profile creation. Basically, we are dealing with a model Profile which extends django.auth.contrib.models.User implementing One-to-One link method, as shown below model.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(default=datetime.date.today) # other custom fields def __str__(self): return self.user.username Since we have registered the model in admin.py, it appears in Django admin panel, as it should be. Then, we have introduced another model PersonalTrainer which is an intherited class of Profile one. admin.py from django.contrib import admin from usermanager.models import Profile, PersonalTrainer admin.site.register(Profile) admin.site.register(PersonalTrainer) Is there any programmatically method to organize PersonalTrainer instances in a such a way they appear both in Profile section and PersonalTrainer section? In other words, we'd like to have a PersonalTrainer instance which appears in auth User model, Profile model and PersonalTrainer model. -
Django messages not working in admin model_save()
I have the following save_model in MyModelAdmin, the print statement gives output in console, but on django admin, i can see default messages, but not my error message for some reason. class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): try: transfer_money() super(MyModelAdmin, self).save_model(request, obj, form, change) except Exception as e: print(e) messages.add_message(request, messages.INFO, str(e)) -
How can I convert my class-based view to function-based views? - Django
I am trying to change all my class-based views to function-based views and I am having difficulty converting the following class: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, UpdateView): model = Post fields = ['image', 'title', 'category', status', 'description'] template_name = 'blog/post-form.html' success_message = 'Your post has been updated.' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def get_context_data(self, **kwargs): context = super(PostUpdateView, self).get_context_data(**kwargs) context['title'] = 'Update post' context['submit'] = 'Update' return context def get_success_url(self): author = self.object.author return reverse_lazy( 'profile', kwargs={'author': author.username}) The function and form should do exactly what this class-based view does, so if anyone can help me out, please let me know. -
Object level authorization in a Django Rest Framework viewset
I'm creating an API with Django Rest Framework (DRF) and wondering where I should handle object level authorization. So far I've created an Organization model and a custom user model with email being the unique identifier instead of username. Organizations and users are currently connected through a many-to-many field. What I'd like to do is make sure that when a user hits my API they're only able to do the standard CRUD actions on the models that are linked to the users respective organization. As an example here's my current UserViewSet where I've overriden then get_queryset method to filter the User queryset to only return other users who are apart of the same organizations as the user calling the API: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer def get_queryset(self): User = get_user_model() user = self.request.user organizations = user.organization.all() return User.objects.filter(organization__in=organizations) What's considered best practice to extend these limitations to other viewset actions? For example, if I want to make sure that the user can only create and add other users into the organizations they're linked to, should I override the create method in the viewset and perform a validation there that the organization which was passed in the request data is the … -
Why does django gives me 405 error on the first instance
I'm writing this code class ParentCancelView(ProfileTypeRequiredMixin, UpdateView): profile_type = 'parent' model = Books template_name = 'library/student_parent_list_view.html' def post(self, *args, **kwargs): recipient = self.request.user.parent.recipient.first() queryset = self.get_queryset() pk = self.kwargs.get('pk') if pk: queryset.filter( pk=pk, recipient=recipient ).update(reserve_status='cancelled') return super(ParentCancelView, self).post(*args, **kwargs) urls.py url( r'^reserve/parent/(?P<pk>\d+)/$', views.ParentCancelView.as_view(), name='reserve_parent_cancel' ), html <form method="POST" action="{% url 'library:reserve_cancel' pk=book.pk %}"> {% csrf_token %} <button class="btn btn-xs btn-primary" type="submit" {% if book.reserve_status != 'for_approval' %}disabled{% endif %}>Cancel Reservation {{ book.pk }}</button> </form> when Im trying to cancel it works fine on second, third but not on first instance it has no error but it gave me 405, does any one what went wrong here? thanks -
Add extra non-model attribute to serializer
I have following scenario: I have a device model with a "deleted" field. When it's true, the device is deleted. I need a endpoint to change the value of that field. I want to do this in a request by giving the device_id and a deleted_flag. I was able to just change the deleted attribute without passing the deleted_flag attribute. But I'm stuck if I want to give the deleted_flag attribute to the serializer because it's a non model field.. This is my code: test: def test_undelete_device(self): self.client.force_login(self.admin_user) url = reverse( "admin-device-change-status", kwargs={"device_pk": self.device.id}, ) response = self.client.patch(url, data={"deleted_flag": False}) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["deleted"], False) serializer: class AdminDeviceChangeStatusSerializer(serializers.ModelSerializer): deleted = serializers.BooleanField() deleted_flag = serializers.SerializerMethodField() class Meta: model = Device fields = ["deleted", "deleted_flag"] def validate_deleted(self, deleted): return deleted def validate_deleted_flag(self, deleted_flag): return deleted_flag def get_deleted_flag(self, deleted_flag): return deleted_flag view: def patch(self, request, device_pk): """ Change deleted status device """ device = get_object_or_404(Device, pk=device_pk) serializer_class = AdminDeviceChangeStatusSerializer serializer = serializer_class(device, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() if serializer.validated_data.get("deleted_flag") == False: device.deleted = True else: device.deleted = False device.save() return Response(serializer.data, status=status.HTTP_200_OK) stacktrace: TypeError: Object of type 'Device' is not JSON serializable -
My code is working on codepen but not on my editor
My code is working on codepen but not on my editor (PyCharm). This is part of django project. By not working I mean I get a blank page, with no output (no text). I have tried to read a few answers addressing a similar issue but none of these solutions seem to be working for me/or I am not applying them correctly. Specifically adding the full URL path for getting ScrollWatch through CDN. Here is a sample of my code html { % load script % } <html lang="en"> <head> <meta charset="UTF-8"> <title>The Gradient Boost</title> <link rel="stylesheet" href="{% static 'second/css/app/book.css' %}"> <script src="https://cdn.jsdelivr.net/npm/scrollwatch@2.0.1/dist/ScrollWatch-2.0.1.min.js"></script> </head> <body> <h2><div data-scroll-watch>First Text</div></h2> <h2><div data-scroll-watch>Second Text</div></h2> <h3><div data-scroll-watch>Third Text</div></h3> <script src="{% static 'second/js/app/book.js' %}"></script> </body> </html> css location -> static\second\css\app\book.css .watch-container { font-size: 2em; width: 75%; height: 150px; padding: 20px; margin: 50px auto; background-color: #0681CD; color: #fff; overflow: auto; text-align: center; } div { text-align: center; font-size: 1em; margin: 200px 0; opacity: 0; transition: opacity 1s; font-weight: normal } div.scroll-watch-in-view { opacity: 1; } and javascript location -> static\second\js\app\book.js (function() { var addElements = function() { var txt = document.createTextNode('Testing'); var el; el = document.createElement('div'); el.appendChild(txt); document.body.appendChild(el); // If we want newly injected elements to … -
argument of type 'QuerySet' is not iterable Django error
In my webapp, I have a friends feature, but one of the if statements produces an error Here is my UserProfileInfo model class UserProfileInfo(models.Model): connection = models.ManyToManyField(User,blank=True,related_name='follow_profile') And now here is my view: def friend_actions(request,username=None): current_user = request.user.userprofileinfo user = request.user # username = get("username") username = User.objects.get(username=username) other_user = get_object_or_404(UserProfileInfo,user__username=username) # other_user = UserProfileInfo.objects.get(username=username) url = other_user.get_absolute_url() if other_user in current_user.connection.all(): current_user.connection.remove(other_user) else: current_user.connection.add(other_user) return HttpResponseRedirect(url) However, this produces the following error: argument of type 'QuerySet' is not iterable Full traceback Traceback: File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\interests-site\interests-drf\mainapp\views.py" in friend_actions 453. if other_user in current_user.connection.all(): Exception Type: TypeError at /mainapp/profile/donnellan0007/connect/ Exception Value: argument of type 'QuerySet' is not iterable I am wondering how I can stop this error from occurring. I have been stumped by it all day -
Django hosting trouble with django.wsgi
I registered everything as it is written in the instructions for django hosting provider (jino), but errors popped up, which I can't even come close to understanding. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] mod_wsgi (pid=61341): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] Traceback (most recent call last): [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:32:40 2020] [error] [client 148.64.56.65] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: '/home/users/m/marselabdullin/projects/caparol_center_spb_decision/env/bin/activate_this.py' [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Failed to exec Python script file '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] mod_wsgi (pid=37979): Exception occurred processing WSGI script '/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi'. [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] Traceback (most recent call last): [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] File "/home/users/m/marselabdullin/domains/caparolcenterspb.ru/django.wsgi", line 4, in <module> [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] exec(open(activate_this).read(), dict(__file__=activate_this)) [Thu Apr 02 22:33:16 2020] [error] [client 5.18.99.123] FileNotFoundError: [Errno 2] \xd0\x9d\xd0\xb5\xd1\x82 \xd1\x82\xd0\xb0\xd0\xba\xd0\xbe\xd0\xb3\xd0\xbe \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0 \xd0\xb8\xd0\xbb\xd0\xb8 \xd0\xba\xd0\xb0\xd1\x82\xd0\xb0\xd0\xbb\xd0\xbe\xd0\xb3\xd0\xb0: … -
Problems with django error handling with ajax
I want to create ajax error handling function for that. Problems can be in the JsonResponse part.Also how to implement that in the template? I tried to create ajax function before but it did't work.I want to create something like on signup page by default views.py def auth_join(request, room, slug): if request.method == 'POST': user = request.user.username form_auth = AuthRoomForm(request.POST) if form_auth.is_valid(): room_pass = form_auth.cleaned_data.get('room_pass') password2 = form_auth.cleaned_data.get('password2') if room_pass != password2: messages.error(request, 'Doesn\'t match') return JsonResponse('error') else: user = CustomUser.objects.get(username=user) room = get_object_or_404(Room, slug=slug) if user.has_perm('pass_perm', room): return HttpResponseRedirect(Room.get_absolute_url(room)) else: messages.error(request,'You don\'t have access to this page') return JsonResponse('error') else: form_auth = AuthRoomForm() return render(request,'rooms/auth_join.html', {'form_auth':form_auth}) template <form method='post' class='ui form' id="form"> {% csrf_token %} <div class="ui middle aligned centered grid"> <div class="four wide column"> <h4 class="ui dividing teal header">Enter room password</h4> <div class="field"> <label>Password</label> {{form_auth.room_pass}} </div> <div class="field"> <label>Confirm password</label> {{form_auth.password2}} </div> <button type="submit" class="ui teal button">join</button> {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <div class="ui green message">{{message}}</div> {% else %} <div class="ui red message">{{message}}</div> {% endif %} {% endfor %} {% endif %} {% if form_auth.errors %} {% for i in form_auth %} <div class="ui red message"> {{i.errors}} … -
Call for model field validation in the serializer
I will try to make a check for the uniqueness of the field at the validation level in the serializer and can not understand why the validator is not called at all. models.py class Vendor(models.Model): active = models.BooleanField(default=False) ... class VendorContacts(models.Model): vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True) ..... serializer.py class VendorContactCreateSerializer(serializers.ModelSerializer): email = serializers.CharField(validators=[RegexValidator(regex=r'[^@]+@[^\.]+\..+', message='Enter valid email address')]) vendor = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = VendorContacts fields = (..... ) def create(self, validated_data): ..... #some logic def validate_email(self, value): print('Start validation') exist_contact = VendorContacts.objects.filter(email=value) if exist_contact: vc = get_object_or_404(VendorContacts, email=value) v = vc.vendor if v.active: raise serializers.ValidationError('Email {} already exists'.format(value)) return value In the above serializer, I perform a check at the def validate_email() model field level. print('Start validation') is not called. I tried the same at the object level through def validate(): but it is not called either. -
Sending data to Django channels
I have an external Python script which generates JSON data every second; on the other side i have a Django application. I would like to stream that data on a webpage on my Django app. I already built a consumer with Django channels, but i don't know how to make Django have the data that i generate from the other Python script. Here is my basic consumer: class EchoConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected", event) await self.send({ "type": "websocket.accept" }) async def websocket_receive(self, event): print("received", event) # Echo the same received payload async def websocket_disconnect(self, event): print("disconnected", event) Is there a specific way do this? Or am i supposed to use another service in the middle?Any advice is appreciated -
IS there any one help me for this errors
Hi evrey one I got this errors in image any help please -
How to download a .txt file from a django project
I find difficulty on how to download my .txt file after pressing the button which calls the view respnosible for that. My .txt file is created locally in the path where my manage.py file resides. snippet code of my view: file_name= open("example.txt","w+") file_name.write("\r\n\r\n%s%s%s%s%s" % (var1," ",var2," ",var3)) response = HttpResponse(file_name, content_type="text/plain,charset=utf8") response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name) file_name.close() return response What i have to change to be able to download my .txt file? -
how to load bootstrap in Django?
so I tried loading Bootstrap to Django. But since I wanted to customize the styling with scss, instead of putting the CDN url in header, I replaced it with a separate css file which has all of the Bootstrap stylings. Here's the code. <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/style/main.css"> <title>{% block title %}BASE{% endblock %}</title> </head> <body> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> I have the correct /style/main.css file, I've checked it by ctrl+clicking it. As mentioned, the file has ALL of the Bootstrap stylings. @charset "UTF-8"; /*! * Bootstrap v4.4.1 (https://getbootstrap.com/) * Copyright 2011-2019 The Bootstrap Authors * Copyright 2011-2019 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ :root { --blue: #007bff; --indigo: #6610f2; --purple: #6f42c1; --pink: #e83e8c; ### AND SO ON ### However my Django page wouldn't reflect it. When I hit refresh I don't see any styling. But when I restore the CDN url, Bootstrap is normally applied. I have no idea what the problem is. I would very much appreciate your help. :) -
Stripe - Retrieve Customer PaymentIntent history
I am building a platform where I am using Stripe's concept of a parent "platform" account and Connected Stripe accounts that belong to this platform. (e.g. Lyft model) Following Stripe's documentation, when I create a new customer in Stripe, I create it under the main platform account and also store all the payment methods under that customer. When a customer buys something from the Connected account, I follow this doc, where I clone payment method and create a PaymentIntent that is attached to the specific Connected account. And it all works. However, when I try to get a history of customer's transactions (List of PaymentIntents), it returns an empty list because it runs it against the main platform account: stripe.PaymentIntent.list(customer='cus_FJDHFGSJHDF') When I specify a customer AND connected account id, it returns an empty list, because that customer doesn't exist in that Connected account, however, the paymentIntents are present in that Connected account. So, what is the right way to create a PaymentIntent for a customer for a Connected account and then get the history of payments for that customer PER Connected Stripe account? Here is how I clone PaymentMethod and create PaymentIntent: payment_method = stripe.PaymentMethod.create( customer=customer, payment_method=customer.invoice_settings.default_payment_method, stripe_account=stripe_connect_id, ) intent … -
Obtain the name of my columns from my django model
I want to show some tables in my templates from my models and I need to know what are the fields from they. Obtain the data is easy, class fleet_bbdd_view(ListView): template_name = 'data_app/info-bbdd.html' paginate_by = 20 model = info context_object_name = 'infoList' Or if I want to specify, def getData(request): data1 = info.objects.all() # Ex1, obtain all the data data2 = info.objects.order_by('id','-data_timestamp').distinct('id') # Ex2, obtain the last data from the distinct ids ctx = {'Data1':data1, 'Data2':data2} return JsonResponse(ctx) But, how can I obtain the name of my columns? Exists something like this? cols = info.objects.fields() I'm sure is not a pro question, but I really don't know what can I do. Thank you very much -
invalid literal for int() with base 10 in django?
I wrote this code : views.py: class IndexView(TemplateView): template_name = 'index.html' class SchoolListView(ListView): context_object_name = 'schools' model = models.School class SchoolDetailView(DetailView): context_object_name = 'school_detail' model = models.School template_name = 'nineapp/school_detail.html' class SchoolCreateView(CreateView): fields = ('name', 'principal', 'location') model = models.School models.py: class School(models.Model): #ppk = models.IntegerField(default=0 , primary_key=True) name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.CharField(max_length=256) school = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE) def __str__(self): return self.name urls.py: urlpatterns = [ url(r'^$', views.SchoolListView.as_view(), name='list'), url(r'^(?P<pk>[-\w]+)/$', views.SchoolDetailView.as_view(), name='detail'), url(r'^createsc/(?P<pk>[-\w]+)$', views.SchoolCreateView.as_view(), name='createsc'), ] this program is working correctly but when i want to go the createsc/ I've got this error: invalid literal for int() with base 10: 'createsc' please help me. -
Django: Query `id__in` with UUIDs
In Django, we can use the id__in query with a queryset to filter down a queryset based on a list of IDs. However, by default this will fail if your IDs are UUIDs. So this will not work and throw the error: LINE 1: ...OM "items_character" WHERE "items_character"."id" IN (SELECT... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. def foos(self): """ Returns the user's owned foos. """ # Todo: Cache & Bust On Update content_type = ContentType.objects.get_for_model(Foo) owned = Ownership.objects.filter(user=self, content_type=content_type) return objects.filter(id__in=owned.values_list("object_id", flat=True)) However, the following will work, if we manually convert the entire thing to UUID. Is there a way to make this work without this iteration over the set? def foos(self): """ Returns the user's owned foos. """ # Todo: Cache & Bust On Update content_type = ContentType.objects.get_for_model(Foo) owned = Ownership.objects.filter(user=self, content_type=content_type) owned_ids = list(owned.values_list("object_id", flat=True)) test = [] for fid in owned_ids: test.append(uuid.UUID(cid)) return Foo.objects.filter(id__in=test) -
python manage.py runserver keeps reloading stating file has changed
I've been working on a django project with no issues. I've pulled updated code from the remote repository and now if i do python manage.py runserver in cmd, i keep getting error Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. D:\some_project\someapp\schemes\models.py changed, reloading. Watching for file changes with StatReloader Performing system checks... then Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. D:\some_project\someapp\schemes\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... it keeps looping through all the files and all the apps that have in my django project. it works if i try python manage.py runserver --noreload however, i'm curious as to what lead to the issue in the first place. -
Django Rest Framework: Passing Context in Viewsets
Viewsets are convenient because we can do stuff like this and get a fully working serializer: class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = [IsAuthenticated] queryset = StoreObject.active_objects.all() serializer_class = serializers.StoreObjectSerializer Unfortunately, as far as I know– to pass the context into the serializer we need to do things like this: PostSerializer(data=request.data, context={'request': request}) Which means we need to manually override every convenient method provided by ViewSets (as far as I know). Is there a way to inject the context into every serializer while still keeping Viewsets convenient? -
Which template loaders is Django using?
In documenation to cached Loader is written This loader is automatically enabled if OPTIONS['loaders'] isn’t specified and OPTIONS['debug'] is False How to confirm that Django is really using cached Loader? How to check which template loaders is Django using?