Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker doesn't reflect code change in docker container
I have a Django application that runs in the Docker container locally on Mac machine. This docker container is managed via docker-compose. Django application is configured to reload if its code changes. However, and this is a problem, when I change application code, Django default server reloads service, but changes are not reflected in the container. API response doesn't change. Here is my docker configuration: Dockerfile FROM python:2-slim RUN apt-get update && apt-get install -y build-essential COPY requirements /requirements RUN pip install -r /requirements/build.txt # copy app source into image COPY service_api /opt/service_api COPY manage.py /opt docker-compose.yml version: '3.7' services: service-django: image: service-django build: dockerfile: Dockerfile context: . ports: - 8000:8000 volumes: - ./service_api/:/opt/service_api/service_api # this path is correct! container_name: service-django hostname: service-django restart: always Docker desktop: 3.5.0 Docker Engine: 20.10.7 Compose: 1.29.2 Big Sur: 11.4 Any help will be appreciated! -
Django: class from models.py won't import
I have a django project where I have two models and added a third in this structure in the same file: from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Product(models.Model): title = models.CharField(max_length=120) class Category(MPTTModel): name = models.CharField(max_length=200) class Range(models.Model): test = models.CharField(max_length=200) For brevity I've only shown the 1st line but Product and Category work perfectly. I then added Range, went to the console and python manage.py makemigrations, then python manage.py migrate, no errors and I can see it in the migrations file. Would somebody please put me out of my mystery and explain why in the shell: from products.models import Product, Category, Range throws cannot import name 'Test' from 'products.models' Product and Category import fine, but not Range?? Am I being dim here? -
Django - getting init parameters into a clean method in a form
I have a model with a unique together and I want to validate this condition in my modelform. The unique together includes a field that is passed to the form in an init method, the user, and a field that is in the form. I'm having problems with getting the first two into the clean method for validation. My first attempts at this failed, and I found this post but I could not get it to work for my situation: How to get requested user in clean function in django forms? model: class Objective(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) objective_name = models.CharField(max_length=10) description = models.CharField(max_length=300) mode = models.CharField(max_length=2, default='LA') class Meta: unique_together = ['user', 'objective_name', 'course'] ordering = ['objective_name'] def __str__(self): return self.objective_name The view: def addobjective(request, course_id): this_course = get_object_or_404(Course, pk=course_id) user = request.user all_courses = Course.objects.filter(user=user) objective_list = Objective.objects.filter( course=this_course).order_by('objective_name') context = {'objective_list': objective_list} if request.method == 'POST': form = ObjectiveForm(request.POST, my_course=this_course) if form.is_valid(): obj = form.save(commit=False) obj.course = this_course obj.user = user obj.save() form = ObjectiveForm(my_course=this_course) context['form'] = form return redirect('gradebook:addobjective', course_id=this_course.id) else: form = ObjectiveForm(my_course=this_course) context['form'] = form context['this_course'] = this_course context['all_courses'] = all_courses return render(request, 'gradebook/objective-form.html', context) … -
Truncated or oversized response headers received from daemon process - throwing error for large files - django
Concept is like this: User will upload two files, program will compare the two excel files for matches. It will match based on amount column. I am using pandas and numpy to achieve this File1: File2: Program will create intermediate matched dataframe, it will contain indices of both dataframe, the matched dataframe will look like below: Then I am merging df1 and df2 with the help of above matched dataframe, after merge, it will look like below: Problem statement: I am using AWS t2.micro, when I use smaller files, everything works fine, program will create the merged dataframe without any error, but when I use files with 40000 entries each, pandas can able to create matched dataframe, but it is not creating merged dataframe. ie) it can able to perform the first step, after the first step, it is throwing me this Truncated error. I am thinking, whether this error is coming, because RAM memory is not enough. Reason for this conclusion is that, 40000 entries will create around 5lakhs entries in matched dataframe, whether this 5lakhs occupies the whole memory space. (1GB RAM in t2.micro) I have WSGIApplicationGroup %{GLOBAL} in apache setting, so that is not the problem and … -
how to get count of using model relation in django?
I have 2 models 1 is Job Model which is something like this class Job(models.Model): name=models.CharField(max_length=500,null=False,blank=False) description=models.TextField(max_length=5000,null=True,blank=True) slug=AutoSlugField(populate_from='name',null=True, blank=True) industry=models.ForeignKey('Industry',null=True, blank=True, on_delete=models.SET_NULL) and other model is Industry model. This model has one to one relation with Job model Industry model is like this class Industry(models.Model): name=models.CharField(max_length=2000,null=True, blank=True) Now what i'm trying to do is to get count of jobs against each indsutry using industry model like this {% for industry in industry_2 %} <li><a href="#"><h6 class="category-title">{{ industry.name }}</h6> <span class="category-count">{{ industry.jobs_count }}</span> </a></li> {% endfor %} but its not working for me, please help me in this regard to solve this issue. Do suggest any better method also, Thanks -
how can i add a search box inside list_filter django?
i want to add a search box in the filter box (that you define as list_filter) class Review (TrackingModifierMixin): rating = models.FloatField( _("rating"), help_text=_("Rating of the product"), ) class ReviewAdmin(SimpleHistoryAdmin): list_display= ['rating'] list_filter = ['rating'] -
Django, query filter not applying to prefetched data
I have a table that contains the details of cards, and another table that holds the inventory data for those cards for the users. I am trying to get the card's data and include the inventory quantities for the cards returned. I do this by adding a prefetch for the query. However when I try to filter the prefetched data by the user id, it is still returning data for the users other than the one that is logged in. Code: sql_int = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" cards = magic_set_cards.objects.all().exclude(side='b').extra(select={'int': sql_int}) \ .prefetch_related(Prefetch('inventoryCards', queryset=inventory_cards.objects.filter(user_id=request.user.id))) \ .values('id', 'set_id__code', 'set_id__name', 'set_id__isOnlineOnly', 'number', 'name', 'imageUri', 'hasNonFoil', 'hasFoil', 'inventoryCards__user_id', 'inventoryCards__nonfoil', 'inventoryCards__foil') \ .order_by('-set_id__releaseDate', 'set_id__name', 'int', 'number') Data returned: { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 3, 'inventoryCards__nonfoil': 2, 'inventoryCards__foil': 0 }, { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 1, 'inventoryCards__nonfoil': 0, 'inventoryCards__foil': 1 } ... As you can see from the data above, they are the same cards but it is returning the inventory data for two different users. Please … -
How to serialize a list of objects into list of numbers
With django-rest-framework, how can I serialize the many elements of a one-to-many relationship into a list of integers with their ids? For example in class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() I would like to get something like { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [15, 16, 17, 23] } -
urlpatterns in django for unicode names
I was working on categories in my website and after adding category with id like 11 or more it had a error . Reverse for 'category' with arguments '('more-cat', 14)' not found. 1 pattern(s) tried: ['category/(?P[\w-]+)/(?P[0-9])/'] its the urls.py re_path(r'^category/(?P<slug>[\w-]+)/(?P<id>[0-9])/' , views.listofproducts , name="category"), and its models.py class category(models.Model): sub_category = models.ForeignKey('self' , on_delete=models.CASCADE , null=True , blank=True , related_name='sub') sub_cat = models.BooleanField(default=False) name = models.CharField(max_length=200 , blank=True , null=True) create = models.DateTimeField(auto_now_add=True ,blank=True , null=True) update = models.DateTimeField(auto_now=True ,blank=True , null=True) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) image = models.ImageField(upload_to = 'category' , blank=True , null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("home:category" , args=[self.slug , self.id]) please help me with this problem.! -
File "/usr/local/lib/python3.6/site-packages/seacucumber/tasks.py", except SESAddressBlacklistedError, exc:
I working on transferring old version Django Project(1.8) to new version. I use python 3.9, Django 3.2.7, docker with celery, Redis, flower on a board. Right now such containers as db(postgres), web(python 3.6), Redis are working well, but celery(worker) and flower do not indicate sights of been live with the error above. celery.py from __future__ import absolute_import, unicode_literals import celery import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') from django.conf import settings # noqa app = Celery('core') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) cwd = os.path.dirname(os.path.realpath(__file__)) environment_name = os.getenv('ENVIRONMENT_NAME', 'dev').lower() environment_path = os.path.join(cwd, '', os.getenv('DJANGO_ENVDIR', 'envs/%s' % environment_name)) if os.path.isdir(environment_path): import envdir envdir.open(environment_path) class Celery(celery.Celery): def on_configure(self): if settings.ENABLE_SENTRY: import raven from raven.contrib.celery import register_signal, register_logger_signal client = raven.Client(settings.RAVEN_DSN) # register a custom filter to filter out duplicate logs register_logger_signal(client) # hook into the Celery error handler register_signal(client) Docker-compose.yaml version: '3.8' services: redis: image: redis networks: - default ports: - 6379:6379 worker: build: context: . dockerfile: Dockerfile image: madefire/chordtest command: celery worker -A core --loglevel=info networks: - default depends_on: - redis env_file: - ./.env.dev db: container_name: db hostname: db image: postgres:13.0-alpine networks: - default ports: - 5432:5432 volumes: - ./postgres_data:/var/lib/postgresql/data/ env_file: - … -
Why don't I see options from models.py in the template?
a doubt, do you know how to pass the options of a select from forms.py? It turns out that I made a model in the client app, then I passed it to the client app form, I inherited it in another form of an app called estimates, and when presenting it in the template, you only see the empty field without the options models.py (app clientes) class Clientes(models.Model): TITLE=( ('Mrs.','Mrs.'), ('Miss','Miss'), ('Mr.','Mr.'), ) titulo=models.CharField(max_length=200, null=True,choices=TITLE) nombre =models.CharField(max_length=80) def __str__(self): return f'{self.id}:{self.titulo}{self.nombre}' forms.py (app clientes) class ClientesForm(forms.ModelForm): class Meta: model=Clientes fields=['titulo','nombre'] forms.py (from the budget app inheriting from forms.py from the customer app) class PresupuestosClientesForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { 'titulo': forms.TextInput( attrs={ 'class': 'form-select' } ), 'nombre': forms.TextInput( attrs={ 'class': 'form-control' } ), } in the presupuestos-form.html template where the options reflected are not seen <label for="titulo" id="titulo">Título</label> {{presupuestosclientesform.titulo}} <select class="form-select"> <option>Elige</option> <option>Mrs.</option> <option>Miss</option> <option>Mr.</option> </select> views.py (app clientes) def create_Clientes(request): form=ClientesForm(request.POST or None) if form.is_valid(): form.save() return redirect('clientes:index') return render(request,'clientes/clientes-form.html',{'form':form}) views.py (app presupuestos) def create_Presupuestos(request): presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) if presupuestosclientesform.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') return render(request,'Presupuestos/presupuestos-forms.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform}) -
django heroku template password_reset_confirm.html does not work
I'm using this build feature of Django. On my local machine everything works just fine. But on heroku the is no actually form on this template. Code of template: <div class="container p-5"> <h2 class="font-weight-bold mt-3">Password Reset Confirm</h2> <hr> <p>Please enter your new password.</p> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Reset password</button> </form> </div> code one developers panel: <div class="container p-5"> <h2 class="font-weight-bold mt-3">Password Reset Confirm</h2> <hr> <p>Please enter your new password.</p> <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="0Vpkz9Uhbp5RjG3op8FnAU77abxRwdf8OtA7r9buOAWnweVueKSRkbbRY6vHh2B6"> <button class="btn btn-primary" type="submit">Reset password</button> </form> </div> -
How to grab data from a rendered Jinja file in a custom filter?
In a website I'm making people can use a custom filter to get the currency that they have set in their account settings. The custom filter would re-render their price with the appropriate currency symbol. <span>{{ product.price | money }}</span> The problem is, I need their store ID to be able to fetch their chosen currency from the DB. Instead of having them pass in their store ID with every filter I wanted to do it all on the backend. I came up with a solution (maybe?) to add JS to the template that would supply that info in an object <script> const shopData = { id: 123123' } </script> My question is can I grab that JS to use in the Django backend without the user supplying a second filter value? -
websocket receiving incomplette data
receiving data from websocket i have notice that fields are missing from the models please help you can see the resualt in postman wil connecting to the django channels consumer.py # Receive message from room group async def chat_message(self, event): method = event['method'] model = event['model'] data = event['data'] description = event['description'] receiver = event['receiver'] sender = event['sender'] created = event['created'] seen = event['seen'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'method': method, 'model': model, 'data': data, 'description': description, 'receiver': receiver, 'sender': sender, 'created': created, 'seen': seen, })) views.py async_to_sync(layer.group_send)(("chat_" + str(channel_name)), { 'type': 'chat_message', 'method': 'POST', 'model': 'social', 'data': json.dumps(serializers.data), 'description': 'new post', 'sender': json.dumps(LikeSerializer(request.user, many=False).data), 'receiver': json.dumps(sorted(my_profile.profile_followers.all().values_list('id', flat=True))), 'created': json.dumps(str(timezone.now())), 'seen': None }) resualt 1 -
ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead
I'm doing my first question on StackOverFlow about something ig going me crazy. My project is an Auction site, and is based on django and Web3 to interact with a smart contract deployed on my Ganache. Now i have got this error on my view : ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead. The problem is: If i register a customer and an address, then i try to receive tokens from the Faucet, If i put customer address i don't receive anything. But if i select another address, i receive token in the first address. I really don't understand why... Thank you very much for your help my Model: class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=256, blank=False, null=False, unique=True, error_messages={'unique': 'This address is already registered'}) tokenBalance = models.FloatField(default=0) dollarBalance = models.FloatField(default=0) my Registration to the site def registrationForm(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] address = form.cleaned_data['address'] user = User.objects.create_user( username=username, password=password, ) newCustomer = Customer( user=user, dollarBalance=random.randrange(500, 1500), address=address, tokenBalance=0 ) user.save() newCustomer.save() user = authenticate(username=username, password=password) login(request, user) messages.success(request, f'''Welcome in DNote {request.user}''') return redirect('homepage') else: form = RegistrationForm() … -
Shop in an iframe
My company has an online shop that is used by third party merchants to sell their goods. Each merchant has their own page, with a list of all their products. Many have asked for a way to embed their page into their own website through an iframe, so I managed to create an embeddable version of their page, and all the code on the server is executed correctly: a new order is created, it's filled with a list of all the purchased products, and then the buyer is sent to our site's basket page. This process is advantageous to us, because in this way we generate traffic towards our shop, and customers can look at other merchants' wares as well, increasing our potential revenue. It also lets me rewrite a lot less code, since I don't have to recreate an embeddable version of every page from purchase to payout. As I said, the order is registered correctly, but when the user lands on the basket page, the basket is always empty. To explain the process a bit more in detail: our shop lets unregistered users put articles in their baskets, but at most during the checkout process they have to … -
Django Rest Framework endpoint is missing 'Access-Control-Allow-Origin' response header
I have a flutter app that makes a call to two different endpoint, one of them responds as expected but the other is blocked by CORS because "No 'Access-Control-Allow-Origin' header is present on the requested resource." Acording to the django rest framework docs i can pass headers as dictionary of HTTP headers to use in the response like this: @api_view(['GET']) @permission_classes((AllowAny,)) def get_new_blog_posts(request): blog_posts = BlogPost.objects.all().order_by('-id')[:5] serializer = BlogPostPreviewSerializer(blog_posts, many=True) return Response(serializer.data, headers={'Access-Control-Allow-Origin':'http://localhost:51626'}) Which should let the front end make the call and get the information, but somehow the response is ignoring the headers. The view that works looks like this: class ApiJobPostsContentView(generics.ListAPIView): queryset = JobPost.objects.all() serializer_class = JobPostCardSerializer authentication_classes = [] permission_classes = [permissions.BasePermission] filter_backends = [SearchFilter, OrderingFilter, DjangoFilterBackend] I have tried making the failing view a generic ListAPIView but it does not matter, the header is still missing. django-cors-headers is installed in the app and my settings.py file haswhat it needs to allow the other views to work the way they should. My setting.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:51626', ) CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ 'accept', … -
Django Real Time actions
How Can I create real time actions in python / django? for more info: Some user add some thing to database also other user add same one too (not same as they are but they have similar property) at same time (and all times) program should being check if they are objects with similar property {if they are not same check both of them in other time with all other objects that may be added/edited on database} these actions should be in real time or at last by few minuts appart. -
Django bootstrap form and button is displaying on browser output extra large
this is my link: <a href="#" class="btn btn-danger">link</a> in the browser it looks too big with djnago but when this link I aplly without django then it's size works well what should i do -
Django not loading static css files
In the process of conntec to a space on digital ocean, I ran python manage.py collectstatic For {% static 'image/image_name.jpg %} works, my images show up, bu for <link rel="stylesheet" type="text/css" href="{% static 'css/fontawesome/css/all.css' %}"> my font awesome isn't showing up. I've checked the location of this link, and I am getting back the correct location, but I don't know what is causing the issue. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'), # https://unlock-optimal-performance.nyc3.digitaloceanspaces.com STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles-cdn") # in production we want cdn MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles-cdn', 'uploads') from .cdn.conf import AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_STORAGE_BUCKET_NAME,AWS_S3_ENDPOINT_URL,AWS_S3_OBJECT_PARAMETERS,AWS_LOCATION,DEFAULT_FILE_STORAGE,STATICFILES_STORAGE urls.py urlpatterns += staticfiles_urlpatterns() Any reason why my images are showing up but not my css ? -
AttributeError at 'WSGIRequest' object has no attribute 'Post'
When i click vote button I got this error AttributeError at /polls/2/vote/ 'WSGIRequest' object has no attribute 'Post'. When i tried to vote for any poll. This is my results.html file I am using django==3.2 and python 3.8 <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} </fieldset> <input type="submit" value="Vote" > </form> -
Django - importing from subordinary folder
I'm making django blog app. And i have problem with import .py file from subordinate directory. Does anyone has any advice maybe what is wrong here? enter image description here -
Redirect back to original post after updateview
I have an update view that is working as expected. The only issue is that I cant figure out how to redirect back to the post that was being updated. I believe I am on the right track with get_success_url but I cant get it working view class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' def get_object(self): return BuildLog.objects.get(pk=self.kwargs["pkz"]) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): pk = self.kwargs["pkz"] return reverse("build-log-view", kwargs={"pkz": pk}) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False urls: path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update'), -
Django model generates hundreds of files in a saving loop
I'm using Django 3.8.2 on Ubuntu 18.04, I'm generating a PDF file upon saving a django model but files are generated in a loop endlessly. I have this django model: class Fattura(models.Model): ordine = models.ForeignKey(Ordine, on_delete=models.CASCADE, related_name="fatture", null=False) pdf = models.FileField(upload_to='archivio/fatture/%Y/%m') the pdf field is generated when an instance is saved, based on the information contained in the related "ordine" field which is a ForeignKey to this other model: class Ordine(models.Model): utente = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ordini", null=False) data = models.DateField(auto_now_add=True) abbonamento = models.ForeignKey(Abbonamento, on_delete=models.PROTECT, null=False) importo = models.DecimalField(max_digits = 5, decimal_places = 2, null=False) I declared every instructions for the generation of the PDF inside the save() method of my Fattura model. I'm using the library that is recommended by Django's documentation: reportlab. Here is the custom save method: def save(self, *args, **kwargs): self.count_save += 1 # I defined this attribute which I increment to understand what is actually looping print("COUNT SAVE: " + str(self.count_save)) # it always grows, that's the save method being re-called if self.pdf._file == None: try: buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100,100, str(self.ordine)) p.showPage() p.save() buffer.seek(0) utente = self.ordine.utente num_questa_fattura = utente.ordini.count() nome_file = "{}_{}-{}.pdf".format( self.ordine.utente.first_name.lower(), self.ordine.utente.last_name.lower(), num_questa_fattura) percorso = '{}/upload/archivio/fatture/{}/{}/{}'.format( BASE_DIR, # from settings.py … -
Django Python Creating Object inside Model delete function returns 500 Error
I am trying to create a new Entry of CloudProfileTransaction before deleting a record. When saving a new record the exact same code works fine ( with: super().save(*args, **kwargs)). If I remove the CloudProfileTransaction code the deletion works. the following code throws a Response 500 Error. what am I missing? def delete(self, *args, **kwargs): CloudProfileTransaction.objects.create( cloud_giver = self.follower, cloud_receiver = self.followee, cloud_model = CloudModel.objects.get(investment='Follow'), add = False ) Followers.objects.filter(user=self.follower).update(followers=F('followers')-1) Followees.objects.filter(user=self.followee).update(followees=F('followees')-1) super().delete(*args, **kwargs) Error Message: E/Volley: [28490] NetworkUtility.shouldRetryException: Unexpected response code 500