Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SUM 2 Column with Different Condition
In Django how to sum 2 column with different condition, how i try to sum column amount with condition trx=2 and amount with condition trx=3 reportusage = (Invoices.objects .annotate(month=ExtractMonth('datetime')) .values('month') .annotate(total=Sum('amount').filter(trx=2) + Sum('amount').filter(trx=3), product=F('tenant')) .order_by()) -
Django, warning as VIEW return queryset unordered
The Django view templates takes parameters from url,filter database and output as list. Even though I have added the ordering , I get result unordered class PostListView(ListView): model = Post template_name = ** ordering = ['-created_at'] paginate_by = 5 def get_queryset(self, *args, **kwargs): **** return posts -
Manytomanyfields issue : Fetch the columns where the manytomanyfield is applied
(Sorry for the inappropriate title. I am very bad at english. So I couldn't find out what should be the title) I have 2 tables Devices and groups class Devices(models.Model): id = models.AutoField(primary_key=True) device_name =\ models.CharField(max_length=100, null=False) class Groups(models.Model): group_id = models.AutoField(primary_key=True) devices = models.ManyToManyField(Devices, blank=True) I have more than 100000 devices and 100 groups. The devices can have multiple groups. I want to fetch the group_ids each device is having. I tried to loop through all the devices and fetch the group column. But it is taking too much time. Is there any pythonic way to solve this? -
Django inline formset not saving default values
I have a child inlineformset that saves if it has been changed by the user, but does not save the default value if left unchanged. SeVsEff is the child, and patient is the parent models.py class Patient(TimeStampedModel): patient_id = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False ) name = models.CharField("Patient Name", max_length=255) user = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL ) class SeVsEff(TimeStampedModel): value = models.IntegerField(default=20) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py class PatientForm(ModelForm): class Meta: model = Patient fields = ["name"] SevseffFormSet = inlineformset_factory( Patient, SeVsEff, fields=("value",), widgets={'value': RangeInput()}, extra=0, min_num=1, validate_min=True, labels=None, ) views.py def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) sevseff_formset = SevseffFormSet(data=self.request.POST) if form.is_valid(): patient_instance = form.save() patient_instance.user = self.request.user patient_instance.save() if sevseff_formset.is_valid(): sevseff_name = sevseff_formset.save(commit=False) for sevseff in sevseff_name: sevseff.patient = patient_instance sevseff.save() So I think the issues is that the sevseff_formset is not registered as valid unless it is changed, but if I add something like: if not sevseff_formset.has_changed(): sevseff_name = sevseff_formset.save(commit=False) for sevseff in sevseff_name: sevseff.patient = patient_instance sevseff.save() This doesn't work as sevseff_name is empty. -
How to upload multiple file in django create view where the total number of files can be uploaded is not fixed
i had created a form to fill up by the users where the user can upload multiple files which is not fixed(like they can upload 1 or 2 and so on).So how to achieve this in django create view -
How to extract top 2 by group in django queryset
Django queryset related question. Feedback class model contains the student registration date, etc... Assignment class model contains student personal information, and Level class model contains the class to which the student belongs. I want to print out the two students with the earliest registration date for each class. Using the max function, the first student registered by class can be printed, Feedback.objects.filter(assignment__is_deleted=0)\ .values('assignment__level')\ .annotate(first=Max('ICF_date')) but how to print the second registered student by class? I would like the result to be printed in one line. -
React While calling API : Access to XMLHttpRequest has been blocked by CORS policy
I am using Django rest api in React but I am getting this as Error: Access to XMLHttpRequest at 'http://127.0.0.1:8000/list/single/6' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. <------- Can anyone help me in brief Please? I need to complete my project for this solution I am searching for a week. If you left your Telegram id then it would be great to solve for me you can delete it later for privacy. -
How can i query multiple objects, filtering with multiple id's
class Timeline(models.Model): license = models.ForeignKey(License, on_delete=models.CASCADE) last_renewed = models.DateField() due_date = models.DateField() def home(request): title = "Licences" agencies = Agency.objects.all() agent =Agency.objects.get(pk=1) licenses = License.objects.all() for license in licenses: print(license.id) timeline = Timeline.objects.select_related().filter(license_id = license.id).order_by('-id')[:1] I want to display at least one timeline related to each of the licenses that i am querying -
How can I pass variable in dynamic URL in Django Template
So I have a blog site and I want that when someone clicks on the delete button so the blog should delete. But the slug in the URL is a Variable how I can pass it? URL path: code:"path('deletePost/slug:slug', views.deletePost, name='deletePost')," I have passed the variable "Del_slug" to this view so how can I use it in the URL. code:"Delete" -
I have django application running on apache+docker on port 8000:80,need to run another application with another port but not working
I have Django application running with apache+docker with 8000:80 port in ubuntu server. Now I have another Django application. I want to run that application with apache+docker with different port 8006 or any other port. I think we can't bind two applications for the same port 80.Correct me if I am wrong and suggestions are most welcome. I am able build docker container and service is up, but I'm not accessible on browser and requests. So, is there any way that I can do it and able to access in browser please suggest Here is my docker-compose.yml version: '3.1' services: test-app: image: test-app build: context: ./app/ ports: - "8006:8006" # networks: # - GST container_name: test-app environment: - TZ=Asia/Kolkata restart: on-failure volumes: - /storage/req_resp_files:/var/www/html/GSTDP_Develop/req_resp_files - /storage/gst_logs:/var/www/html/GSTDP_Develop/logs Here is my Dockerfile FROM httpd:latest RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf #ADD ./httpd-ssl.conf /usr/local/apache2/conf/extra/httpd-ssl.conf #ADD ./server.key /usr/local/apache2/conf/server.key #ADD ./server.crt /usr/local/apache2/conf/server.crt #ADD ./gd_bundle-g2-g1.crt /usr/local/apache2/conf/gd_bundle-g2-g1.crt ADD ./GSTDP_Develop /var/www/html/GSTDP_Develop RUN chown -R www-data. /var/www/html/GSTDP_Develop RUN chown -R www-data. … -
In which part of Django application a user is made authenticated?
I am trying to restrict multiple logins by a user with the use of sessions Below is my code my model class LoggedInUser(models.Model): user = models.OneToOneField(CustomUser, related_name='logged_in_user', on_delete =models.CASCADE) session_key = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return self.user.username my middlware ef MySessionMiddleware(get_response): def my_function(request): if request.user.is_authenticated: try: user = LoggedInUser.objects.filter(user=request.user).first() except: user = LoggedInUser.objects.create(user=request.user) if user.session_key: #check whether old key is same as current print('here inside user.session_key') if user.session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() response = get_response(request) return response return my_function my middleware setting MIDDLEWARE = [ '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', 'pwned_passwords_django.middleware.PwnedPasswordsMiddleware', 'oneFA.middlewares.password_validator_middleware', 'oneFA.middlewares.MySessionMiddleware', ] my logic I created a model which stores a user with OnetoOne field with CustomUSer which is my authenticated model, and a session key then everytime i made a call i am trying to check the current session key with previous one and if it is not same then a user is trying to login again so i am returning error my error request.user.is_authenticated is always coming false which means that user is not authenticated now , i even tried placing my middleware ahead of authentication middleware and … -
how to make a url variable available to all the template
I have a specific requirement - say I hit the url as below - http://127.0.0.1:8000/brand_product_list/1 in the above url the last 1 is a brand-id and I need this brand-id to be available to all the templates for eg. if I call my brand_product_list looks like below in views.py - # Product List as per Brand1 def brand_product_list(request,brand_id): brandid = brand_id brand_b=Brand.objects.get(id=brand_id) cats_b=Product.objects.filter(brand=brand_b).distinct().values('category__title','category_id') data_b=Product.objects.filter(brand=brand_b).order_by('-id') colors_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('color__title','color__id','color__color_code') sizes_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('size__title','size__id') flavors_b=ProductAttribute.objects.filter(brand=brand_b).distinct().values('flavor__title','flavor__id') return render(request,'brand_product_list.html', { 'data_b':data_b, 'brandid':brandid, 'cats_b':cats_b, 'brand_b':brand_b, 'sizes_b':sizes_b, 'colors_b':colors_b, 'flavors_b':flavors_b, }) in the above code I need brandid to be available in cart.html which is called from clicking cart button in base.html which is extended in brand_product_list.html point is since base.html is extended in brand_product_list.html, the brandid is available to base.html (means child variable available in parent) and I can filter stuff based on brand but somehow when I click on cart button in base.html, the same brandid is not taken to cart.html even though base.html is extended in cart.html (means parent variable not available in child). I tried include as below {% include "./brand_product_list.html" %} but since in brand_product_list.html, there is some filter.html, it throws error that argument is not available -- NoReverseMatch at /cart Reverse for 'filter_data_b' with arguments '('brandid',)' not … -
Django - python form returns nothing in webpage
I am trying to add user to groups using rest api in Python. The thing is when I check the webpage it return nothing. I don't seem to be able to see my form there. Is there something wrong with my codes? and If I am doing it wrong how can I return the form in the template? Python codes: class AddUserToGroupForm2(TemplateView): template_name ='artifactory.html' def add_artifactory(request): if request.method == 'POST': form = ArtifactoryGroupForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] Group_Artifactory = form.cleaned_data['Group_Artifactory'] user = User.objects.create( name = name, Group_Artifactory = Group_Artifactory,) headers = { 'Content-Type': 'application/json; charset=UTF-8', } data = json.dumps( {"groups": Group_Artifactory}) response = requests.post(f'https:*******/api/security/users/{name}', headers=headers, data=data,verify=False, auth=(ADMIN_USERNAME , ADMIN_PASSWORD)) print(response.content) return render(request, 'homepage.html', {'form': form}) Html codes: <form method="POST"> {% csrf_token %} <h3>Artifactory Groups</h3> <div id="list1" class="dropdown-check-list"> {{form}} </div> <div id="button" class="field"> <button class="btn" type=submit> Add User to Groups </button> </div> </form> -
Django Raw SQL Returning No Results
I have a remote Microsoft SQL server accessed by my Django app. All queries are in stored procedure format. Among these SPs, some will return a queryset while some will return a distinct value (i.e. integer). For those returning a queryset, I have been able to read data by: with connections['connection_name_defined_in_settings.py'].cursor() as cursor: cursor.execute("EXEC SP_returning_queryset %s", (param,)) result = cursor.fetchone() return result The result will be in python tuple format. No problem in this case. I used the exactly same approach for those returning a distinct value (e.g. integer), an error called No results. Previous SQL was not a query. occurred in Django debugging page. Currently, my guess is that the cursor object can only contain querysets but not distinct values. Is there a way to solve it? -
How to set up the correct url ? (Django)
I have two classes in model. class Ebuy_Fields(models.Model): source = models.CharField(max_length=10) category = models.CharField(max_length=32) rfq_id = models.CharField(max_length=32) rfq_title = models.TextField() class Ebuy_Detail_Fields(models.Model): rfq_id_final = models.CharField(max_length=10) rfq_id_title_final = models.TextField() In views.py, def ebuy_detail(request,rfq): # unique_bid = get_object_or_404(Ebuy_Detail_Fields,rfq_id_final=rfq_id_final) unique_bid = Ebuy_Detail_Fields.objects.filter(rfq_id_final__icontains=rfq) context = {'unique_bid':unique_bid} return render(request,'rfq-display.html',context) urls.py path('ebuy/<rfq>', ebuy_detail, name='ebuy_detail'), In templates, <td data-label="RFQ Id"><a href = "{% url 'ebuy_detail'}">{{ i.rfq_id }}</td> After clicking, this link, it should open the detail view of the Ebuy_Detail_Fields. This opens the view but the data is not displayed according to {{ unique_bid.rfq_id_final }}. Only the template tags are loaded but not the data. rfq_id and rfq_id_final are same and it should be matching. -
How do I retain my `profile_pic` when I update other fields in my Profile model in django?
I am trying to update my UserProfile model, however the issue is, whenever I update other fields the profile_pic is set to null. How do I retain the profile_pic when I update other fields? This is my models.py from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from django.db import models from django.conf import settings class CustomUser(AbstractUser): username = models.CharField(max_length=100, blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return self.email class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=5, blank=True, null=True) dob = models.DateField(auto_now=False, auto_now_add=False, null=True) address = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) zip = models.CharField(max_length=10, blank=True, null=True) country = models.CharField(max_length=50, blank=True, null=True) profile_pic = models.ImageField(default='user_default_m.png', upload_to='profile/', blank=True, null=True) def __str__(self): return f'{self.user.username} Profile' This is my serializer.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'profile_pic',) class CustomUserDetailsSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = CustomUser fields = ('email', 'first_name', 'last_name', 'profile') # extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = CustomUser(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = … -
How to mock decorator in django unit test?
I am trying to write simple unit test for my view. I have a decorator which authenticate by sending http request. How to mock decorator of my view and run unit test? my views.py @method_decorator(authentication_decorator, name='post') class AddBlogView(CreateAPIView): serializer_class = BlogSerializer -
How does Django query the tree structure
I am new to Django and I am creating a blog and comment function from django.db import models from django.contrib.auth import get_user_model class Blog(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=200) content = models.TextField(max_length=200) class Comment(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name="children") content = models.CharField(max_length=200) This is my current test data Comment.objects.all().values() <QuerySet [ {'id': 1, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '1'}, {'id': 2, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '2'}, {'id': 3, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-1'}, {'id': 4, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-2'} ]> But now I want to find out such a tree structure, what should I do? [ {'id': 1, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '1', 'children': [ {'id': 3, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-1'}, {'id': 4, 'user_id': 1, 'blog_id': 1, 'parent_id': 1, 'content': '1-2'} ]}, {'id': 2, 'user_id': 1, 'blog_id': 1, 'parent_id': None, 'content': '2', 'children': [] }, ] -
Is there a way to connect to a bluetooth device by a django web app (so with python)?
I a personal project I was able to connect via Bluetooth to a device that measure body temperature with some python libraries. I want to implement this code in a Django web app to collect data from these Bluetooth devices, is this possible? Can you suggest me, if is it possible, how can I get this work in Django? Thanks in advance, Marco -
How do I style the formset in Django?
I have a problem; I want to put the styles to my formset because it does not inherit them from the main form and the design looks horrible, I don't know how to fix it or if there is a type of widget to make the fields look better. Thank you so much Parte/forms.py from django import forms from django.forms import formset_factory from .models import Parte class ParteForm(forms.ModelForm): class Meta: model=Parte fields=['codigo','descripcion','quantity','unit_price','total_price','tax_free'] Presupuestos/forms.py class PresupuestosParteForm(forms.ModelForm): class Meta: model = Parte fields = '__all__' widgets = { 'codigo': forms.TextInput( attrs={ 'class': 'form-control' } ), 'quantity': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'unit_price': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'multiplicar()', } ), 'total_price': forms.NumberInput( attrs={ 'class': 'form-control', } ), 'tax_free': forms.CheckboxInput( attrs={ 'class': 'form-check-input', 'onclick': 'taxes_free(multiplicar())', } ), 'descripcion': forms.TextInput( attrs={ 'class': 'form-control' } ), 'descuento': forms.NumberInput( attrs={ 'class': 'form-control', 'onchange': 'totales()', } ), 'total': forms.NumberInput( attrs={ 'class': 'form-control', } ), } ParteFormSet = formset_factory(ParteForm, extra=1) Presupuestos/views.py def create_Presupuestos(request): #Crear cada uno de los formularios y reunirlos 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) #Creación del formset de parteform if request.method == 'POST': formset = ParteFormSet(request.POST) if formset.is_valid(): # extract name from each form and … -
How to run a Function on a varying schedule in Python/Django? [duplicate]
I have a Django/Python project that I use for work, and one of the most important aspects of the website is that it tracks our equipment location. I am looking to set a custom schedule that will execute the function that gets the current location data. The schedule would look something like this. Monday Through Friday Update Every Hour between the hours of 5AM and 5PM. Update Every 3 Hours between the hours of 5PM and 5AM. Saturday and Sunday Update Every Hour between the hours of 6AM and 10AM. Update Every 4 Hours between the hours of 10AM to 6AM. In addition, if a user generates the locations manually, the counter then gets reset. For example, let's say on a Monday at 630AM, a user generates the locations manually, the next scheduled call gets moved to 730AM rather than 7AM. -
django AWS EB CLI Unable to deploy with mysqlclient
I have been attempting to deploy my Django project up on AWS ElasticBeanstalk via EB CLI n my local Pycharm project with the built in terminal. Having setup IAM/group (through aws web console) I migrated and ran server locally (Pycharm terminal) and all works fine, and then created env/instance and requirements.txt and deployed using EB CLI in Pycharm and this also worked fine. I setup a database connection on RDS (AWS web Console) then changed settings to connect to mysql, pip installed mysqlclient, migrate and ran locally (Pycharm terminal) and again all works fine. However, when I try to deply the project again with mysqlclient installed I get errors and I just cannot figure out why. Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.7 running on 64bit Amazon Linux 2/3.3.7 Requirements.txt asgiref==3.4.1 awsebcli==3.20.2 boto3==1.20.3 botocore==1.23.3 cement==2.8.2 certifi==2021.10.8 charset-normalizer==2.0.7 colorama==0.4.3 Django==3.2.9 django-storages==1.12.3 future==0.16.0 idna==3.3 jmespath==0.10.0 mysqlclient==2.0.3 pathspec==0.5.9 pypiwin32==223 python-dateutil==2.8.2 pytz==2021.3 pywin32==302 PyYAML==5.4.1 requests==2.26.0 s3transfer==0.5.0 semantic-version==2.8.5 six==1.14.0 sqlparse==0.4.2 termcolor==1.1.0 typing-extensions==3.10.0.2 urllib3==1.26.7 wcwidth==0.1.9 .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: awsdeploy.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static container_commands: 01_collectstatic: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py collectstatic --noinput --clear" 02_migrate: command: "source /var/app/venv/staging-LQM1lest/bin/activate && python manage.py migrate --noinput" leader_only: true EB Error Logs Collecting mysqlclient==2.0.3 Using cached mysqlclient-2.0.3.tar.gz (88 kB) 2021/11/11 02:10:40.712344 [ERROR] An error … -
How to keep the sidebar elements active after reloading the page
I have a sidebar implemented in my base template. The other pages, let's say page1, page2 and page3 inherit the sidebar from the base template: {% extends 'base_generic.html' %} <=== This code is present in page1, page2 and page3 My sidebar contains a <li> with three links to page1, page2 and page3. When I visit my home page, let's say example.com/index.html and the sidebar is loaded, if I click on the sidebar page1 (for example) that will reload the page since I'm calling the view: def page1(request): return render(request, 'page1.html', context=None) But then how can I mark the page1 as 'active' in the sidebar? Every time I click on some page everything is reloading. I have implemented this, but it only works if the sidebar item I click does not reload the page and remains with index.html: $(document).ready(function() { // Get the container element var sidebarContainer = document.getElementById("sidebarLinks"); // Get all li's with class="sidebar-element" inside the container var lis = sidebarContainer.getElementsByClassName("sidebar-element"); // Loop through the li and add the active class to the current/clicked li for (var i = 0; i < lis.length; i++) { lis[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // If there's no active class if (current.length … -
Django: is it good to have a model with more then 60 fields? And best way to develop project
I'm working on my first project in Django and I'd really like to have some advice from people with more experience then me since right now I'm a little stuck on what road take to keep developing my project. This is my plan to develop my project: Create a modelsFileFields so that my user can upload one or more standarded excel file Read it and create variables with pandas Create an html page with the graph with chart.js and render it in pdf with ReportLab Store the pdf in my user profile usinig primary key so that they can see it and download it again. My main problem right now is to store or not the information that are in the excel file in my database. Since getting the information in the excel file is what is important to me, my first thought was to import them and the only thing that it keeping me from doing so is the quantity of column that I have. This how my excel file looks like: total partial [...] user1 10 4 user2 18 6 I have more then 60 variable in my excel file (so I'd need a model with more then … -
django postgres :there is no unique constraint matching given keys for referenced table " "
I have 3 tables(models): event,event_type,patient both event_type and patient are foreign keys for event. event fields:id, event_type(foreign key),event_unit, event_value,event_time, patient(foreign key) event_type fields: id, type_name patient fields : patient_id ,patient_name I used Django to build the tables: class Event_type(models.Model): type_name = models.CharField(max_length=40,null=True,unique=True) class Meta: verbose_name = "event_type" verbose_name_plural = verbose_name def __str__(self): return self.type_name class Patient(models.Model): patient_id = models.AutoField(unique=True, primary_key=True) # patient identification patient_name = models.CharField(max_length=30, unique=True, verbose_name='patient_name') class Meta: verbose_name = 'Patient' verbose_name_plural = verbose_name ordering = ['-patient_id'] def __str__(self): return self.patient_name class Event(models.Model): event_id = models.AutoField(unique=True, primary_key=True) event_type = models.ForeignKey(Event_type, null=True, blank=True,on_delete=models.CASCADE, verbose_name='event type',default="",to_field='type_name' ) event_value = models.PositiveIntegerField(default=0, verbose_name='even value', blank=True) event_unit = models.CharField(max_length=100, blank=True, verbose_name='event unit') event_time = models.DateTimeField(auto_now=False, verbose_name='event time') patient = models.ForeignKey(verbose_name='patient', to='Patient', to_field='patient_id', on_delete=models.CASCADE,default="") class Meta: verbose_name = 'Event' verbose_name_plural = verbose_name ordering = ['-event_id'] def __str__(self): return self.event_type.type_name After: python manage.py migrate I received error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "patients_event_type" Any friends can help?