Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I filter out errors on sentry to avoid consuming my quota?
I'm using Sentry to log my errors, but there are errors I'm not able to fix (or could not be fixed by me) like OSError (write error) Or error that come from RQ (each time I deploy my app) Or client errors (which are client.errors) I can't just ignore them because I consume all my quota. How I can filter out this errors? Here some references for interested people. uwsgi: OSError: write error during GET request Fixing broken pipe error in uWSGI with Python https://github.com/unbit/uwsgi/issues/1623 -
Return foreign key model from other model (not model instance)
I have model like this: class B(models.Model): value = models.CharField(etc...) class A(models.Model): name = models.Charfield( fk = models.ForeignKey(B, etc...) I have no instance of A in my database, but I have few instances of B. What I want to do is to get all instances of B through A model (not instance, since I have none) in Django template. I was thinking, since model is an object, maybe we can pass it like we pass any other object and use it's attributes in some way. Example In views.py: def my_view(request): B.objects.create(value=1) B.objects.create(value=2) B.objects.create(value=3) return render(request, 'template.html', {'model_a': A} In template.html: ... {% for b in a.fk_set.all %} {{ b }} {% endfor %} ... renders as 1 2 3 I understand that's wrong, because there is no A instance and db don't know that B is related to A in any way. Question: Is there a way to get similar effect like I mentioned in the example? -
Matplotlib package not working in django application
I have matplotlib install in docker.But not working in matplotlib.pyplot is not working in django app -
css and other static files not working in django
The current project I've started working on, uses django 2.2 and most of the links are hardcoded. All static content is in folder named media and used in base.html as follows in base.html {% load staticfiles %} ---- using this as first line of base.html ....... ....... <head> <link href="/media/css/backoffice/font-awesome.min.css" rel="stylesheet" type="text/css"> </head> in settings.py STATIC_URL = '/media/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'media'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'media/') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) I've also added following to the main urls.py file: from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Yet I'm not able to render the static file listed in the head section of base.html I've also experimented with commenting out static root and staticfiles_dir but it does not work -
Need help! I have followed the official tutorial of Django to make a poll app, but I couldn't go on
I have followed the tutorial to make the app, but after I changed the code from def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) to def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now (The code is at mysite\polls\models.py and the required changing action is on part 5 of the tutorial), I ran the py manage.py test polls, and then I got the error: the error feedback, and I also couldn't run the webserver. Could you please help me? The platform: Windows 10 Django version: 3.0.4 Python version: 3.8.2 The database is MySQL8.0 and the tutorial:tutorial my code files:enter link description here -
Django insert record
I am selecting a mark for every student and every core value then sending all data back to the database my main problem here is , i didnt get the right mark for every student and core value this is my html <form method="post" id="DogForm" action="/studentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="hidden" value="{{teacher}}" name="teacher"> <tr> <td rowspan="2" colspan="2">Core Values</td> {% for core in corevalues %} <td colspan="8"><input type="hidden" value="{{core.id}}" name="core">{{core.Description}}</td> {% endfor %} </tr> <tr> {% for corevalues in corevaluesperiod %} <td colspan="4" style="font-size: 12px"><input type="hidden" value="{{corevalues.id}}" name="coredescription">{{corevalues.Description}}</td> {% endfor %} </tr> <tr> <td colspan="2">Student's Name</td> {% for corevalues in period %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="coreperiod">Q {{corevalues.id}} </td> {% endfor %} </tr> {% for students in student %} <tr> <td colspan="2" class="names"><input type="hidden" value="{{students.id}}" name="student">{{students.Students_Enrollment_Records.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td colspan="4"> <select name="marking"> <option>--------</option> {% for m in marking %} <option value="{{m.id}}" >{{m.Marking}}</option> {% endfor %} </select> </td> <td colspan="4"> … -
Can I run scripts at the click of a button in Django?
I want to run a script with a button click in Django. If you have any reference, please share it. -
In graphene-django, How can I use middleware to specific resolver
I want to set cookie by a resolver input value like: @decorator_from_middleware_with_args(TestMiddleare) def resolve_is_user_canary(self, info, user_token): return True Unfortunately, I can't get_response without middleware, what should I do to set a cookie without a global middleware? -
how to fill histroy chage reason in django simple history?
class ModelA(models.Model): name = models.CharField("Name", max_length=128) history = HistoricalRecords( history_change_reason_field=models.TextField(null=True)) I made a serializer : class ModelAHistorySerializer(serializers.Serializer): name = serializers.CharField() history_change_reason = serializers.CharField() history_date = serializers.DateTimeField() history_user = serializers.CharField() history_type = serializers.CharField() views : @action(methods=["GET"], detail=True) def history(self, request, *args, **kwargs): a = self.get_object() result = ModelA(a.history.all(), many=True).data return Response(data=result) this works at the point as it provides me name , history_user and history date but null value in change reason and type. Result: [ { "name": "john", "history_change_reason": null, "history_date": "2020-03-06T06:48:36.065985Z", "history_user": "admin", "history_type": "~" }, how to fill up override the change reason and type field??? -
vscode don't close all django(python) processes when I click stop button
VSCode Version: 1.42.1 OS Version: Ubuntu 18.04 Steps to Reproduce: Press Ctrl + F5 to run the django process. Click "stop" button to stop all django process. But there is still a process that has not been closed. -
How to send the image to API from modal window in Django?
I'm using Fengyuan Chen Image Cropper in Django. Here you can see more about it After cropping the Image, I want to send the image to API and get the response in JSON. This is how my views.py file looks like.. import json import urllib.request from .models import Photo from .forms import PhotoForm def photo_list(request): photos = Photo.objects.all() if request.method == 'POST': form = PhotoForm(request.POST, request.FILES) if form.is_valid(): if form.save(): data = get_json("http://127.0.0.1:5000/") return render(request, 'album/photo_list.html', {'form': form, 'photos': photos, 'data': data}) else: form = PhotoForm() return render(request, 'album/photo_list.html', {'form': form, 'photos': photos}) def get_json(url): html = urllib.request.urlopen(url) raw_json = html.read().decode('utf-8') forex_json = json.loads(raw_json) return forex_json And here is how my photo_list.html form code looks like.. <form method="post" enctype="multipart/form-data" id="formUpload" name="file"> {% csrf_token %} {{ form }} </form> Where "file" is the name of the key. I'm facing an issue where sending file using this form. ERROR :: raise exceptions.BadRequestKeyError(key) werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'file' May be it's because it can't perform two tasks simultaneously. I'm new to Django. Any help will be really appreciable. Thanks -
csrf_exempt Decorator does not work in Dajngo function based views
I am using React with Django, most of the client server interaction is being done through the API using Django Rest Framework. I created a standard app called mail, it has a standard view which accepts a POST request with csrf_exempt and login_required decorators on it. However whenever making an ajax call through Axios it always gives me a 400 Invalid CSRF Token error - CSRF Cookie not specified. views.py from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt @login_required @csrf_exempt def testmail(request): if request.method=="POST": EmailQueue.objects.create(subject='TEST EMAIL BROTHER', body=render_to_string('nordalmail/testmail.html'), to_email=request.user.email, from_email=settings.FROM_EMAIL, send_now=True) return HttpResponse("CHECK ADMIN") if request.method == "GET": return render(request, "nordalmail/test-mail.html") React Component import axios from 'axios'; import {createMessage, returnErrors} from './messages.js'; import {tokenConfig} from './auth.js'; // Tokenconfig simply gets the Authorization Token and sends it as a Header value export const sendTestMail = () => (loggedUserEmail, getState) => { axios .post('http://alice:55403/nordalmail/', tokenConfig(getState)) .then(res => { createMessage("A test email has been sent to your registered email address!", "Email Sent"); }) .catch(err => { returnErrors("Something went wrong while sending your email, website administrator has been notified of this incidence!", "Error"); }); } Here's the Request I send Request URL: http://alice:55403/nordalmail/ Request Method: POST Status Code: 403 Forbidden Remote Address: 127.0.0.1:55403 Referrer … -
How to serve image from bucket in gcloud to opencv detect face method in view?
i have two methods one which sends the path of the newly uploaded image file by user from frontend to the other method which reads the image path by pre-appending the my storage path to detect the face from it. But in my case the cv.imread function is not considering the path to be an image but actually it is image path only because when i get the image when i directly write the path on browser url. OPEN CV IMAGE READ AND FACE DETECT def detect_im(request, pathname): rootpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) haar_file = rootpath + '\\face_detector\\haarcascade_frontalface_default.xml' datasets = 'datasets\\' myid = random.randint(1111, 9999) path = f"https://storage.googleapis.com/agevent269406.appspot.com/srv/face_detector/static/face_detector/datasets/{str(myid)}" face_cascade = cv2.CascadeClassifier(haar_file) newpath = f"https://storage.googleapis.com/agevent-269406.appspot.com/{str(pathname)}" //JOINING THE OBTAINED PATH WITH MY BUCKET PATH count = 1 while count < 30: im = cv2.imread(newpath, 1) gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) ... GET UPLOADED IMAGE PATH FROM USER AND SEND TO ABOVE METHOD def add_image(request): form = PicUpForm() if request.method == "POST": form = PicUpForm(data=request.POST, files=request.FILES) if form.is_valid(): picup = form.save() pathname = picup.picture item = detect_im(request, pathname) #SENDING THE IMAGE PATH FROM HERE TO ABOVE METHOD return item else: return render(request, "add_dataset.html", {"picform": form}) BUT I AM GETTING THIS ERROR Exception Type: error Exception Value: … -
Django Rest Auth: Customer Register Serializer not saving extra fields
NOT A DUPLICATE I am building a simple Todo app with Django & ReactJs, and i have ran into a problem with django-rest-auth. the problem is that my custom UserRegisterSerializer only saves a fragment of the request.dataand ignore the rest. and i have no idea why. Here's my code: User Model: class User(AbstractUser): id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False, db_index=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) email = models.EmailField(max_length=247, blank=False, unique=True, error_messages={ 'unique': _('A user with this email already exists.'), 'invalid': _('Invalid e-mail address detected.'), 'blank': _('this field may not be blank.') }) phone = models.CharField(max_length=20, blank=True, null=True, unique=True, error_messages={ 'unique': _('A user with this phone number already exists.'), }) gender = models.CharField(max_length=5, choices=GENDERS, default=NOOP) birthday = models.DateField(blank=True, null=True) @property def user_id(self): return self.id RegisterSerializer(Custom): class UserRegisterSerializer(RegisterSerializer): first_name = serializers.CharField( write_only=True, required=True, max_length=100) last_name = serializers.CharField( write_only=True, required=True, max_length=100) birthday = serializers.DateField(required=True, write_only=True) phone = serializers.CharField(max_length=20, write_only=True, validators=[ UniqueValidator( User.objects.all(), message=_('A user with this phone number already exists.') ) ]) gender = serializers.ChoiceField( write_only=True, choices=[ ('NO-OP', 'Rather not tell'), ('M', 'Male'), ('F', 'Female'), ], default='NO-OP' ) def get_cleaned_data(self): cleaned_data = super().get_cleaned_data() cleaned_data['first_name'] = self.validated_data.get('first_name', '') cleaned_data['last_name'] = self.validated_data.get('last_name', '') cleaned_data['phone'] = self.validated_data.get('phone', '') cleaned_data['birthday'] = self.validated_data.get('birthday', '') cleaned_data['gender'] … -
How to allow django view in nginx with PWA at /
I'm trying to setting up nginx to my PWA app with django backend. My django backend has some views to pdf reports on /export route. My PWA app (Vue) runs on /. I'm getting a blank page when access to /export. The blank page is trying to response from PWA, but when I reload with Shift (⇧) it loads the pdf report. Here is my nginx server config: server { server_name awesome.app; root /home/awesomeapp/pwa; location /api/ { include proxy_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/awesomeapp/awesome-backend/awesome.sock; } location /export/ { include proxy_params; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/awesomeapp/awesome-backend/awesome.sock; } location / { index index.html; } } Any idea how to setting up nginx to allow the access to the pdf report generated by django? Secondly, django backend also has a dashboard app (no pwa) but nginx does not allows to access it (only with shift(⇧)). -
Data from react axios post is not sending data to django
I am trying to send post data from react to django, however, the data is not attached to the post object. My react code looks something like this: class Homepage extends React.Component { createProject() { axios({ url: "localhost:8000/createProject/, headers: { "Content-Type": "application/json" }, data: { name: "projectname" }, }) } render() { return <div onClick={this.createProject}></div> } urls.py urlpatterns = [ path( "createProject/", views.createProject ), ] views.py def createProject( requests ): print( requests.POST ) return JsonResponse({"this returns": "just fine"}) output from print( requests.POST ) in views.py: <QueryDict: {}> If it matters, I'm using csrf_exempt on my django functions as there are no plans of deploying. Thanks! -
delendent dropdown in django(DJango,Python)
I want to make four drop down button(like country state city and location)each field we want to make it based on the selection like when country select its state related to country we get and when state is s selected then city related to these state gets populated when city get slelected then its loctation related to these city we get -
please give me advice with django admin
I'm new with python and Django. I know a lot about the Codeigniter framework and there if you want to create a project like an eCommerce you must create an admin panel with template and function for the backend. when I was creating backend I was adding functions for the admin panel where all functions were for adding some informations in the database. so when I start with Django I saw that there was an integrated admin panel which can be modified but I have a question can I create app for Django which will be admin panel of my project -
How do I make a user-specific database in Django?
so what I'm trying to do is make a user-specific dataset and show the data only to the user. You can think of social media. The layout is all the same, but what is shows is very much personalized to the user. I'm trying to do this with Django and PostgreSQL, but I have no idea on how to do this. Btw I'm a beginner, I've only took a few Django classes. So if there is any further knowledge that I have to learn, please let me know. I would very much appreciate your help or advice. :) -
ManagementForm data is missing or has been tampered with' while using Nested Django Formsets
I have been trying to use django forms in nested way. I have succesfully made the forms.py and models.py for the purpose but I have been struggling to Implement its html java script part. Now while saving the form I am getting an error "ManagementForm data is missing or has been tampered with'". I am not able to figure whether its views.py bug or my html/java script. I am a starter in django. Kindly help me to debug my code. models.py ``` from django.db import models # Create your models here. from django.contrib.contenttypes.models import ContentType # Create your models here. class courses(models.Model): name = models.CharField(max_length = 50) enter code here class topics(models.Model): name = models.CharField(max_length = 50) course = models.ForeignKey(courses,on_delete = models.CASCADE,null = True) class sub_topics(models.Model): name = models.CharField(max_length = 50) topic = models.ForeignKey(topics,on_delete = models.CASCADE,null = True) class course_to_topics(models.Model): serial_no = models.IntegerField() course = models.ForeignKey(courses ,related_name="course", on_delete = models.CASCADE,null = True) topic = models.ForeignKey(topics ,related_name="topics", on_delete = models.CASCADE,null = True) class topics_to_subtopics(models.Model): serial_no = models.IntegerField() topic = models.ForeignKey(topics ,related_name="topic", on_delete = models.CASCADE,null = True) subtopic = models.ForeignKey(sub_topics ,related_name="subtopics", on_delete = models.CASCADE,null = True) forms.py from django.forms import ModelForm from django.forms import formset_factory, inlineformset_factory,modelformset_factory from .models import courses, topics, sub_topics, … -
Clear the cache for django rest framework
I set the cache with this @method_decorator class IssueViewSet(viewsets.ModelViewSet): queryset = Issue.objects.all() serializer_class = IssueSerializer @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) def list(self,request,*args,**kwargs): api/issue returns the cached objects correctly, But now I want to off the cache sometimes. I notices just api/issue?something off the cache though, I want to off the cache for api/issue. Is there any way to solve this?? -
Jinja2 set block not recognized in Django
I searched for 2 days before posting this, so I really hope its not a duplicate question. I am building my first Django site and after getting into it I realized I'd rather have the power of jinja2. I installed jinja2 to my virtual environment and made the necessary changes to django (see below). However, django appears to be rendering the template with the standard django template engine instead of jinja2. All of my code works as expected when using {% block content %} template content {% endblock content %} Instead of block, I am trying to use {% set %} template content {% endset %} so that I can duplicate a template in base.html. but I get this error: django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 7: 'set'. Did you forget to register or load this tag? [05/Mar/2020 22:27:37] "GET /bge/ HTTP/1.1" 500 161659 I made the following changes to my project to try and make jinja2 work: Settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2' , 'DIRS': [os.path.join(BASE_DIR, 'templates/jinja2')], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'bge_app.jinja2.environment' }, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [(os.path.join(BASE_DIR, 'templates')),], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] jinja2.py added to … -
How do i create a table using JSON in my views.py?
This is my views.py marking = StudentBehaviorMarking.objects.all() corevaluesdescription = CoreValuesDescription.objects.values('id', 'Description').distinct( 'Description').order_by('Description') period = gradingPeriod.objects.filter(id=coreperiod).order_by('Display_Sequence') studentcorevalues = StudentsCoreValuesDescription.objects.filter(Teacher=teacher).filter( GradeLevel=gradelevel.values_list('Description')) \ .values('Students_Enrollment_Records').distinct('Students_Enrollment_Records').order_by( 'Students_Enrollment_Records') student = StudentPeriodSummary.objects.filter(Teacher=teacher).filter( GradeLevel__in=gradelevel.values_list('id')) How do i create a table using this query that correspond each other? this is i want a result This is my models class CoreValues(models.Model): Description = models.CharField(max_length=500, null=True, blank=True) Display_Sequence = models.IntegerField(null=True, blank=True) . class CoreValuesDescription(models.Model): Core_Values = models.ForeignKey(CoreValues,on_delete=models.CASCADE, null=True) Description = models.TextField(max_length=500, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, on_delete=models.CASCADE) Display_Sequence = models.IntegerField(null=True, blank=True) class StudentBehaviorMarking(models.Model): Marking = models.CharField(max_length=500, null=True, blank=True) Non_numerical_Rating = models.CharField(max_length=500, null=True, blank=True) class StudentPeriodSummary(models.Model): Teacher = models.ForeignKey(EmployeeUser, on_delete=models.CASCADE,null=True, blank=True) Students_Enrollment_Records = models.ForeignKey(StudentSubjectGrade,on_delete=models.CASCADE) -
Error while creating a view and displays some errors which goes like explicit label and isn't inside the INSTALLED APPS
the Entire error message is: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x000001967F417820> Traceback (most recent call last): File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 356, in check all_issues = self._run_checks( File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\ALEX GEORGE\Dev\cfehome\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "c:\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\ALEX GEORGE\Dev\cfehome\src\trydjango\urls.py", line 19, in <module> from … -
why i cant save m2m relationships in Django 3
recently i have upgrade and app to django 3, and i'm using a many to many relationship to define the people i want to send and email, in this way: class Contact(Master): name = models.CharField(max_length=100, blank=True, null=True, verbose_name=_('name')) email = models.EmailField(verbose_name=_("Email"), max_length=70, db_index=True, unique=True) class Meta: verbose_name = _("contact") verbose_name_plural = _("contacts") def __str__(self): return "{} - {}".format(self.name, self.email) class Newsletter(Master): template = models.CharField(verbose_name="template",max_length=100,null=True,blank=True) subject = models.CharField(max_length=100,null=False) text_content = models.TextField(blank=True,null=True) send = models.BooleanField(db_index=True,default=True) contacts = models.ManyToManyField('contacts.Contact', blank=True, related_name="contacts", verbose_name=_('contacts')) i make all the migrations and everything looks normal, but when i try to add contacts to the newsletter, via "admin" or "shell" it shows this error: ProgrammingError at /es/admin/contacts/newsletter/4/change/ syntax error at or near "ON" LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC... the complete traceback error shows this Traceback (most recent call last): File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.SyntaxError: syntax error at or near "ON" LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 944, in add self._add_items( File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 1123, in _add_items self.through._default_manager.using(db).bulk_create([ File …