Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Pagedown; Form looks highlighted
Not sure what is going on here. The form from django-pagedown looks highlighted. I followed the docs here; section: Outside Django Admin. I just cannot figure this out and I can't find and forms about the issue to help resolve this. When I click on the textarea to, the box turns white. forms.py from pagedown.widgets import PagedownWidget # Django from django import forms # local Django from .models import ExampleModel class ExampleForm(forms.ModelForm): content = forms.CharField(widget=PagedownWidget) """Form for Blog posts""" class Meta: model = ExampleModel fields = ['content'] views.py def get_form(request): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/success/') else: form = ExampleForm() return render(request, 'example.html', {'form': form}) example.html <!DOCTYPE html> <html lang="en"> <head> {{ form.media }} </head> <body> {{ form }} </body> </html> -
How to fix can't find CSS path in Django app?
When deploy Django project to Heroku, Style is not working fully and I have some errors "not found" If you have good experience, please explain to me. Thanks. -
Django Model Calculation Performing however .save() not updating postgresql database
I have some code that is basically supposed to execute on a button click. if response.POST.get("calculate"): sh.isEdit=False temp=[] for link in sh.tablink_set.all(): temp.append([link.link, link.tournName]) print(link.link) sh.createdsheet=finalCalc(temp) sh.save(update_fields=['isEdit', 'createdsheet']) everything is working fine, except for the last line to save. I know the rest of it is working, as a) the calculation performs fine as I printed the result to the console, and that looked totally fine. Moreover, I know that the saving issue is associated with the 'createdsheet' and not the boolean 'isEdit', as prior to adding 'createdsheet', my script was working fine. In my model, createdsheet is an 3-d arrayfield, and similarly, the function I call, 'finalCalc' returns a 3-d array. class eloSheet(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE, related_name="elosheet", null=True) name= models.CharField(max_length=500) startYear=models.CharField(max_length=4) endYear=models.CharField(max_length=4) createdSheet=ArrayField( ArrayField( models.CharField(max_length=100) ) ) isEdit=models.BooleanField(default=True) The error I get from the terminal is raise ValueError("The following fields do not exist in this " ValueError: The following fields do not exist in this model or are m2m fields: createdsheet however I know that the field does exist (I went to the admin page to confirm it was in the model) however I am unclear on what a ManyToMany field is. Any advice to make this work would be … -
Django Update fileinput widget doesnt work when field is required
I have a FileField in the form that I'm passing to my updateview. The default widget clearablefileinput is visually disgusting, so I changed it to the simple fileinput. The issue is that when I set my field to required in init method, the update doesnt work. Nothing happens when I push the update button. I only have 2 ways to make it work it seems: widget = fileinput but required = false widget = clearablefileinput and required = true I have no idea how these things work behind the scenes and honestly I'm angry that django is making me tackle the stupid clearable file input. Is there any way to make the fileinput work even when required = true? -
How to filter a condition in class based view
class PostDetailView(HitCountDetailView): model = PostForNewsFeed template_name = 'feed/post_detail.html' context_object_name = 'post' slug_field = 'slug' # set to True to count the hit count_hit = True def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context.update({ 'popular_posts': PostForNewsFeed.objects.filter(visibility='Public').order_by('-hit_count_generic__hits')[:3],'page_title': 'Shared Post' }) return context I am able to see even the Private Post instead of just Public Post. -
Docker and Django PermissionError: [Errno 13] when running collectstatic
Django version: 3.2.5 Python Image: python:3.9-alpine3.14 Nginx Image: nginxinc/nginx-unprivileged:1-alpine Docker version: 18.09.1, build 4c52b90 I am trying to configure my application to to use static files served via an Nginx proxy image within Docker. (Apologies if I explain this badly, I will explain it as well as I currently know how.) I have set up a volume within my docker-compose-prod.yml with the aim of serving static content here via those volumes and nginx. As part of that I have added the creating of the volumes to Dockerfile and edited the urls.py and settings.py to look for the relevant url patterns and set the STATIC_ROOT. The application builds fine but when I run docker compose -f docker-compose-prod.yml up I get a looping error conatining multiple references to collectstatic.py and with the error: PermissionError: [Errno 13] Permission denied: '/app/app/static/admin/css/nav_sidebar.css' Full stack trace is below. I have run chown -R 755 richard:richard on my home system just to be sure but this had no effect. collectstatic is run via a /static/run.sh script in the root of my project and is initialised from my Dockerfile. From what i understand, collectstatic should be going through each of my apps and collecting all the content from … -
Django payment calculation getting error query does not exist
info I try to make monthly billing app. i have get total_amount from property price. customer has multiple payments so i am trying to adding all payments amount of specific customer into customer collect_amount and collect_amount deducts from total amount. if i remove any payment from a customer the total_amount will update automatically. problem When i try to update the exiting payment the calculation create a mess. if anybody have a better solution to the reported post. I would be grateful for any help.. if i try to edit the exiting payment i want only that to updated particularly i don't want any changes in remaining balance. henceforth after i complete the updating exiting payment then the remaining balance can get updated it self. anybody know the better to calculate the amount...? please help me models.py: class Property(models.Model): area = models.CharField(max_length=255) price = models.IntegerField(default=0) class Customer(models.Model): name = models.CharField(max_length=255) prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True) total_amount = models.IntegerField(default=0) collect_amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.total_amount = self.prop_select.price self.total_amount -= self.collect_amount super().save(*args, **kwargs) class Payment(models.Model): customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, blank=True, related_name='payment') amount = models.IntegerField(default=0) def save(self, *args, **kwargs): self.customer.collect_amount += self.amount self.customer.save() super(Payment, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.customer.collect_amount … -
Django: show instance string value in ModelField
I initialize a ModelForm before to send it to front-end. Everything works ok but the generated form shows 'associative_subscription' and 'course' ids, but I want to show the strings converded values(more readable for the user). Here's my code: models.py class CourseSubscription(models.Model): start_date = models.DateField(default=datetime.date.today, null=False, blank=False, verbose_name="Data di inizio") associative_subscription = models.ForeignKey(AssociativeSubscription, on_delete= models.CASCADE, null=False, blank=False, verbose_name="Iscrizione Associativa") course = models.ForeignKey(Course, on_delete= models.CASCADE, null=False, blank=False, verbose_name="Corso") fee_paid = models.DecimalField(max_digits=7, decimal_places=2, null=False, blank=False, verbose_name="Quota versata") payment_completed = models.BooleanField(default=False, verbose_name="Pagamento Completo") expiration_date = models.DateField(editable=False, null=False, blank=False, verbose_name="Scadenza") payment_method = models.CharField( max_length = 4, blank=False, verbose_name="Modalità di pagamento", choices=PAYMENTS ) class Meta: unique_together = ("associative_subscription", "course") def __str__(self): return u'%s / Iscrizione corso %s dal %s al %s' % (self.associative_subscription.member, self.course, self.start_date.strftime('%d/%m/%Y'), self.expiration_date.strftime('%d/%m/%Y')) forms.py class CourseSubscriptionForm(ModelForm): def __init__(self, max_value, *args, **kwargs): super(CourseSubscriptionForm, self).__init__(*args, **kwargs) self.fields['fee_paid'] = forms.DecimalField( max_digits=7, decimal_places=2, required=True, label="Quota Versata", min_value=0.01, max_value=max_value, help_text= f"Valore Massimo: {max_value}", widget = forms.NumberInput() ) class Meta: model = CourseSubscription exclude = ('expiration_date','payment_completed') widgets = { 'associative_subscription': forms.TextInput(attrs={'readonly':'readonly'}), 'course' : forms.TextInput(attrs={'readonly':'readonly'}) } views.py def add_course_subscription(request, associative_subscription_id, course_id): if request.method == 'POST': ... return JsonResponse(context) associative_subscription = AssociativeSubscription.objects.get(id= associative_subscription_id) course = Course.objects.get(id = course_id) remaining_fee = course.inscription_price form = CourseSubscriptionForm( initial={ 'associative_subscription': associative_subscription, 'course':course, 'fee_paid': 1.00, }, … -
Using Weasyprint to create file response
I am making a web application with Django relating to guitar chord sheets. One of the features is the ability to generate a PDF from a chord sheet and download it. I am using Weasyprint to generate the PDF, but I'm getting a problem where instead of downloading the file, the view just shows a really long sequence of digits. Here's my view function: def download_pdf(request, song_id): song = get_object_or_404(Song, pk=song_id) song.chordsheet.open("r") chordsheet_html = HTML(string=chopro2html(song.chordsheet.read())) # Generates HTML from a text file, not relevant here chordsheet_css = CSS(string="div.chords-lyrics-line {\n" " display: flex;\n" " font-family: Roboto Mono, monospace;\n" "}\n") song.chordsheet.close() return FileResponse(chordsheet_html.write_pdf(stylesheets=[chordsheet_css]), as_attachment=True, filename=song.title + "_" + song.artist + ".pdf") And when I run the code, I get this: <html> <head></head> <body> (a 53,635-digit number here) </body> </html> For what it's worth, I have a similar view function that does the same thing except without the PDF generation (downloads the raw file) and it works fine. How can I fix this? -
How i can compare models in template
Why this compare code not work? I want to display all departments where departments filial = filial, but i got failure only. Thanks very much for you answers! {% for filial in filials %} {{ filial }} {% for dep in departments %} {{ dep }} {% if dep.Filial == filial.pk %} IFIFIFIFIF{{ dep.fullname }} {% endif %} {% endfor %} <br> {% endfor %} models: class Filials(models.Model): Fullname=models.CharField(max_length=30,blank=False) Entity=models.CharField(max_length=20,blank=True) City=models.CharField(max_length=15,blank=True) INN = models.IntegerField(max_length=20,blank=True,null=True) def __str__(self): return self.Fullname def get_absolute_url(self): return f'/{self.id}' class Department(models.Model): Filial=models.ForeignKey(Filials, on_delete=models.CASCADE,related_name='department', blank=True) Fullname = models.CharField(max_length=30,blank=False) def __str__(self): return self.Fullname -
LEFT JOIN with other param in ON Django ORM
I have the following models: class Customer(models.Model): name = models.CharField(max_length=255) email = models.EmailField(max_length = 255, default='example@example.com') authorized_credit = models.IntegerField(default=0) balance = models.IntegerField(default=0) class Transaction(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) payment_amount = models.IntegerField(default=0) #can be 0 or have value exit_amount = models.IntegerField(default=0) #can be 0 or have value transaction_date = models.DateField() I want to query for get all customer information and date of last payment. I have this query in postgres that is correct, is just that i need: select e.*, max(l.transaction_date) as last_date_payment from credit_customer as e left join credit_transaction as l on e.id = l.customer_id and l.payment_amount != 0 group by e.id order by e.id But i need this query in django for an serializer. I try with that but return other query Customer.objects.filter(transaction__isnull=True).order_by('id') But that i need is this rows example -
Django- how to render images in templates uploaded from admin?
I want to render images that I uploaded from my Django admin in my template views. Since I need to upload multiple images at a time, I declared a separate model, ShowPhoto, with a foreign key attached to my Problem model: models.py class Problem(models.Model): slug = models.SlugField(null = False, unique = True, max_length = 255) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) free = models.CharField(max_length = 1, choices = Free) #problem when introducing UUID field traceID = models.UUIDField(default=uuid.uuid4, editable = True) #use meta tags to optimize SEO metaTags = models.TextField(default = "") questionToProblem = models.TextField() class ShowPhoto(models.Model): show = models.ForeignKey(Problem, on_delete = models.CASCADE, related_name = "photos") photo = models.ImageField() class Meta: verbose_name = 'Solution Image' verbose_name_plural = 'Solution Images' Thus, in my admin.py, I also added: class AdminImageWidget(AdminFileWidget): def render(self, name, value, attrs=None, renderer = None): output = [] if value and getattr(value, "url", None): image_url = value.url file_name = str(value) output.append(u' <a href="%s" target="_blank"><img src = "%s" alt="%s" width="600" height="600" style="object-fit: cover;"/></a> %s ' % \ (image_url, image_url, file_name, _(''))) output.append(super(AdminFileWidget, self).render(name, value, attrs)) return mark_safe(u''.join(output)) class ShowPhotoInline(admin.TabularInline): model = ShowPhoto formfield_overrides = {models.ImageField: {'widget': AdminImageWidget}} @admin.register(Problem) class ProblemModelAdmin(admin.ModelAdmin): form = ProblemForm list_display = ('questionToProblem', 'topic', 'free', 'traceID') search_fields = … -
How to Save A Post from 2 forms
How to save a Post from 2 forms # iterable VISIBILITY_CHOICES =( ("1", "Private"), ("2", "Public"), ("3", "Selected Friends"), ("4", "Everyone"), ("5", "Only One Friend"), ) # creating a form class VisibilityForm(forms.Form): geeks_field = forms.ChoiceField(choices = VISIBILITY_CHOICES) Views: def create_post(request): user = request.user if request.method == "POST": form2 = VisibilityForm(request.POST) form = NewPostForm(request.POST, request.FILES) if form.is_valid(): data = form.save(commit=False) data.user_name = user data.save() messages.success(request, f'Posted Successfully') return redirect('home2') else: form = NewPostForm() form2 = VisibilityForm(request.POST) return render(request, 'feed/create_post.html', {'form':form,'form2':form2, 'page_title': 'Share a Post' }) class PostForNewsFeed(models.Model): title = models.CharField(max_length=100, blank=False, null=False) description = models.CharField(max_length=255, blank=False, null=False) #slug = models.SlugField(unique=True, max_length=100, blank=True,null=True) pic = models.ImageField(upload_to='path/to/img', default=None,blank=True) youtubeVideo = models.CharField(max_length=200, null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation2', default=1) visibility = models.CharField(max_length=10, blank=False, null=False, default="Private") <form class="form-signin" method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form|crispy }} {{ form2|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-info btn-block text-uppercase" type="submit" > Post</button ><br /> </div> </form> -
book appointment functionality
I have Django project, which contains two classes in model.py file, one is clinic(which has a contact number as a field) and other one is patient. I have rendered all the clinics in cards and each card has a button book-appointment. here is my model.py: class Clinic(models.Model): clinic_name = models.CharField(max_length=200, blank=True, verbose_name='Name') poster = models.ImageField(blank=True, null=True, upload_to='uploads/%Y/%m/%d', verbose_name='Picture') address = models.TextField(max_length=500, blank= True) contact_no = models.CharField(max_length=12, blank=True, verbose_name='Mobile') def __str__(self): return self.clinic_name class Patient(models.Model): clinic = models.ForeignKey(Clinic, on_delete=CASCADE) patient_name = models.CharField(max_length=200, blank=True) contact_no = models.CharField(max_length=12, blank=True) appointment_time = models.DateTimeField(auto_now=True) def __str__(self): return self.patient_name Now what I want is, when a authentic user which is patient in this case, clicks on book-appointment , A message should be sent on the clinics phone number saying this guys have booked an appointment with you on this date. how this can be achieved??? please guide me. -
convert django fileobject.chunks() into image
i am trying to create a progress bar for my file upload, so I need a way of know the state of the file been uploaded at any point in time. def simple_upload(request): if request.method == 'POST' and request.FILES['image']: file = request.FILES['image'] fs = FileSystemStorage() for chunk in file.chunks(): image = ImageFile(io.BytesIO(chunk), name=file.name) filename = fs.save(file.name, content=image) I am looking for a way of saving the chunk and later converting them into an image to be saved, I don't want to use the python read and right interface because i will be uploading the file to aws. can someone point me in the right direction. -
How to validate Django forms and show validation error in front-end?
My models.py class Room(models.Model): room_category = models.ForeignKey(Cat, on_delete=models.CASCADE) number = models.IntegerField(unique=True) people = models.IntegerField() picture = models.ImageField(upload_to = 'room/', null=True, blank=True) actual_price = models.IntegerField() offer_price = models.IntegerField() class Booking(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) room=models.ForeignKey(Room, on_delete=models.CASCADE) check_in=models.DateTimeField() check_out=models.DateTimeField() payment_status_choices = { ('SUCCESS', 'SUCCESS'), ('FAILURE', 'FAILURE'), ('PENDING', 'PENDING')} HTML file : <form id="booking-form" action="" method="POST"> {% csrf_token %} <div class="group"> <input type="hidden" name="category" id="id_category" class="input" value="{{ cat }}"> </div> <div class="group"> <label for="id_check_in" class="label">Check In</label> <input type="datetime-local" name="check_in" id="id_check_in" class="input"> </div> <div class="group"> <label for="id_check_out" class="label">Check Out</label> <input type="datetime-local" name="check_out" id="id_check_out" class="input"> </div> <div class="group"> <label for="id_people" class="label">People</label> <input type="number" name="people" id="id_people" class="input"> </div> <div class="group"> <button type="submit" class="button" style="font-family: Century Gothic;">Book</button> </div> </form> Views.py : def Explore(request, **kwargs): category=kwargs.get('category') room_list=Room.objects.filter(room_category=category) cat1 = Cat.objects.get(category=category) if request.method == 'POST': form=AvailabilityForm(request.POST) if form.is_valid(): data=form.cleaned_data else: return HttpResponseRedirect(reverse('system:homepage')) room_list = Room.objects.filter(room_category=category, people=data['people']) available_rooms = [] for room in room_list: if check_availability(room, data['check_in'], data['check_out']): available_rooms.append(room) if len(available_rooms) > 0: room = available_rooms[0] booking = Booking.objects.create( user=request.user, room=room, check_in=data['check_in'], check_out=data['check_out'], amount=100 ) booking.save() return HttpResponseRedirect(reverse('system:BookingList')) else: form=AvailabilityForm() context={'category':category, 'cat':cat1, 'room_list':room_list,} return render(request, 'system/explore.html', context) My forms.py class AvailabilityForm(forms.Form): category = forms.CharField(max_length=100) check_in = forms.DateTimeField(input_formats='%Y-%m-%dT%H:%M', required=True) check_out = forms.DateTimeField(input_formats='%Y-%m-%dT%H:%M', required=True) people = forms.IntegerField(required=True) def clean(self): cleaned_data = super().clean() room_list = … -
django "detail": "Method \"GET\" not allowed." (one to many relationship)
models.py from django.db import models class User(models.Model): username = models.CharField(max_length=64) class Games(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) game = models.CharField(max_length=128) serializers.py from rest_framework import serializers from . import models class UserSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = '__all__' class GameSerializer(serializers.ModelSerializer): class Meta: model = models.Games fields = '__all__' views.py from django.shortcuts import render from . import models from . import serializers from rest_framework import generics, status from rest_framework.views import APIView from rest_framework.response import Response class UserView(generics.ListCreateAPIView): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer class CreateUser(APIView): # this works just fine def post(self, request): serializer = serializers.UserSerializer(data= request.data) if serializer.is_valid(): username = serializer.data.get('username') queryset = models.User.objects.filter(username) if queryset.exists(): user = queryset[0] user.username = username user.save(update_fields=['username']) else: user = models.User.objects.create(username=username) user.save() return Response(serializers.UserSerializer(user).data, status=status.HTTP_200_OK) return Response({'BAD REQUEST': 'INVALID DATA'}, status=status.HTTP_400_BAD_REQUEST) class CreateGame(APIView): # this is causing problems def post(self, request): serializer = serializers.GameSerializer(data= request.data) if serializer.is_valid(): game = serializer.data.get('game') user = serializer.data.get('user') game = models.Games.objects.create(user=user, game=game) game.save() return Response(serializers.GameSerializer(game).data, status=status.HTTP_200_OK) return Response({'BAD REQUEST': 'INVALID DATA'}, status=status.HTTP_400_BAD_REQUEST) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.UserView.as_view(), name='view'), path('user', views.UserView.as_view(), name='user-view'), path('game', views.CreateGame.as_view(), name='create-game') ] Basically I have 2 models, the User and Game model, I want there to be … -
Django: include a url with no namespace
I have an a Django app, with respect to the project root at applib/hw/apps.py The name attribute of the config class within this apps.py is applib.hw. The app controls how a user is logged in. I wish it's urls to its own app url.py so its modular, but it fails: # applib/hw/urls.py url_patterns = [ path('accounts/login/', UserLoginView.as_view(), name='login'), path('version/', views.version_view, name='version'), ] This fails because then the login name for reversal is applib.hw.login, whereas Django expects just login I could place it in the project url.py but this defeats the modularity of the django app. -
When attempting to loaddata - get error problem installing fixture
I am trying to load data from a db.json file I created (Sqlite db was the source). The original database is Sqlite, and I am try to migrate to Mysql. Everything works fine under Sqlite. I get the following error: django.db.utils.OperationalError: Problem installing fixture '/home/balh/blah/db.json': Could not load trackx_site.Segment(pk=1): (1054, "Unknown column 'program_id' in 'field list'") It seems like the Mysql tables do not have the foreign key or something?.... The models look like this: class Program(models.Model): air_date = models.DateField(default="0000/00/00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00",blank=True) running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00",blank=True) remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) locked_expiration = models.DateTimeField(null=True,default=None,blank=True) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(max_length=64) producer = models.CharField(max_length=64) editor = models.CharField(max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) class Segment(models.Model): class Meta: ordering = ['sequence_number'] program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='segments', # link to Program ) sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00") title = models.CharField(max_length=190, blank=True) bridge_flag = models.BooleanField(default=False) seg_length_time = models.TimeField() seg_length_time_delta = models.DurationField(default=timedelta) seg_run_time = models.TimeField(default="00:00:00",blank=True) seg_run_time_delta = models.DurationField(default=timedelta) seg_remaining_time = models.TimeField(default="00:00:00",blank=True) seg_remaining_time_delta = models.DurationField(default=timedelta) author = models.CharField(max_length=64,null=True,default=None,blank=True) voice = models.CharField(max_length=64,null=True,default=None,blank=True) library = models.CharField(max_length=190) summary = models.TextField() audit_time = models.DateTimeField(auto_now=True) audit_user = models.CharField(null=True,max_length=32) … -
Django version not found when running docker-compose with python3.9 alpine image
Hi I'm trying to build out a basic app django within a python/alpine image. I am getting en error telling me that there is no matching image for the version of Django that I am looking for. The Dockerfile in using a python:3.9-alpine3.14 image and my requirements file is targeting Django>=3.2.5,<3.3. From what i understand these should be compatible, Django >= 3 and Python 3.9. When I run docker-compose build the RUN command gets so far as the apk add commands but fails on pip. I did try changing this to pip3 but this had no effect. Any idea what I am missing here that will fix this issue? requirements.txt Django>=3.2.5,<3.3 uWSGI>=2.0.19.1,<2.1 Dockerfile FROM python:3.9-alpine3.14 LABEL maintainer="superapp" ENV PYTHONUNBUFFERED 1 COPY requirements.txt /requirements.txt RUN mkdir /app COPY ./app /app COPY ./scripts /scripts WORKDIR /app EXPOSE 8000 RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache --virtual .build-deps \ build-base \ gcc \ linux-headers && \ /py/bin/pip install -r /requirements.txt && \ apk del .build-deps && \ adduser --disabled-password --no-create-home rsecuser && \ mkdir -p /vol/web/static && \ chown -R rsecuser:rsecuser /vol && \ chmod -R 755 /vol && \ chmod -R +x … -
How to add a journal reference to a django template
I want to add references from a list to a django template. Are there any extensions available that let me cite a reference from a list in a django template? -
Heroku - gunicorn timeout for simple Django app
I know there are several questions about that on SO but none of them solved my problem. I don't understand why there is a timeout in heroku (code=H12 desc="Request timeout") when I try to deploy my app knowing that this is a very lite Django app. Any idea of what could be the problem ? -
How to show some local information by clicking on the Folium marker, No popup, just out side the map box
I have about 1000 marker points on the folium map on my Django application. I would like to show the information of each point by clicking on the Marker. I tried the popup and it works well. But the information of each point is very detailed and I would like to show the information outside of the map box. Do you have any idea or any keywords to search for? -
Image not showing in Gmail - Using django
After testing sending an email from the local machine and get this URL https://ci4.googleusercontent.com/proxy/HtWaUlJqlZOG14quifhHYMFq5Br1BurGYqsuwPFVS2j8LTQeUxlce2SSqo8TLtszqF6Qf_jYdJJoADpgwn1OaVoAk-dJH14LZUyj5UMMAh7hrvZ8Xk0iDTQzEbJq03w9cn-86dJ7c_Q9T-oPVjaJDiXjWkGz_GKxs3HQ2uGGd_OMTF6BOA=s0-d-e1-ft#http:///media/products/397349892806/www.vivamacity.com6image_43794f79-7fa4-4a05-939b-7b0fbabe651c_900x_MaS1ucL.jpg Can you give me the solution to fix this issue??? -
annotate missing grouping keys with zero
I have models: class Deviation(models.Model): class DeviationType(models.TextChoices): TYPE1 = 'type1', TYPE2 = 'type2' COMMON = 'common' type = models.CharField( _('deviation type'), choices=DeviationType.choices, max_length=25, default=DeviationType.COMMON, ) class Task(models.Model): name = models.CharField() deviation = models.ForeignKey(Deviation) ORM request: res = Task.objects.values('deviation__type')\ .annotate(type=F('deviation__type'), count=Count('pk'))\ .values('type', 'count') As you can see the aim is to count Tasks grouping by deviation__type. If there is no Tasks with specific deviation__type, they will not be in res. For example if there no Tasks with deviation__type=COMMON the res will be: [ { "type": "type1", "count": 9 }, { "type": "type2", "count": 10 } ] Is that possible to add missing records in res like that: [ { "type": "losses", "count": 9 }, { "type": "personnel", "count": 10 }, { "type": "common", "count": 0 } ] ?