Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a visible route/path on leaflet map?
I have an app which allows a user to see a route between his location and the place they want to get to, and im having difficulties showing the route however the 2 markers show up. //Passing lat and lon value from a django template variable const latitude = document.getElementById('lat').textContent; const longtitude = document.getElementById('lon').textContent; // Creating map options let mapOptions = { center: [latitude, longtitude], zoom: 18, zoomControl: true, zoomAnimation: true, } // Creating a map object guessing if there's an error it could be down here... var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }); map.addLayer(layer); L.marker([latitude,longtitude]).addTo(map); const btn = document.getElementById('create_route'); btn.addEventListener("click",function create_route(e){ function success(pos) { const crd = pos.coords; let crdLat = crd.latitude, crdLon = crd.longitude; L.Routing.control({ waypoints: [ L.latLng(latitude,longtitude), L.latLng(crdLat,crdLon) ], autoRoute: true, routeWhileDragging: true }).addTo(map); } //get user location navigator.geolocation.getCurrentPosition(success); }) Also i get this error in my console leaflet-routing-machine.js:15868 Routing error: {message: 'HTTP request failed: undefined', url: 'https://router.project-osrm.org/route/v1/driving/-…erview=false&alternatives=true&steps=true&hints=;', status: -1, target: XMLHttpRequest} Any help will be much appreciated, I'am open to other alternatives also...As long as it gets the job done. -
Django puts slug between parentheses, then stops doing that
I have an issue similar to this one. My error message is something like this: Reverse for 'detail' with arguments '('some-slug',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$'] I intend to use some-slug and not ('some-slug',) for URL reversal. When I follow Saifeddin's suggestion of using <str:slug>, it works. I then switch back to <slug:slug>, it also works. The problem simply vanishes. Could someone explain to me why Django (4.1.2) behave this way? I am at a loss. -
why is starting a celery worker showing what appears to be random print statements
When I start a celery worker I get the following. The >>> bla bla <<< print statements are in various scripts having nothing to do with celery or beat. After that the worker does not show any activity when I save a task in beat admin pages. > celery -A mysite worker -l info --pool=solo -n worker3 XXXXXXXXXXXXXXXXX correlator views IndexView XXXXXXXXXXXXXXXXXXXXXXX >>>>>>>>>>>>>>>>>>> Reviews.views.IndexView <<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>> Reviews.views.DetailView <<<<<<<<<<<<<<<<<<<<<<<<<<<< >> correlator/urls.py << XXXXXXXXXXXXXXXXX parameters/views.py ParametersIndexView XXXXXXXXXXXXXXXXXXXXXXX QuestionsViewSet correlator/urls.py -------------- celery@worker3 v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2022-11-01 12:33:52 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: mysite:0x18cc6d60208 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . correlator.tasks.add . correlator.tasks.mul . iris.tasks.add . iris.tasks.mul . mysite.celery.debug_task . mysite.celery.hello_world . reviews.tasks.add . reviews.tasks.mul . reviews.tasks.rename_widget [2022-11-01 12:33:52,901: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2022-11-01 12:33:52,906: INFO/MainProcess] mingle: searching for neighbors [2022-11-01 12:33:53,946: INFO/MainProcess] mingle: all alone ings.DEBUG leads to a memorARNING/MainProcy thub\correlator leak, never useelery\fixups\dj this setting in productionsing … -
Django ArrayField of Floats: Can't seem to input floats in a list into Django Admin
These are basically cartesian coordinates that I am storing, of y values only. I am unsure how to store them other than an "list of floats", but unable to make it to an arrayfield of floats in django as shown above. I am not sure how to fix this. I understand I could store it all as a string, but if I am doing a lot of operations, and my arrays can go up to lengths of hundreds of thousands, getting that as a string and converting to float arrays could become very expensive. (or would it not be?) -
Celery unexpectedly closes TCP connection
I'm using RabbitMQ 3.8.2 with Erlang 22.2.7 and having a problem while consuming tasks. My configuration is django-celery-rabbitmq. While publishing messages in a queue everything goes ok until the length of the queue reaches 1200 messages. After this point RabbitMQ starts to close AMQP connection with following errors: ... 2022-11-01 09:35:25.327 [info] <0.20608.9> accepting AMQP connection <0.20608.9> (185.121.83.107:60447 -> 185.121.83.116:5672) 2022-11-01 09:35:25.483 [info] <0.20608.9> connection <0.20608.9> (185.121.83.107:60447 -> 185.121.83.116:5672): user 'rabbit_admin' authenticated and granted access to vhost '/' ... 2022-11-01 09:36:59.129 [warning] <0.19994.9> closing AMQP connection <0.19994.9> (185.121.83.108:36149 -> 185.121.83.116:5672, vhost: '/', user: 'rabbit_admin'): client unexpectedly closed TCP connection ... [error] <0.11162.9> closing AMQP connection <0.11162.9> (185.121.83.108:57631 -> 185.121.83.116:5672): {writer,send_failed,{error,enotconn}} ... 2022-11-01 09:35:48.256 [error] <0.20201.9> closing AMQP connection <0.20201.9> (185.121.83.108:50058 -> 185.121.83.116:5672): {inet_error,enotconn} ... Then the django-celery consumer disappears from queue list, messages become "ready" and celery pods are unable to ack the message after the job is finished with the following error: ERROR: [2022-11-01 09:20:23] /usr/src/app/project/celery.py:114 handle_message Error while handling Rabbit task: [Errno 104] Connection reset by peer Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 514, in channel return self.channels[channel_id] KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/src/app/project/celery.py", … -
django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace
I am trying to create a Log in and Registration for a Django Rest Framework but I keep getting django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace not sure what is the reason for getting this error and how to fix it? Here is the serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "first_name", "last_name", "username"] class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user Here is the views.py: class UserDetailAPI(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def get(self,request,*args,**kwargs): user = User.objects.get(id=request.user.id) serializer = UserSerializer(user) return Response(serializer.data) class RegisterUserAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = RegisterSerializer Here is the urls.py path('get-details/', UserDetailAPI.as_view()), path('register', RegisterUserAPIView.as_view()), Here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inne r response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_res ponse response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Django - Why Sweetify is not working. SweetAlert2
I'm followed the documentation from Atrox, and then still not working on my project. Any Idea ? I write the code like below. 1. home/views.py from django.shortcuts import redirect from django.views.generic import FormView from attendance.models import Graduates from home.forms import TicketForm from django.utils import timezone from django.urls import reverse import sweetify class HomeView(FormView): template_name = 'home/index.html' form_class = TicketForm def form_valid(self, form): getId = form.cleaned_data['nomor_ticket'] try: graduate = Graduates.objects.get(ticket_id=getId) message_success = 'Congratulations' if graduate: graduate.attendance = timezone.now() graduate.status = True graduate.save() sweetify.success(self.request, message_success, text='Cool', persistent='Thanks', timer='3000') return (redirect('attendance:index', graduate.ticket_id)) except Graduates.DoesNotExist: print('ticket not found') return redirect('home:index') 2. templates/base.html ... <body> {% block contents %}{% endblock contents %} <script src="https://unpkg.com/flowbite@1.5.3/dist/flowbite.js"></script> {% load sweetify %} {% sweetify %} </body> ... 3. core/settings.py INSTALLED_APPS = [ ... 'sweetify' ... ] SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' -
How to effectively iterate by many foreignkey objects with Django ORM?
Let's say that I have model like: class User(AbstractUser): ... seller = models.ForeignKey(Seller, related_name="user", on_delete=models.SET_NULL, null=True) ... And I trying to get seller email address using this code: from app.models import User from django_print_sql import print_sql with print_sql(count_only=False): users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().only('seller__email') for u in users.iterator(): email = u.seller.email send_email(email) In this case I can see SQL queries like: SELECT `user`.`id`, `user`.`seller_id` FROM `user` WHERE (`user`.`is_active` AND `user`.`seller_id` IS NOT NULL) ... SELECT `seller`.`id`, ... `seller`.`email`, ... FROM `seller` WHERE `seller`.`id` = 1 ... The problem is Django ORM accessing DB at every iteration (Select seller... where seller.id = ...). So that will be too many queries (== DB connections) if we have many sellers. In other way it is possible to replace only with values: from app.models import User from django_print_sql import print_sql with print_sql(count_only=False): users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().values('seller__email') for u in users.iterator(): email = u['seller__email'] send_email(email) And I can see SQL query like: SELECT `seller`.`email` FROM `user` INNER JOIN `seller` ON (`user`.`seller_id` = `seller`.`id`) WHERE (`user`.`is_active` AND `user`.`seller_id` IS NOT NULL) It is little bit better and we able to get emails by single DB query, but iterator is useless here because we load all emails once inside … -
AttributeError: module 'django.core.serializers' has no attribute 'ModelSerializer'
I had this error: "AttributeError: module 'django.core.serializers' has no attribute 'ModelSerializer'" before running makemigrations Though I have imported serializers from rest_framework, and I have added rest_framework to my installed app, it still did not work -
How to edit my get_queryset method Django Rest to acept authenticated users and authenticated user
I have this CourseViewSet which is using mixins to create,list, retrieve and update courses. Right now only authenticated users can list and retrieve courses and adminUsers can create, update courses. The get_queryset method has been overwritten to list the courses that users have bought and all the courses. It looks like this: courses/views.py def get_queryset(self): qs = Course.objects.filter(is_active=True, level=0) active_levels_prefetch = Prefetch( "levels", queryset=Level.objects.filter(is_active=True).order_by("is_special"), ) qs = qs.prefetch_related("children", active_levels_prefetch) # Add purchased courses amount qs = CourseQuerySet._add_purchase_amount_to_qs(qs) if self.request.user.is_student(): self._set_geolocation_params() qs = CourseQuerySet.list(qs, self.country) print(qs) return qs In my util, I have this file permissions.py, to verify if users are students: class IsStudent(BasePermission): """Verify is user is student.""" def has_permission(self, request, view): # Anonymous user aren't allowed if isinstance(request.user, AnonymousUser): return False return request.user.is_student() I also edited the get_permissions method to accept unauthenticated users to get a list of the courses: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.request.method == 'GET': permission_classes = [AllowAny] else: permission_classes = [IsAdmin] return [permission() for permission in permission_classes] When I tried to get all the courses without authentication, I get the next error: AttributeError: 'AnonymousUser' object has no attribute 'is_student', which is obvious because in … -
Django Rest Framework returns {'detail': 'Not found.'} when tested although it is showing Data in URL
I have the following django project with the following views.py: @api_view(['GET']) @permission_classes([AllowAny]) def getItem(request, **kwargs): user = get_object_or_404(User, username=request.user) items=Item.objects.filter(user=user) serializer = ItemSerializer(items, many=True) return Response(serializer.data) Here is the serializer.py class ItemSerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Workout fields = '__all__' Here is the outcome in the Django Rest Framework URL: Get Workout GET /api/Shiko/items/ HTTP 200 OK Allow: GET, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "user": "Shiko", "active": false, "name": "Item 1", "slug": null } ] Test using Jupyter to check for data availablity: import requests data = requests.get(URL) json_data = data.json() print (json_data) My question: What could be wrong in my settings that needs changed to return valid data in my test code knowing that there is data in Json but returning not found when testing. Also I have used IsAuthenticated which returned {'detail': 'Authentication credentials were not provided.'} which means that the test code is valid. What am I doing wrong and how should I fix? -
How to filter in HTML using a field from model?
I want to implement a page with check boxes from university's subjects and the user can select which ones are already completed, I code a for loop that displays in the page all subjects from that course, but I want to separate the subjects by semester in a div, but in the same page, can I do this with a custom template tag or filter? I have tried using .filter on the query, but in this case only returned one specified semester. -
Django to AWS deterministic=True requires SQLite 3.8.3 or higher
I have deployed my AWS application, but am receiving the error when I navigate to it's EC instance URL: deterministic=True requires SQLite 3.8.3 or higher I have tried the solution here, but when I run eb deploy and eb ssh and vi /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py , but the file still says from sqlite3 import dbapi2 as Database rather than from pysqlite3 import dbapi2 as Database However, in /var/app/current/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py it correctly says from pysqlite3 import dbapi2 as Database Any ideas how I can solve this issue? -
reversing admin "change" url
I´m trying to find some example of how to use change url of modelAdmin and what exactly result it gives. Sincerly I do not understand the part from docs: "This will find the first registered instance of the admin application (whatever the instance name), and resolve to the view for changing poll.Choice instances in that instance." -
When to use web socket or http
In a social media app development, when should I use web sockets? I know I have to use them to get the real time things, like messaging, and notification. But should I use web sockets in features like "Like", "Retweet", etc? Currently, I have one websocket for each of those resources, it's working great but I'm not sure it is the best approach. Inside those web socket connections, I have a function that notifies users in real time. But then I thought, "Man i dont think I need web socket for like function, I could just use Http and use web socket only for the notification"? So I have this doubt -
heroku Response times
I am deploying my django web app to heroku I am not using free tier, but my application is soo slow how can I make it faster, this is the error I am having now : Active Alerts: Response times have been above your 1000ms threshold for an hour. probably because I am using images and database from aws. I tried upgrading web dyno type to standard -
How to make simple filtration with django-filter
I faced with a problem. I have a simple drf project with car-entrance permits application. views.py ` class PermitViewSet(ModelViewSet): queryset = Permit.objects.filter() serializer_class = PermitSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['car_number'] serializers.py ` class PermitSerializer(serializers.ModelSerializer): class Meta: model = Permit fields = ['car_number', 'is_active'] models.py ` class Permit(models.Model): car_number = models.CharField(max_length=15) customer = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) urls.py router = SimpleRouter() router.register(r'permit', PermitViewSet) urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += router.urls ` i type in my browser http://127.0.0.1:8000/api/v1/permits/?car_number=555 and i recieve full list of cars ` [{"car_number":"555","is_active":true},{"car_number":"666","is_active":true},{"car_number":"777","is_active":true}] ` It doesn't work, what's the problem? -
Supervisor shutsdown when I have multiple services in the .conf file
I have a Linux server running ubuntu 22.10 with digital ocean where I plan to host multiple virtualenv to run isolated Django applications. Using gunicorn to serve the application and nginx as the reverse proxy. The supervisor to control the processes. I started with one django application and everything was working fine. on adding the second .conf file for the second application, the supervisor shuts down and subsequent supervisorctl commands return this error unix:///var/run/supervisor.sock refused connection this is my supervisor configuration [program:brotherstech] command=/home/webapps/brotherstech/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/brotherstech/logs/gunicorn-error.log [program:officebook] command=/home/webapps/officebook/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/officebook/logs/gunicorn-error.log -
Django Graphene hiding a model field (or return null) based on user preference in ManyToMany
assume we have the following Django Models: class Person(models.Model): name = models.CharField(max_length=255) personal_field = models.CharField(max_length=255) class Group(models.Model): name = models.CharField(max_length=255) participants = models.ManyToManyField( "Person", through="GroupPersonOption", through_fields=('group', 'person') ) class GroupPersonOption(models.Model): person = models.ForeignKey("Person", on_delete=models.CASCADE) event = models.ForeignKey("Event", on_delete=models.CASCADE) hide_personal_field = models.BooleanField(default=False) Example: Based on the group a user is in, they can choose to hide their personal_field, so that instead of its regular value, None or Null is returned. The Person can set this in the ManyToMany Model called GroupPersonOption Where it gets tricky: How do I change its value to None in my DjangoObjectTypes? When I try to add a resolve function for the personal_field in PersonObjectType, I don't know if the user wanted to hide this info. Graphene Code: { peopleByGroup(name: "DjangoIsAwesome") { person { name personal_field } } } I have waited a few days in the Django Subreddit but the only solution one person came up with was just to ignore setting the personal_field to None based on some value and then hide it in the frontend, however that is not an acceptable solution, as this would expose user data. I have also tried adding a resolve_person function to the PersonEventOptionType, but that broke a lot … -
How to subtract contents of IntegerField of one table from another in Django?
How it works: When I add a product to the Bouquet table, in the CompositionOfTheBouquetInline class, I can select an object from the Flower table and select the number of flowers. For example, there is a "Rose" flower in the Flower table, stock = 10 there is a bouquet "Bouquet of roses" in the Bouquet table, stock = 1 select the "Rose" flower in the amount of 5 and save, in the CompositionOfTheBouquet table What is going to happen: flower "Rose" is now stock = 5, in the Flower table Formula: Flower.stock = Flower.stock - (CompositionOfTheBouquet.count * Bouquet.stock) models.py class Flower(models.Model): title = models.CharField(max_length=100) stock = models.PositiveIntegerField(default=0) class Bouquet(models.Model): title = models.CharField(max_length=150) stock = models.PositiveIntegerField(default=0) class CompositionOfTheBouquet(models.Model): flower = models.ForeignKey( Flower, on_delete=models.PROTECT ) bouquet = models.ForeignKey( Bouquet, on_delete=models.PROTECT ) count = models.PositiveIntegerField(default=0) admin.py from .models import Flower, Bouquet, CompositionOfTheBouquet class CompositionOfTheBouquetInline(admin.TabularInline): model = CompositionOfTheBouquet @admin.register(Flower) class Flower(admin.ModelAdmin): pass @admin.register(Bouquet) class Bouquet(admin.ModelAdmin): inlines = [CompositionOfTheBouquetInline, ] What you need to do: When adding a flower and its quantity, you need to remove this number of flowers and save it in the Flower table, stock column. Important: calculations should take place when adding a Bouquet through the admin panel -
Django media 'image.url' showing the image path instead of the actual image
here's the HTML: {{player.image.url}} and this is what it shows up: the view: def homepage(request): thePlayer = Player.objects.get(name="Hamada") return render(request, 'homepage.html', {'player': thePlayer}) settings.py: MEDIA_ROOT = path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' image field in the model: image = models.ImageField(default="images.png") project urls.py: from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainApp.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) app urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.homepage, name="homepage") ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
inserting a django form with javascript
what I am trying to do is fairly simple: I want to add {{ form }} to a table cell with javascript this what I have but it only works for labels: function showOrHideReconciliationTable() { var checkBox = document.getElementById("edit-inventory-reconciliation"); if (checkBox.checked == true) { var table = document.getElementById("main-table"); var row = table.insertRow(7); row.classList.add("warehouse-row"); row.setAttribute('id','table-toogle'); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); cell1.innerHTML = "{{ form }}"; cell2.innerHTML = "NEW CELL2"; cell3.innerHTML = "NEW CELL3"; } else { var table = document.getElementById("main-table"); var row = table.deleteRow(7); } any help would be appreciated (it's probably something simple or you cannot do it this way) Thanks! -
Filter available blocks for StreamField in Wagtail's Editor Interface
I have the following StructBlock subclasses and Page subclass class TestimonialBlock(blocks.StructBlock): class Review(blocks.StructBlock): text = blocks.TextBlock(label=_("Text")) author = blocks.TextBlock(label=_("Author")) link = blocks.URLBlock(required=False, label=_("Author link")) class Meta: icon = "openquote" label = _("Testimonial") title = blocks.TextBlock(required=False, label=_("Title")) review_list = blocks.ListBlock(Review(), label=_("Review(s)")) class TeamBlock(blocks.StructBlock): class Member(blocks.StructBlock): name = blocks.TextBlock(label=_("Name")) role = blocks.TextBlock(label=_("Role")) photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("Team") title = blocks.TextBlock(required=False, label=_("Title")) member_list = blocks.ListBlock(Member(), label=_("Member(s)")) class RPTeamBlock(blocks.StructBlock): class UpMembers(blocks.StructBlock): photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("RPMember") class DownMembers(blocks.StructBlock): photo = ImageChooserBlock(label=_("Photo")) link = blocks.URLBlock(required=False, label=_("Profile link")) class Meta: icon = "group" label = _("RPMember") class Meta: icon = "group" label = _("Team") title = blocks.TextBlock(required=False, label=_("Title")) up_member_list = blocks.ListBlock(UpMembers(), label=_("Member(s) top")) down_member_list = blocks.ListBlock(DownMembers(), label=_("Member(s) down")) class LandingPage(Page): THEMES = [("transitive", "Transitive"), ("rp", "RP")] # WEBSITE IDENTITY website_theme = models.CharField( blank=False, null=False, max_length=32, choices=THEMES, default=THEMES[0][0], verbose_name=_("Theme"), ) website_logo = models.ForeignKey( "wagtailimages.Image", blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("Logo"), related_name="website_logo", ) # WEBSITE CONTENT body = StreamField( [ ("testimonial", TestimonialBlock()), ("team", TeamBlock()), ("rpteam", RPTeamBlock()), ], blank = True, null = True, use_json_field = True ) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel("website_theme", widget=forms.Select), FieldPanel("website_logo"), ], … -
How to get annotated attributes in a template from a DetailView?
I'm working on a small e-commerce. For a model 'Product' I keep track of the stock using a Custom Manager and a method called Products.objects.with_stock() that uses annotations (I'm required to do so, there's no way I can add a stock attribute in Product) In a ListView of all the products, it's pretty straightforward to add the stock, to access it from a template: # app/views.py class ProductListView(ListView): ... def get_stock(self, obj): return obj.stock def get_queryset(self): return super().get_queryset().with_stock() And then in the template I just call it: <!-- templates/home.html--> {% for product in products %} <p> Stock: {{product.stock}} <p> {% endfor %} How do I perform something similar for a DetailView? Given that a DetailView gets a particular object instance, where or how do I run something similar to what I did in the ListView? Where do I run that query method that affects all objects as a whole, so that then I can access it in the same way from the template? -
How to use whitenoise with digitalochen space?
Attempted access to '/img/apple-touch-icon.png' denied. , django - digitalocean - spaces what is the riget way to connect django with digitalocean spaces this is my code from storages.backends.s3boto3 import S3Boto3Storage class StaticRootS3Boto3Storage(S3Boto3Storage): location = 'static' class MediaRootS3Boto3Storage(S3Boto3Storage): location = 'media' import os AWS_ACCESS_KEY_ID="----" AWS_SECRET_ACCESS_KEY="---" AWS_STORAGE_BUCKET_NAME="---" AWS_S3_ENDPOINT_URL="---" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } AWS_LOCATION = "----" DEFAULT_FILE_STORAGE = "----.cdn.backends.MediaRootS3Boto3Storage" STATICFILES_STORAGE = "----.cdn.backends.StaticRootS3Boto3Storage" DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/' and i got this erorr when i run my server