Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I can't start Django web site with docker?
I have a Django web app and I need to launch it with docker. I created two images: one for Django and another for postgresql. It successfully builds but during the composing up shows the problem that django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module. Seems like docker didn't install psycopg2 from requirements.txt. Dockerfile: # Here I'm creating an image for Django. FROM python:3.10.0-alpine COPY requirements.txt /requirements.txt COPY movies_admin /movies_admin WORKDIR /movies_admin EXPOSE 8000 RUN apk add postgresql-client build-base postgresql-dev RUN pip install -r requirements.txt docker-compose.yml services: django: build: context: . ports: - "8000:8000" volumes: - "./movies_admin:/movies_admin" environment: - DB_HOST=database - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe command: sh -c "python3 manage.py runserver 0.0.0.0:8000" depends_on: - database database: image: postgres:16 environment: - POSTGRES_DB=movies_database - POSTGRES_USER=app - POSTGRES_PASSWORD=123qwe requirements.txt asgiref==3.8.1 autopep8==2.1.0 black==24.3.0 click==8.1.7 Django==5.0.4 django-split-settings==1.3.1 flake8==7.0.0 mccabe==0.7.0 mypy-extensions==1.0.0 packaging==24.0 pathspec==0.12.1 platformdirs==4.2.0 psycopg2==2.9.9 psycopg2-binary==2.9.9 pycodestyle==2.11.1 pyflakes==3.2.0 python-dotenv==1.0.1 sqlparse==0.4.4 tomli==2.0.1 typing_extensions==4.11.0 -
Django- How to use django-silk to work in running tests
I use the django-silk to profile the APIs of my Django project (Django + DRF). Currently, I call APIs in the browser (using DRF browsable API) and then I can see the API profiling data in the silk. When I run the test command, it doesn't capture requests and responses and therefore it doesn't create any profiling data to show. Is there a way to force the silk to work in test environment? My idea is to instead of calling APIs one by one in the browser and then check the silk, only run the tests and then see the profiling data after tests finished. -
Is it possible to use Hug with Django?
I'm a Django developer and recently stumbled onto the Hug framework... Then I decided to give it a shot. But usually when you talk about building RESTful APIs with Django you usually use the Django Rest Framework (DRF)... -
Dropzone.js does not post files in queue, only post files with JavaScript is incorrectly formatted
I have a Django project that uses Dropzone to upload multiple files to a project a user has created. All of this is within the same instance (project is created alongside file uploads), so I am using autoProcessQueue: false and running dropzone.processQueue() once the rest of the form data has been added. I have a malformatted javascript file that ends up working. Files are posted and I can access them through <MultiValueDict: {'file': [<InMemoryUploadedFile: <img_name>.jpg (image/jpeg)>]}>. This 'works' but I cannot upload multiple files. My correctly formatted javascript doesn't return anything. When I drop a file into the dropzone space in the html, the preview shows but now file is loaded. When I POST the form, I get this in the output for dropzone: <MultiValueDict:[] Why is my bad JS partially functional, but my proper JS is not capturing any file uploads? BAD but Working javascript.js for 1 file in dropzone dropzonePreviewNode && (dropzonePreviewNode.id = "", previewTemplate = dropzonePreviewNode.parentNode.innerHTML, dropzonePreviewNode.parentNode.removeChild(dropzonePreviewNode), dropzone = new Dropzone(".dropzone", { headers: { 'X-CSRFToken': csrftoken }, autoProcessQueue: false, url: "create", method: "post", uploadMultiple: true, previewTemplate: previewTemplate, previewsContainer: "#dropzone-preview", acceptedFiles:'.jpg', }) dropzone.on('success', dropzone.processQueue.bind(dropzone)); Correct JS, but not working - Causes Broken Pipe: dropzonePreviewNode && (dropzonePreviewNode.id = "", … -
jango Cannot resolve keyword 'display_data' into field. Choices are: choosenum, displays, id, puplish_date, users v2
hi i have a django project rise the error above this is models.py class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display,related_name='display_data') users= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this is views.py check_url_exists(url_to_check): try: countArray= [] # محاولة استرداد سجل بناءً على الرابط المعطى display_obj = Display.objects.get(url=url_to_check) for i in range(1, 6): # حساب عدد السجلات where choosenum = i count = Display_Data.objects.filter(display_data__url=url_to_check, choosenum=i).count() print(count)# إضافة عدد السجلات إلى القائمة countArray.append(count) return countArray # الرابط موجود في قاعدة البيانات except Display.DoesNotExist: countArray= [0,0,0,0,0] return countArray def display_video(request, url): # تشكيل الـ URL الكامل لإطار الفيديو على YouTube embed_url = f"https://www.youtube.com/embed/{url}" full_url = f"https://www.youtube.com/watch?v={url}" soup = BeautifulSoup(requests.get(full_url).content, "html.parser") title = soup.title.text # استخدم نموذج "display_data" countArry=check_url_exists(embed_url) # استخدم "Count" لحساب عدد السجلات # طباعة النتيجة this is templete who is include with the templete above <div class="container mt-5"> <div class="d-flex justify-content-start">> <!-- زر "نجحت" --> <button type="submit" name="CHOOSE" value="1" class="btn btn-success mr-2">{{carry_0}} نجحت</button> <!-- زر "فشلت" --> <button type="submit" name="CHOOSE" value="2" btn btn-danger mr-2">{{carray_1}}فشلت</button> <!-- زر "تحتاج إلى مال" --> <button type="submit" name="CHOOSE" value="3" class="btn btn-warning mr-2">تحتاج إلى مال{{carray_2}}</button> <!-- زر "تحتاج إلى أدوات" --> <button type="submit" name="CHOOSE" value="4" btn btn-info mr-2">{{carray_3}}تحتاج إلى أدوات</button> <!-- زر "مؤجل" --> … -
Loop in a Django template simple_tag returning a dictionary
When using a simple template tag that returns a dictionary: @register.simple_tag def get_types(): return { "item1": "Foo", "item2": "Bar", } This doesn't print any column: {% for type in get_types.values %} <th>{{ type }}</th> {% endfor %} While this does: {% get_types as types %} {% for type in types.values %} <th>{{ type }}</th> {% endfor %} Is there a way to make it work without having to put the temporary variable {% get_types as types %}? Most questions I found on StackOverflow or in forums are from 2018 or older. I'm wondering if there is a cleaner way to do this 6 years later as I'm not a fan of temporary variables. -
Django newbie started an hour ago
here Why is this happening? I just copied whatever this guy explained and tried mapping the URLs to views but my homepage ended like the image. Please help me and explain however you can. nothing yet cause i am still learning and this is my first time. please dont judge me -
How to use Celery as priority queue?
I use Celery to process background jobs that use a blocking API for a Django web app. Since the API can only process one job at a time, I also use a lock (implemented with Redis) to ensure that only one job is running at a time. I have jobs with different priorities, and I wonder if I need to implement the sorting by priority myself, or if celery or Redis already provides a priority queue, which might also be more robust against race conditions. Best would be if I also had the option for the current job to check if something with a higher priority is in the queue and then decide if it should cancel the current operation and put it back in the queue. -
How do i get this filter class view to work since first two views are working?
Just started learning django. I can't get the filtering for this to work: views.py: class BlogPostList(APIView): def get(self, request, format=None): title = request.query_params.get("title", "") if title: blog_posts = BlogPost.objects.filter(title_icontains=title) else: blog_posts = BlogPost.objects.all() serializer = BlogPostSerializer(blog_posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) urls.py: urlpatterns = [ path("blogposts/", views.BlogPostListCreate.as_view(), name="Blogpost-view-create"), path("blogposts/<int:pk>/", views.BlogPostRetrieveUpdateDestroy.as_view(), name="update"), path("blogposts/", views.BlogPostList.as_view(), name="Filter"), ] the first two views work. models.py: from django.db import models # Create your models here. class BlogPost(models.Model): title = models.CharField(max_length=100) content = models.TextField() published_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title here's the full views.py code: from django.shortcuts import render from rest_framework import generics, status from rest_framework.response import Response from .models import BlogPost from .serializers import BlogPostSerializer from rest_framework.views import APIView # Create your views here. class BlogPostListCreate(generics.ListCreateAPIView): queryset = BlogPost.objects.all() serializer_class = BlogPostSerializer def delete(self, request, *args, **kwargs): BlogPost.objects.all().delete() return Response(status=status.HTTP_204_NO_CONTENT) class BlogPostRetrieveUpdateDestroy(generics.RetrieveUpdateDestroyAPIView): queryset = BlogPost.objects.all() serializer_class = BlogPostSerializer lookup_field = "pk" class BlogPostList(APIView): def get(self, request, format=None): title = request.query_params.get("title", "") if title: blog_posts = BlogPost.objects.filter(title_icontains=title) else: blog_posts = BlogPost.objects.all() serializer = BlogPostSerializer(blog_posts, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
Use autocomplete filter in Django admin back-end for integer / dates / string fields
Is it possible to use an autocompelte filter class to be used in the list_filter for normal fields (i.e. not foreign keys or other relations)? For example, for this model: class Project(models.Model): project_number = models.DecimalField(max_digits=15, decimal_places=0, blank=True, null=True) I'd like to have an autocomplete filter in my admin back-end for the project_number field. Would [admin_auto_filters][1] be able to do that? -
Integrating a fine-tuned model into my Django-React application issue
I have a feature where the user can log what they’ve eaten for meal and the food data would get passed into to a fine-tuned model on OpenAI I created and the model would feedback to the user the impact it would have on their sugar levels and well-being. After having trained the model using the jsonl file which successfully completed and tested it in the playground. When I include the code in my views.py and test it, i get a 200 response in the terminal, but on the UI its saying “Sorry, I couldn’t provide a response. Please try again.”. Any help here would be much appreciated to help me fix this issue. On the frontend, the user enters what they had for breakfast for example, fish and chips, and the model would produce an output like shown on the second image. Dietary habits UI user enters their food `const DietaryHabits = () => { const [selectedDate, setSelectedDate] = useState(new Date()); const [open, setOpen] = useState(false); const [currentMeal, setCurrentMeal] = useState(''); const [foodEntry, setFoodEntry] = useState(''); const [entries, setEntries] = useState({ Breakfast: '', Lunch: '', Dinner: '', Snacks: '' }); const [dietaryAdvice, setDietaryAdvice] = useState(''); const handleClickOpen = (meal) … -
Django group by after annotate does not work
I have the following Django models: class Order(models.Model): ... org_slug = models.CharField() class ProductToOrder(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) qty = models.IntegerField() cost = models.FloatField() I need to sum Orders that grouped by on org_slug and it must have sum of orders that have only one ProductToOrder and ProductToOrder.qty=1 I'm trying to do it in this way orders = Order.objects.filter( some_filter_here ).values('org_slug').annotate( order_sum=Subquery(Order.objects.filter( org_slug=OuterRef('org_slug')).annotate( product_count=Coalesce(Sum('producttoorder__qty'), 1) ).filter(product_count=1).values('org_slug').annotate( sum=Sum('producttoorder__cost') ).values('sum')[:1] But it returns queryset of all orders. For example, if I have 1000 orders and 2 org_slugs, I need to get 2 objects in the query list but it returns 1000. This line where I'm trying to group by queryset in the following Subquery does not work: .filter(product_count=1).values('org_slug') I'm tried a lot of different querysets to fix it but it didn't give me any positive result. I see only one way to fix it, I need to create qty field in Order model but I hope, there are other ways to fix it. Can anybody help me with it? -
Docker / Celery / Django : Run a task with `celery` in a container while my `django` server is running in another container. It's possible?
I'm working on a project that uses Django, I'm a beginner with Django and Docker. For a feature, I decided to create a task with Celery (the feature consist to create a matchmaking queue) But, I use Docker for run my app, and I have 3 containers : one is for the frontend (node), the second for Django and the last is for my database PostgreSQL. And I don't really know if it's necessary to create another container for Celery. I found nothing with my research about a thing like that, but (if I say nothing wrong) in theory, it's possible and even very good to create a container for Celery, it's logic. So, I tried to launch my celery task in background, then launch my Django server like this in the same container : $ celery -A backend worker -l INFO --detach $ daphne -p 8000 backend.asgi:application TWO PROBLEMS : We lose the whole point of using Docker doing this AND we can't see the logs of celery. Problem : it is "ok" to do that, or it's really better to create another container for Celery or only for my task ? If yes, how I can do this … -
How to replicate tinymce V6 html minification on Django templates?
So I'm using both tinymce and React-hook-forms to create a form which is linked to a Django backend. I've recently updated tinymce to version 6 but I have noticed that now it automatically minifies the default values upon mounting I.e. if the default value is: <p>Random text<p> <p>Random text 2<p> Then the final tinymce result will be: <p>Random text<p> <p>Random text 2<p> I need to replicate this logic on the Django template backend otherwise the default template value and the actual tinymce value will be different and set dirty fields equal to true on react-hook-forms. This is easy to do for small templates, I've created my own personal python minification function but this does not work for large templates. Is there any way for me to replicate the tinymce minification process on the backend or somehow turn it off in the tinymce config frontend? Note: I have already tried a couple of backend minification libraries like django-htmlmin but this hasn't worked. -
Why does the nested sterilizer in django rest framework not work?
Good afternoon, I'm making an API and I ran into a problem, the embedded sterilizer does not work. Models from django.db import models def upload_to(instance, filename): return 'posts/{filename}'.format(filename=filename) class Brands (models.Model): BrandsDescription=models.TextField(null=True) def __str__(self): return self.BrandsDescription[0:50] class Cosmetic (models.Model): CosmeticName = models.TextField(default="") CosmeticDescription = models.TextField(null=True) Price = models.IntegerField(null=True) UrlsImage = models.ImageField(upload_to=upload_to, default = "") IsItNew = models.BooleanField(default="") Brands = models.ForeignKey(Brands,related_name="brands", on_delete=models.CASCADE) def __str__(self): return self.CosmeticName[0:50] class Order (models.Model): UserToken = models.TextField(default="") Date= models.DateTimeField(auto_now_add=True) Product = models.ManyToManyField(Cosmetic) Price = models.IntegerField(null=True) class Meta: ordering = ['UserToken'] def __str__(self): return self.UserToken[0:50] Serializers from dataclasses import field from rest_framework.serializers import ModelSerializer from rest_framework import serializers from .models import * class BrandsSerializer(ModelSerializer): class Meta: model= Brands fields='__all__' class CosmeticSerializer(ModelSerializer): brands=BrandsSerializer(read_only=True, many=True) class Meta: model= Cosmetic fields=('CosmeticName','CosmeticDescription','Price','UrlsImage','IsItNew','brands') class OrderSerializer(ModelSerializer): product = CosmeticSerializer(read_only=True, many=True) class Meta: model= Order fields=('UserToken','Date','product','Price') class postOrderSerializer(ModelSerializer): class Meta: model= Order fields='__all__' Views from rest_framework.decorators import api_view from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import * from rest_framework.authentication import TokenAuthentication from api.permissions import IsAdminOrReadOnly from .serializers import * from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter class BrandsAPI(viewsets.ModelViewSet): queryset= Brands.objects.all() serializer_class = BrandsSerializer def get_paginated_response(self, data): return Response(data) class CosmeticAPI(viewsets.ModelViewSet): queryset= Cosmetic.objects.all() serializer_class = CosmeticSerializer def get_paginated_response(self, data): return Response(data) … -
Django doesn't send csrftoken and sessionid cookies
I accidentally deleted the csrftoken and sessionid cookies and now django is not sending me new cookies when pages load. What to do? (I'm using the Edge browser) -
django Could not parse the remainder: '[0]' from 'carray[0]'
hi i receved the mistake above with this sutiuation type here def check_url_exists(url_to_check): try: countArray= [] # محاولة استرداد سجل بناءً على الرابط المعطى display_obj = Display.objects.get(url=url_to_check) for i in range(1, 6): # حساب عدد السجلات where choosenum = i count = Display_Data.objects.filter(url=url_to_check, choosenum=i).count() print(count)# إضافة عدد السجلات إلى القائمة countArray.append(count) return countArray # الرابط موجود في قاعدة البيانات except Display.DoesNotExist: countArray= [0,0,0,0,0] return countArray def display_video(request, url): # تشكيل الـ URL الكامل لإطار الفيديو على YouTube embed_url = f"https://www.youtube.com/embed/{url}" full_url = f"https://www.youtube.com/watch?v={url}" soup = BeautifulSoup(requests.get(full_url).content, "html.parser") title = soup.title.text # استخدم نموذج "display_data" countArry=check_url_exists(url) # استخدم "Count" لحساب عدد السجلات # طباعة النتيجة # مرر الـ embed_url وعنوان الفيديو إلى القالب return render(request, 'display/videoA.html', {'embed_url': embed_url , 'title': title,'carry':countArry}) and templet have include sentence <div class="container mt-5"> <div class="d-flex justify-content-start">> <!-- زر "نجحت" --> <button type="submit" name="CHOOSE" value="1" class="btn btn-success mr-2">{{carray[0]}} نجحت</button> <!-- زر "فشلت" --> <button type="submit" name="CHOOSE" value="2" btn btn-danger mr-2">{{carray[1]}}فشلت</button> <!-- زر "تحتاج إلى مال" --> <button type="submit" name="CHOOSE" value="3" class="btn btn-warning mr-2">تحتاج إلى مال{{carray[2]}}</button> <!-- زر "تحتاج إلى أدوات" --> <button type="submit" name="CHOOSE" value="4" btn btn-info mr-2">{{carray[3]}}تحتاج إلى أدوات</button> <!-- زر "مؤجل" --> <button type="submit" name="CHOOSE" value="5" class="btn btn-secondary">{{carray[4]}}مؤجل</button> <!-- زر "اخر نجاح" --> <button … -
My custom permission isn't blocking put requests for editing objects
I have this permission class class AuthorOrReadOnly(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.author == request.user And this viewset class PostViewSet(viewsets.ViewSet): permission_classes = (AuthorOrReadOnly, ) queryset = Post.objects.all() serializer_class = PostSerializer def list(self, request): serializer = self.serializer_class(self.queryset, many=True) return Response(serializer.data) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.validated_data['author'] = request.user serializer.save() return Response(serializer.data, status=201) return Response(serializer.errors, status=400) def retrieve(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post) return Response(serializer.data) def update(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400) def partial_update(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) serializer = self.serializer_class(post, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=400) def destroy(self, request, pk=None): post = get_object_or_404(self.queryset, pk=pk) post.delete() return Response(status=204) And when I open my view url route It hidden the input fields for put patch... etc methods. But when I make a request from shell it just edit any objects. So I think my permission isnt working. I already tried put permission in list and a tuple and tried combining with other permissions, changing has_permission func, but It looks like it didnt work at all. -
For some reason the code doesn’t work until you set it unsafe in the settings? [closed]
from asgiref.sync import sync_to_async @sync_to_async @login_required def export_excel1(request): pricesecret = Price.objects.get(id=1) path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "" try: os.makedirs(path) except: path = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "" filepath = '/var/www/django/mysite/static/media/pricenew/' + str(request.user.usrid.listusers_id) + '/' + pricesecret.url + '.xlsx' if os.path.exists(filepath) and os.stat(filepath).st_size != 0: url = "https://x.x.x.x/static/media/pricenew/" + str( request.user.usrid.listusers_id) + "/" + pricesecret.url + ".xlsx" print(filepath) return JsonResponse({'priceurl': 0, 'filepath': filepath, 'pricesecret': pricesecret.url + '.xlsx', 'url': url}) else: files = os.listdir("/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "") if files: files = ''.join(map(str, files)) eawa = "/var/www/django/mysite/static/media/pricenew/" + str(request.user.usrid.listusers_id) + "/" os.remove(eawa + files) price_title = "Прайс_" + datetime.today().strftime('%Y-%m-%d %H:%M') headers = ( 'Код', 'Артикул', 'Наименование', 'Производитель', 'Ед', 'Цена,руб', 'Остаток', 'Заявка', 'Норма отпуска', 'Новинка!', 'Изображение') data = [] data = tablib.Dataset(*data, headers=headers, title=price_title) products = Product.objects.filter(stock__gt=0, published=True).select_related('brand', 'product_sklad').prefetch_related( 'brand__clt1__client_id__discount_list_k1', 'category__parent', ).exclude( product_sklad__gte=1) saleban = Salenban.objects.filter(client_id=request.user.usrid.listusers_id, published=1).select_related('client_id', 'mf_un').prefetch_related( 'client_id__discount_list_k1').values_list('mf_un', flat=True) post = [] for person in saleban: post.append(person) if saleban.exists(): for pos in post: products = products.filter.exclude(brand=pos) else: products = products for book in products: zayvka = "" if book.artikul == None: book.artikul = "" if book.brand == None: book.brand = "" if book.new_product == 0: book.new_product = "" if book.stock > 50: book.stock = ">50" data.append((book.id_p, book.artikul, book.name, book.brand, book.shtuk_e, book.price, … -
Django - Custom Translation for Django automatically generated messages
In a django project, how do I access the messages generated automatically by django? After implementing internationalization it seems some messages have been left our of the translation. IN particular those generated as part of the authentication process. Amongst the different messages I am trying to access is this one: The two password fields didn’t match.. I thought I could: override the existing UserCreationForm in the views write the sentence in english I want to override use from django.utils.translation import gettext as _ to capture it in the .po file. It feels overly complicated for what I am trying to achieve. Is there a more elegant way to achieve this? forms.py: class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) def clean_email(self): if User.objects.filter(email=self.cleaned_data['email']).exists(): raise forms.ValidationError(_("the given email is already registered")) return self.cleaned_data['email'] class Meta: model = User fields = ["username", "email", "password1", "password2"] def __init__(self,*args,**kwargs): super(RegisterForm, self).__init__(*args, **kwargs) #iterate over form fields and set label to false for field_name, field in self.fields.items(): field.label = False views.py def register_user_form(request): url = request.META.get('HTTP_REFERER') if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = True user.save() age_group = form.cleaned_data.get('age_group') # check if userprofile with same username already exists user_profile, created = UserProfile.objects.get_or_create( … -
How to get an object by max value in Django ORM
I'm searching for a better way to do this: i need to get an object with the highest value in a model. The value isn't stored in a field, instead it is a number of objects from related(secondary) model (ManyToOne relations, ForeignKey) I've tried this: from django.db.models import * annotatedPM = PrimaryModel.objects.annotate(Count('secondarymodel')) max_value = annotatedPM.aggregate(Max('secondarymodel__count'))['secondarymodel__count__max'] annotatedPM.get(secondarymodel__count=max_value) >>> <PrimaryModel: object> This variant works well, but i'm wondering, is there any better way to do this? -
Django Class Based View Failed to Pass a Variable to the Template
I am new to Django and trying to build up a simple catalog site. I inserted some data into the table. So there should be values at primary key = 1 However, class is empty after passing to the template allclass_detail.html. There should be name and description text above the red line as in the screenshot Missing text, but now they are missing Same thing happened to both AllClassDetailView() and CombatEngravingDetailView() views.py from django.shortcuts import render from .models import CombatEngraving, ClassEngraving, AllClass, Archetype from django.views import generic from django.shortcuts import HttpResponse, Http404 def index(request): return render(request, 'index.html') class AllClassListView(generic.ListView): model = AllClass paginate_by = 5 context_object_name = 'class_list' template_name = 'catalog/class_list.html' class AllClassDetailView(generic.DetailView): model = AllClass def all_class_detail_view(request, primary_key): try: the_class = AllClass.objects.get(pk=primary_key) except AllClass.DoesNotExist: raise Http404('Class does not exist') return render(request, 'catalog/allclass_detail.html', context={'class': the_class}) class CombatEngravingListView(generic.ListView): model = CombatEngraving paginate_by = 10 context_object_name = 'combat_engraving_list' template_name = 'catalog/combat-engraving.html' class CombatEngravingDetailView(generic.DetailView): model = CombatEngraving def combat_engraving_detail_view(request, primary_key): try: combat_engraving = CombatEngraving.objects.get(pk=primary_key) except CombatEngraving.DoesNotExist: raise Http404('Combat Engraving does not exist') return render(request, 'catalog/combatengraving_detail.html', context={'combat_engraving': combat_engraving}) class_list.html {% extends "base_generic.html" %} {% block content %} <h1>Class List</h1> {% if class_list %} <ul> {% for class in class_list %} <li> <a href="{{ class.get_absolute_url … -
How to make CKEditor Django Mobile Responsive?
Well, I have a website that contains a ckeditor field (RichTextUploadingField) Default, no extra config but I want it to be mobile responsive. Here's the look of ckeditor in mobile view: I am not able to wrap it in a width coz that also doesn't work. I wasn't able to find any of solutions. Thank You! -
DisallowedHost message despite correctly configuring ALLOWED_HOSTS in my settings.py
Right, so I have an Amazon AWS Ubuntu server set up to deploy my website. I have correctly set up my virtual environment .venv and installed Python 3.10.12 and Django version 5.0.3 I have successfully cloned my GitHub Repo via the SSH methodology and have full access to said repo through my EC2 server I cd into my repo with no issues. I set up the NSG correctly - as confirmed my Amazon support I run the command python3 manage.py runserver 0.0.0.0:8000 I enter the Public IPv4 address http://xx.xx.xx.xx:8000/ into my address browser. Django Local Vars Settings.py Django Error Page Why are the local vars declaring the local host as given by Visual Studio Code 127.0.0.0.1 when this is clearly not the case. Its like it's refusing to take another look at the ALLOWED_HOSTS variable. I did read on here that this could be a cashe issue - if so how would I clear the cache. If this is not a cache issue then why is Django not seeing the correct host in the ALLOWED_HOSTS settings.py variable. Why has this not updated itself? Even when I clear the cache from my browser and even tried this in another browser, the … -
Hello, im new to programing can anyone help me with my problem, for some reason this massage keeps poping up
`Reverse for 'vjestiPlus' with arguments '('',)' not found. 1 pattern(s) tried: ['vjesti\-Dodavanje/(?P<slug>[-a-zA-Z0-9_]+)\Z'] `This is my views.py class VjestiDodavanje(View): def get(self, request, slug): vjest = Post.objects.get(slug=slug) context = { "vjest" : vjest, "vjestiForm" : VjestiForm() } return render (request, "members/vjestiDodavanje.html", context) def post(self, request, slug): vjestiForm = VjestiForm(request.POST) vjest = Post.objects.get(slug=slug) if vjestiForm.is_valid(): vjest = vjestiForm.save(commit=False) vjest.post = vjest vjest.save() return HttpResponseRedirect(reverse("vjestiPlus", args=[slug])) context = { "vjest" : vjest, "vjestiForm" : VjestiForm() } return render (request, "members/vjestiDodavanje.html", context) html {% extends "base.html" %} {% load static %} {% block title %} Vjesti {% endblock title %} {% block css_filles %} {% endblock css_filles %} {% block content %} <a href="{% url "><img src="{% static ' alt="Logo"></a> </div> <div> </div> <div class="desno"> <p class="naslovTekst"> <a href="{% url "prijava" %}">PRIJAVI SE</a></p> </div> <div class="desno"> <p class="naslovTekst"><a href="{%url "kontakti"%}">KONTAKTIRAJ NAS</a></p> </div> <div> <p class="naslovTekst"> <a href="{%url "vjesti"%}">VIJESTI</a></p> </div> </div> </header> <section id="all-posts"> <h2>My Collected Posts</h2> <ul> {% for post in Vjesti %} {% include "members/includes/vjestiPost.html" %} {% endfor %} </ul> </section> <p><a href="{% url "vjestiPlus" vjest.slug %}"> Dodavnje Vjesti </a></p> {% endblock content %} model.py class Post(models.Model): title = models.CharField(max_length=150) description = models.CharField(max_length=200) image = models.ImageField(upload_to="posts", null=True) date = models.DateField(auto_now=True) slug = models.SlugField(unique=True, db_index=True) …