Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get value from Django view into Ajax success function
I have a django application where a user can upload a file on form submit. When the file is uploaded the program will get the column names from the csv file and display that in the Django Template This is my views def handle_new_file(request): if (request.method == 'POST'): form = NewFileForm(request.POST, request.FILES) if form.is_valid(): csv_file = request.FILES['csv_file'] fs = FileSystemStorage() file_name = fs.save(csv_file.name, csv_file) file_url = f"./media/file_uploads/{file_name}" print(file_name) print(file_url) cols = get_column_names(file_url) form.save() return HttpResponse(cols) While the above view is called successfully on form submit, I am not able to pass this cols data back to the template. Here is my Ajax code function upload(event) { event.preventDefault(); var data = new FormData($('form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: function (data) { alert(data); } }); return false; } $(function () { $('#new_form').submit(upload); }); What am I doing wrong? -
How to patch (or mock) Django’s ImageField form field’s properties?
I have a model which includes an ImageField (lets call it my_project.models.Profile) and a corresponding form (my_project.forms.ProfileForm). Let us say the name of the model’s field is picture. I am writing tests for the form and need to test the handling of the content_type property of the form's ImageField file underlying object, by my own project. For the life of me, I cannot work out where I would patch this property, to test the different scenarios. What I figured out: django.forms.fields.ImageField has a method to_python which transforms the uploaded binary data into an actual image file (https://github.com/django/django/blob/aec71aaa5b029640ce066fe5dc34f7a0050d50b2/django/forms/fields.py#L621). It uses PIL.Image to do so. Once the image is successfully opened by Pillow, the file object to be returned by to_python is assigned the content_type property, taken out of the PIL.Image.MIME dictionary (https://github.com/django/django/blob/aec71aaa5b029640ce066fe5dc34f7a0050d50b2/django/forms/fields.py#L653). What would be the correct path for mock.patch? -
Printing matplot graph in django?
Views.py:- from django.shortcuts import render, HttpResponse from tweetanalysis import tweety import matplotlib.pyplot as plt import pandas as pd import base64 from io import BytesIO # Create your views here. def index(request): return render(request, 'index-search.html') def result(request): if request.method == 'POST': query = request.POST.get('hashtage') df = tweety.Analyzer(query) plt.figure(figsize=(8, 6)) for i in range(0, df.shape[0]): plt.scatter(df.loc[i, 'Polarity'], df.loc[i, 'Subjectivity'], color='Blue') plt.title('Sentiment Analysis') plt.xlabel('Polarity') plt.ylabel('Subjectivity') buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() ans1 = base64.b64encode(image_png) ans1 = ans1.decode('utf-8') buffer.close() plt.title('Sentiment Analysis') plt.xlabel('Polarity') plt.ylabel('Subjectivity') df['Analysis'].value_counts().plot(kind='bar') buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() ans2 = base64.b64encode(image_png) ans2 = ans2.decode('utf-8') buffer.close() return render(request, 'result.html', {'chart': ans1, 'plot': ans2}) else: return HttpResponse("Error!") result.html:- {% extends 'base.html' %} {% block content %} {% if chart %} <img src="data:image/png;base64, {{chart|safe}}" /> {% endif %} <br /> {% if plot %} <img src="data:image/png;base64, {{plot|safe}}" /> {% endif %} {% endblock %} here df in dataframe. I am making a tweet sentiment analysis web app For that I want to print my matplot graphs in frontend as a result in django but error arises name 'posts' is not defined. Here in my code my sentiment analysis code return dataframe contains tweets polarity subjectivity. I want to show … -
Django looping through items not showing
Hi I am looping through items being passed through the context but nothing is showing. This is what I am passing: {"error":[],"result":{"USDT":"60000.00000000","CHZ":"13773.0349000000","ZRX":"0.0000000000","ZUSD":"67787.8285","DOT":"0.0000000000","COMP":"0.0000034600","ENJ":"257.6815000000","ADA":"2473.80445621","XXDG":"17006.92601155","ALGO":"32063.69514500","XXBT":"0.0000012880","SUSHI":"172.4585500000","SOL":"1133.3543869800","DASH":"0.5104491200","LINK":"144.2407000000","ATOM":"151.26763831","XXLM":"6926.27220000","XXRP":"0.00000000","XETH":"14.5877343640","TRX":"923.80015900","KNC":"0.0000000000","BAL":"0.0000000000","XLTC":"11.4923900000","KSM":"24.7142610000","SC":"0.0000000200","OCEAN":"652.6077000000","MATIC":"1838.9295772000","AAVE":"83.6218990800","ZGBP":"30622.0790","XZEC":"0.0000073100"}} And inside my template I have this: {% for k, v in api_reply.items %} <tr> <td>{{ k }}</td> <td>{{ v }}</td> </tr> {% endfor %} I have no errors showing but it is not displaying, any help would be great thank you. -
Django- Duplicated queries in nested models querying with ManyToManyField
How do I get rid of the duplicated queries as in the screenshot? I have two models as following, class Genre(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') def __str__(self): return self.name class Game(models.Model): name = models.CharField(max_length=50) genre = models.ManyToManyField(Genre, blank=True, related_name='games') def __str__(self): return self.name and have a serializer and views, class GameSerializer(serializers.ModelSerializer): class Meta: model = Game exclude = ['genre', ] class GenreGameSerializer(serializers.ModelSerializer): children = RecursiveField(many=True) games = GameSerializer(many=True,) class Meta: model = Genre fields = ['id', 'name', 'children', 'games'] class GamesByGenreAPI(APIView): queryset = Genre.objects.root_nodes() serializer_class = GenreGameSerializer def get(self, request, *args, **kwargs): ser = GenreGameSerializer(data=Genre.objects.root_nodes() .prefetch_related('children__children', 'games'), many=True) if ser.is_valid(): pass return Response(ser.data) so basically the model populated when serialized looks like this The result is what I am expecting but there are n duplicated queries for each of the genre. How can I fix it? Thanks.. here is a paste https://pastebin.com/xfRdBaF4 with all code, if you want to reproduce the issue. -
How to display video and image in same Carousel Slider based on what user have uploaded- Django
I'm trying to build a Instagram Clone using Django. If user uploads video and image for a single post and then I want to display both image and video in single Carousel slider. Do you guys have any idea. How to implement such functionality. Models.py User = get_user_model() class Post(models.Model): user = models.ForeignKey(User, models.CASCADE) caption = models.CharField(max_length=50) post_id = models.CharField(max_length=10) post_media = models.FileField(blank=True) # post_images = models.ManyToManyField('PostFiles', null=True, blank=True) timestamp = models.DateTimeField() # Will be de-activated if found suspicious is_active = models.BooleanField(default=True) likes = models.ManyToManyField(User, related_name='post_likes') comments = models.ManyToManyField('comment', related_name='post_comments') def __str__(self): return self.user.username def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): if not self.post_id: self.post_id = ''.join(random.choices( string.ascii_uppercase + string.digits, k=8)) return super().save(*args, **kwargs) class PostFiles(models.Model): post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE) post_media = models.FileField(upload_to='post_media/') def __str__(self): return self.post.caption -
Why does it show TypeError: UpdateContent() got an unexpected keyword argument 'instance'?
Working on a simple project in Django 3.2 and trying to add an edit button, to edit the content of the page. To do that I did: views.py def UpdateContent(request, pk): contents = todo.objects.get(id=pk) form = UpdateContent(instance=contents) if request.method == 'POST': form = UpdateContent(request.POST, instance=contents) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'html/update.html', context) forms.py class UpdateContent(ModelForm): class Meta: model = todo fields = ['content'] home.html <table class="table table-dark table-hover table-bordered"> <thead> <tr id="tr-table"> <th id="text-left">#</th> <th id="text-center">ITEMS</th> <th id="text-right"><i class="material-icons">&#xe872;</i></th> </tr> </thead> <tbody> {% for all_item in all_items%} <tr> <th id="row" scope="row"> {{ forloop.counter }} </th> <td id="content">{{ all_item.content }}</td> <form action="delete_todo/{{all_item.id}}/" method="post"> {% csrf_token %} <td class="text-right-delete"> <button id="btn-delete" class="btn btn-outline-danger">Delete</button> </td> </form> <td><a class="btn btn-outline-info" href="{% url 'todo:update' all_item.id %}">Edit</a></td> </tr> {% endfor %} </tbody> </table> update.html {% extends 'html/main.html' %} {% load static %} {% block content %} <form action="", method="POST"> {% csrf_token %} {{form}} <input type="submit" name="Submit"> </form> {% endblock %} But when I run the code it shows me this error TypeError: UpdateContent() got an unexpected keyword argument 'instance' Would appreciate any response or suggestion. Thanks! -
How do I handle foreign key relationship in the urlpattern in the django-rest-framwork
In my models.py I have the following classes: class Project(models.Model): name = models.CharField(max_length=100) class ProjectMaterial(models.Model): project = models.ForeignKey("Project", on_delete=models.CASCADE) material = models.CharField(max_length=150) units = models.IntegerField() My serializers are like this: class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = "__all__" class ProjectMaterialSerializer(serializers.ModelSerializer): class Meta: model = ProjectMaterial fields = "__all__" My current views.py looks like this: class ProjectList(generics.ListCreateAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer class ProjectMaterialList(generics.ListCreateAPIView): queryset = ProjectMaterial.objects.all() serializer_class = ProjectMaterialSerializer How should I create my urlpatterns to make a PUT request to change the units value for a project with an id=1 for a material with an id=3? -
Django how do we send a model into javascript and render it onto a template
I'm trying to pass a Django model into a template using javascript. I can't seem to filter or do anything with the QuerySet once I get the javascript to read it and pass it on to the template. My html file: <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat}}"; var lastEntry = "{{last}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry; } </script> The result I get after 2 seconds: 2 seconds <QuerySet [<ChatStream: ChatStream object (31)>, <ChatStream: ChatStream object (32)>]>lastEntryChatStream object (31) Instead of showing "<QuerySet [<ChatStream: ChatStream object (31)>....] " How do I show the text inside the model named ChatStream?... I've tried: <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat.user}}"; var lastEntry = "{{last.user}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + "lastEntry" + lastEntry; } </script> But the above displays nothing. I've also tried <p id="demo2">I will display when two seconds have passed.</p> <script> var data = "{{chat | last }}"; var lastEntry = "{{last}}" } setTimeout(myTimeout1, 2000) function myTimeout2() { document.getElementById("demo2").innerHTML = "2 seconds " + data + … -
File upload Django form is not valid
I have a Django Model as follows class NewFile(models.Model): name = models.CharField(max_length=200) phone = models.CharField(max_length=200) address = models.CharField(max_length=1000) csv_file = models.FileField(upload_to ='retailer_uploads/') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name And a Django form as follows class NewFileForm(forms.ModelForm): class Meta: model = NewFile fields = ('name', 'phone', 'address', 'csv_file') This is my Django views def handle_new_file(request): if (request.method == 'POST'): form = NewFileForm(request.POST, request.FILES) if form.is_valid(): form.save() csv_file = request.FILES['csv_file'] fs = FileSystemStorage() csv_file_name = fs.save(csv_file.name, csv_file) csv_file_url = fs.url(csv_file_name) return redirect('home') And lastly my template <form action="{% url 'handle_new_file' %}" method='post' enctype="multipart/form-data" id='new_form'> {% csrf_token %} <div class="row"> <div class="col-md-6"> {{ new_file_form.name|as_crispy_field }} </div> <div class="col-md-6"> {{ new_file_form.phone|as_crispy_field }} </div> </div> {{ new_file_form.address|as_crispy_field }} {{ new_file_form.ean_mapping|as_crispy_field }} {{ new_file_form.retailer_file|as_crispy_field }} <div class="d-grid gap-2"> <button class="btn btn-primary" type="submit">Submit</button> </div> </form> Firstly the issue I am facing is that, for some reason this form is not valid as it is not getting saved. Not sure why. But what I want to do is after the form is saved, I want to open the csv file from the media folder and get the column names from the file. I have the helper function to that. The problem is I am … -
How does Django find template?
Below is my urls.py in mysite/mysite/settings.py urlpatterns = [ path('', TemplateView.as_view(template_name='homepage/main.html')), path('admin/', admin.site.urls), # add something path('polls/', include('polls.urls')), path('hello/', include('hello.urls')), path('accounts/', include('django.contrib.auth.urls')), # Add, Search how does djnago find template. path('autos/', include('autos.urls')), ] If some user request www.mysite.com/accounts/login This request go to 'django.contrib.auth.urls' in there request go to path('login/', views.LoginView.as_view(), name='login') not in django/contrib/auth/urls.py.. But my login template is in mysite/homepage/templates/registration/login.html And below is my login.html {% extends "base_bootstrap.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} {{ form.as_p }} <input type="submit" class="btn btn-primary" value="Login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} It works well. so I don't know how Django find my login.html How does Django find my login.html? -
How to load bootstrap styles in Django
ingestion-dashboard/ ├── apps │ ├── adapter │ ├── authentication | |__init__.py │ ├── static │ │ ├── assets │ │ │-- css │ │ │── img │ │ │── scss │ │ │── vendor │ └── templates │ ├── accounts │ ├── home │ ├── dashboard │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── manage.py ├── requirements.txt └───staticfiles ├── assets │── css │── img │── scss │── vendor settings.py CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # ingestion-dashboard STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CORE_DIR, 'apps/static'), ) With this layout, django works fine with local server with proper loading of bootstraps and styles. But when i ran this on kubernetes/nginx , the app is working fine but missing bootstraps, styles. The staticfiles dir in ingestion-dashboard/dashboard/staticfiles is being populated by command django-admin manage.py collectstatic. Any help is appreciated. I have loaded styles as <script src="/static/assets/vendor/@popperjs/core/dist/umd/popper.min.js"></script> works fine with local development. -
i want a validation in my Django model that question field would not accept an integer i try but it's not working..How can i do that?
Here this is my Code #models.py from django.db import models class Question(models.Model): question = models.CharField(max_length=200, null= True) option1 = models.CharField(max_length= 200, null= True) option2 = models.CharField(max_length= 200, null= True) option3 = models.CharField(max_length= 200, null= True) option4 = models.CharField(max_length= 200, null= True) answer = models.CharField(max_length=200, null=True) def __str__(self): return self.question #views.py from django.shortcuts import render,redirect from .models import * from .forms import QuestionForm from django.views import View from django.urls import reverse class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid(): forms.save() print("i was in If ") return redirect(reverse('home')) else: print("i was in else ") context = {'forms': forms} return render(request, 'file/addQuestion.html', context) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) -
How to create a cluster of links, then feed it to scrapy to crawl data from the link based on a depth and crawling strategy set by user from browser
We need help doing this project for our junior year software engineering project. So, our web app is supposed to: Login/Register/Authenticate via google : (we have completed this using Django Allauth.) Then, users will be able to create a cluster of links in a new cluster creating page, there the users will be able to provide information about the clusters. They will provide: cluster name, links to crawl data from, set a depth for each link they provide. (By depth I mean, following the links and webpages associated with the website) Finally, the users will be able to provide a crawling strategy to what to crawl, for this instance(we do not want to crawl any non textual data) : non HTML text data, pdf, doc files. Then, we need to crawl the data and store it in a database or a service (We intend to use Apache Lucene here). So, the data is searchable for the end user from a cluster that they had created. For now, how can we implement all of the things mentioned in point 2? Can someone please help by debunking this step by step on exactly what we need to do? We are a bit … -
Django SECRET_KET on VPS
I'm working on a Djnago app that needs to be uploaded on a VPS. I already have moved my SECRET_KET from settings.py and placed it inside .env file that I created and addedthis .env file to .gitignore. When I'm uploading the project to my VPS, Django isn't able to locate my SECRET_KEY because obviously the .env file is not found inside my project directory on the VPS. What should I do in this case and how am I supposed to call the SECRET_KEY on the server? -
How to reset password in Django by sending recovery codes instead of sending link
Can anybody explain how to use the recovery codes to reset the password using recovery codes instead of recovery links like of Facebook ,Gmail etc. I'd like to reduce the pages user have to open. Here're what I want: instead the reset link, send to user the key only -
Nasa Insights Api
I am trying to make a weather app using Nasa insights Api. But when i am workig with api's first key i.e., "sol_keys" which is a list of sol's, But when i am printing this sol_keys list, I am gettting an empty list. Now, what to do, and how to use this api. Url = "https://api.nasa.gov/insight_weather/?api_key="+mars_api_key+"&feedtype=json&ver=1.0" mars_weather = requests.get(Url) mars_weather = mars_weather.json() Present_sol = mars_weather['sol_keys'] print(Present_sol) I am getting "[]" this as an output. But what I am expecting is the seven sol string like -> ["256","257","258","259","300","301","302"] -
How to include a CSRF token inside a hardcoded form post
I have the following AJAX datatable: $('#ittFileUploadTable').DataTable( { responsive: true, autowidth: false, destroy: true, deferRender: true, ajax: { url: '/project_page_ajax/', type: 'GET', data: {}, dataSrc: "" }, columns: [ {"data": "fields.filename"}, {"data": "fields.uploaded"}, {"data": "fields.updated"}, {"data": "fields.user"}, {"data": "pk"}, ], columnDefs: [ { className: 'text-center', targets: [1] }, { targets: [0], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<a href="/media/'+data+'" target="_blank">'+data+'</a>'; return buttons; } }, { targets: [-1], class: 'text-center', orderable: false, render: function (data, type, row) { var buttons = '<form method="post" action="delete_file/'+data+'/"><button type="submit" class="btn btn-danger"><svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" fill="white" class="bi bi-trash-fill" viewBox="0 0 16 16"><path d="M2.5 1a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1H3v9a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V4h.5a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1H10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1H2.5zm3 4a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 .5-.5zM8 5a.5.5 0 0 1 .5.5v7a.5.5 0 0 1-1 0v-7A.5.5 0 0 1 8 5zm3 .5v7a.5.5 0 0 1-1 0v-7a.5.5 0 0 1 1 0z"/></svg></button></form>'; return buttons; } }, ], order: [ [0, 'asc'] ], "pagingType": "numbers", dom: 'rt' }); The function in … -
Validation error in Django 'POST' request
I'm a beginner with Django Rest Framework I've created a model and serializer for it. There it goes: models.py class Car(models.Model): make = models.CharField(max_length=15) model = models.CharField(max_length=15) def __str__(self): return self.make class CarRate(models.Model): rate = models.ForeignKey(Car, related_name='rates', on_delete=models.CASCADE) serializers.py class CarRateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = CarRate fields = ('rate') class CarSerializer(serializers.HyperlinkedModelSerializer): rates = CarRateSerializer(many=True) '''rates = serializers.PrimaryKeyRelatedField( many=True, read_only=False, queryset=CarRate.objects.all() )''' def create(self, validated_data): rates_data = validated_data.pop("rates") car = Car.objects.create(**validated_data) for rate_data in rates_data: CarRate.objects.create(car=car, **rate_data) return car class Meta: model = Car fields = ('id', 'make', 'model', 'rates') What I want to do is to add a rate for a Car with a specific ID with a POST method and JSON, but when I do it multiple times it stores all the rates for that one object. I will add a rate like that: { "id":2, "rate":4 } So here is my POST method, but it gives a response Car id not found so it doesn't pass validation. views.py @api_view(['POST']) def car_rate(request): if request.method == 'POST': rate_data = JSONParser().parse(request) rate_serializer = CarSerializer(data=rate_data) if rate_serializer.is_valid(): ''' Code that checks if a rate is from 1 to 5 ''' return JsonResponse({'message': 'Car id not found!'}) So what I think might be … -
how to save parent , child and grand child forms in one submit - django
i'm building an application for a mobile trading company , the is the scenario : every invoice has an unique invoice number and every unique date has several phone models and every phone models have a number of IMEI here is how i designed the database model class Collection(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) company = models.ForeignKey(Company,on_delete=models.PROTECT) invoice_no = models.IntegerField(unique=True) collection_date = models.DateTimeField(default=timezone.now) class MobileCollection(models.Model): collection = models.ForeignKey(Collection,on_delete=models.PROTECT,related_name='collections') mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) i have to submit all of them in one go ! i'm not sure how to build its view , while the MobileCollection model should increase dynamically , and with the qnt field in MobileCollection the Imei forms should increase , for example if the qnt=10 we should add 10 Imei forms , i thought about inlineformset_factory but i its not work in my case . please is there a better approach to achieve that ? thank you in advance -
How can I build share option like facebook or youtube using Django?
I am building a social website using Django. I want to implement the share function for users to data between other users. Can someone give me brief idea about that? How can I do this or How to implement the code. -
Override helptext in Wagtail EditView
I am trying to override the helptext that is set in my model in the wagtail admin (an edit view). I have tried the code below but the text is not changed, why is that? class MemberRegistrationEditView(EditView): def get_form(self): form = super().get_form() form.base_fields.get("own_email").help_text = "Test" return form -
Executing a function right before\after revoking a task in celery
For the demonstration, I have a class that does something like this: class Writer: def __init__(self, num): self.num = num def write(self): for i in range(0, num): with open("/outfile", "w") as o: o.write(i) def cleanup(self): # should be executed when write has not finished os.system('rm -rf /outfile') Im using a shared task in celery to execute it like: @shared_task def mytask(): w = Writer(100) w.write() return "Done" Im using django and DRF, and i have an endpoint api that recieves a task_id and revokes the task using revoke(task_id, terminate=True) My goal is to run the cleanup function from the Writer class when the revoke happens. The reason I cannot just run cleanup after the revoke as a regular function is because it needs to access the attributes of its class (in the real senario and not this example), and each class might have a different cleanup function. how can i detect the revoke in mytask() ? Is there a solution using something like try except? Moving the task to a class based task? Have not found anything online or in the docs. Thanks in advance. -
Django-Rest-Framework can't override serializer unique error_messages
I have the following model: class PersonDiscount(models.Model): user = models.OneToOneField('backend.Customer', related_name='discount', on_delete=models.CASCADE, error_messages={ 'unique': _('A discount setting is already set up for this customer.')}) discount = models.IntegerField(default=0) discount_auto = models.IntegerField(default=0) auto = models.BooleanField(default=True) class Meta: ordering = ['-id'] And a following serializer for the model: class PersonDiscountPostSerializer(serializers.ModelSerializer): class Meta: model = PersonDiscount fields = '__all__' extra_kwargs = { 'user': { 'error_messages': { 'unique': _('A discount setting is already set up for this customer.') } } } When i tried to create a PersonDiscount instance with existed user from the api i'm not getting the custom error message which i set in both model and serializer. { "user": [ "This field must be unique." ] } I had already looked up in the docs and can't find any other way to understand why the override error_messages not getting applied. I also restarted the django runserver several times already Hope someone can help me with this problem -
Django : FOREIGN KEY constraint failed on delete, but I don't have any Foreign Key on my model
Here is my model which objects I can't delete : class Broker(models.Model): code = models.CharField(default="", max_length=100, blank=True) name = models.CharField(default="", max_length=100, blank=True) email = models.CharField(default="", max_length=100, blank=True) city = models.CharField(default="", max_length=100, blank=True) address = models.CharField(default="", max_length=100, blank=True) postal_code = models.CharField(default="", max_length=100, blank=True) brokerage = models.FloatField(default=0.00) class Meta: verbose_name = 'Broker' verbose_name_plural = 'Brokers' ordering = ['name'] def __str__(self): return str(self.name) Here is what creates my error (he occurs on the line where I make rem.delete()): if request.POST.get('action') == 'remove_element_selected': element_selected = request.POST.getlist('element_selected[]') for element_id in element_selected: rem = Broker.objects.get(id=element_id) rem.delete() return JsonResponse({}) And here is my error : Internal Server Error: /brokers/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/lucas/Desktop/myapp/app/views/views.py", line 636, in brokers rem.delete() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/base.py", line 880, in delete return …