Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect if error occurs inside class-based view Django
I have a class-based view (lets say, DetailView) which renders a page with a list of objects based on slug in the URL. But if an object with the given slug does not exist, it gives me an error. What I want is to redirect to the main page instead of raising an error. It should be easy, but I can't understand how to do this, so I wanna ask for help here. Example: views.py class ShowExerciseRecords(ListView): def get_queryset(self): exercise = Exercise.objects.get(slug=self.kwargs['slug']) return exercise.record__set.all() urls.py urlpatterns = [ path('/exercise/<slug:slug>/', ShowExerciseRecords.as_view()) path('', index, name='home') ] -
Pytest to verify the existence of fields listed in list_display
I'm writing unit tests and want to know if it's possible to make a test of the existence of all list_display fields in the admin interface. for example for this model: class Order(models.Model): class PaymentStatuses(models.TextChoices): PENDING = "pending" PAID = "paid" REFUNDED = "refunded" order_ref = models.CharField(max_length=128, unique=True) payment_status = models.CharField(max_length=50, choices=PaymentStatuses.choices) user = models.ForeignKey( "users.User", on_delete=models.CASCADE, related_name="orders" ) shipping_cost = models.DecimalField(max_digits=9, decimal_places=2, default=0) delivery_datetime = models.DateTimeField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) @property def total_price(self) -> Decimal: total_price = Decimal(0) for item in self.items.all(): total_price += item.unit_price * item.quantity return total_price I want to add total_price field to the list of Orders displayed in the admin interface and make a test for that. how to verify the existence of the field in the content of response = client.get('/admin/orders/order/') -
Can I use the values from a form in other form with Django?
I have a Django app with two forms where the views.py looks like this: import pandas as pd import numpy as np from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.template.response import TemplateResponse from pbmcalculator.models import PbmCalculator, simulator from django.core.cache import cache import json @login_required def subs_calc(request): # this is from the first form # selection = request.GET.get("id", None) customer = request.GET.get("customer", None) initial_date = request.GET.get("initial_date", None) final_date = request.GET.get("final_date", None) if selection is not None and 'initial_date' in request.GET: calculation_target = PbmCalculator(customer, initial_date, final_date) html = TemplateResponse( request, "pbmcalculator/table.html", { some operations }, ) return html if 'generico_sim' in request.GET: # this is from the second form # brand_sim = request.GET.get("brand_sim",None) generico_sim = request.GET.get("generico_sim",None) marca_sim = request.GET.get("marca_sim",None) initial_date_sim = '2021-08-08' final_date_sim = '2021-08-15' calculation_sim = simulator(brand_sim, initial_date_sim, final_date_sim) html = TemplateResponse( request, "pbmcalculator/table1.html", { some operations }, ) return html return render(request, "pbmcalculator/subs_calc.html", {"selected": False}) So I want to use the variables initial_date and final_date in the second if statement to fill the initial_date_sim and final_date_sim. I tried several ways but none worked. Some idea? -
Django UpdateView only possible within 15 minutes
I have a small app. In the model I have: created_at = models.DateTimeField(auto_now_add=True, default = 'time and date created'), Now I want that after 15 minutes of the created_at the UpdateView is no longer executable. however I just can't even display the creats_at class update_post(UpdateView): print(Posts.created_at) model = Posts ... This show only (<django.db.models.fields.DateTimeField>,) -
How can I run multiple Django servers from one Pycharm Project?
I want to be able to run three different Django servers from within 1 Pycharm project, however, when you go into: settings -> languages & frameworks -> Django it seems that you can only set 1 Django project root, 1 Django settings.py file, and 1 Django manage.py file for all the Django servers you have running. Short of creating a new Pycharm project for each Django server, which I do not want to do, is there any way I can have a separate configuration for each of the three Django projects? -
Saving centroid of a (multi)polygon as point geometry in a model
I have two tables, one with multipolygon geometries, the other with a column for point geometries. I want the centroid of the selected polygon to be saved as the point geometry for the other table. class matview_all_administrative_units(models.Model): lau_id = models.IntegerField(primary_key=True) ortsgemeinde = models.CharField(max_length=150) verwaltungsgemeinde = models.CharField(max_length=150) landkreis_bezirk = models.CharField(max_length=150) bundesland_kanton = models.CharField(max_length=150) staat = models.CharField(max_length=150) geom = models.MultiPolygonField(srid=4326) class Meta: managed = False db_table = 'administrative_hierarchy_full_geom' class site(models.Model): sid = models.AutoField(primary_key=True) site_name = models.CharField(max_length=250) site_notes = models.CharField(max_length=2500, blank=True, null=True) municipality = models.ForeignKey('local_administrative_unit', on_delete=models.PROTECT) geom = models.PointField(srid=4326) def __str__(self): return '{}, {} ({})'.format(self.sid, self.site_name, self.municipality) To add a new site, an existing administrative unit must be associated with it and the center of it's polygon should be used as the location/geometry of the site. For now I made this: class NewSiteView(CreateView): model = models.site form_class = forms.NewSiteForm template_name = 'datamanager/newsite.html' success_url = '/sites/' calling this form: from django.forms import ModelForm, HiddenInput from django.contrib.gis.db.models.functions import Centroid from . import models class NewSiteForm(ModelForm): class Meta: model = models.site fields = ['site_name', 'site_notes', 'municipality','geom'] widgets = { 'geom': HiddenInput(), } def clean(self): super().clean() self.cleaned_data['geom'] = Centroid(models.matview_all_administrative_units.objects.values('geom').filter(lau_id=self.cleaned_data['municipality'].lau_id)) however, this leads to this error: So I am basically not calculating a point but a 'centroid object' … -
Django: constraint with nullable multiple field conditions
I have a model in Django/PostgreSQL project and want to add following constraints to three nullable fields: either all fields are NULL, either all of them aren't. Here's code (simplified): class SomeModel(models.Model): ... a = models.IntegerField(nullable=True) b = models.DateTimeField(nullable=True) c = models.DateTimeField(nullable=True) ... class Meta: constraints = [ models.CheckConstraint( check=( (Q(a__isnull=True) & Q(b__isnull=True) & Q(c__isnull=True)) | (Q(a__isnull=False) & Q(b__isnull=False) & Q(c__isnull=False)) ) ) ] If I understand correctly, I've just described two possible states of those three fields. First is "all three are NULL", second is "none of them are NULL". But what I got, actually, is "none of them can be NULL". Django admin panel insists on filling all of the fields, they all are mandatory. How can I fix this behaviour? Thanks! -
After deploy django projcet,emal send doesn't work.Can anyone help me to fix that?
In my django project when ı am working localhost sending mail is working.After that ı deployed my project on aws,but at this time email send doesn't work.Can anyone explain this? My settings/base.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_PORT = '587' # EMAIL_USE_SSL = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER EMAIL_USE_TLS = True -
How can I show mi profile picture?
The photo is uploaded and saved in the database but I can't show the picture in the template. Now, what can I do? Where is the problem? What will be the logic? Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR] MEDIA_URL = '/media/' Urls: urlpatterns = [ path('admin/', admin.site.urls), path('', include('business_app.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Views: def change_profile_picture(request): if request.user.is_authenticated: if request.method == "POST": profile_picture = request.FILES['profile_picture'] if 'profile_picture' in request.FILES else None user = get_object_or_404(User, pk=request.user.pk) if request.user.pk != user.pk: return redirect("/") Profile_picture.objects.create( Profile_picture = profile_picture, USer = request.user, ) return redirect("/") return render(request,'0_index.html') Models: class Profile_picture(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE, related_name="user_propic") Profile_picture = models.ImageField(upload_to="3_profile_picture/",default='3_profile_picture/avatar.png', null=True, blank=True) templates: <img src="static/1_images/3_about.jpg" alt="" width="100" class="img-fluid rounded-circle mb-3 img-thumbnail shadow-sm"> -
Can a textfield in postgres be used with a charfield in django?
I have a table in postgres with a column description that had the type varchar(2000), so in django: description = serializers.CharField(......., max_length = 2000) I want to change the description column in postgres to type text Can I leave the description as a charfield? Or do I have to change it to a textfield? I still want to have max_length specified but change it to 5000, ie: description = serializers.CharField(......., max_length = 5000) I've tried to read the docs: https://www.django-rest-framework.org/api-guide/fields/#charfield, but I didn't see it being stated explicitly. From what I've seen, it says: CharField corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField I'm guessing that means it's ok? I also looked around on stackoverflow: What's the difference between CharField and TextField in Django?, but I didn't see it being stated explicitly either. -
how to store user data from user model inside a database table in django
I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table, Buyer model in models.py: class Buyer(models.Model): row_id = models.AutoField(primary_key=True) user_name = models.CharField(unique=True, max_length=50) user_password = models.CharField(max_length=16) first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50) email = models.CharField(unique=True, max_length=100) home_phone = models.CharField(max_length=20, blank=True, null=True) mobile_phone = models.CharField(unique=True, max_length=20) personal_id = models.CharField(max_length=30, blank=True, null=True) idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True) # Field name made lowercase. personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk') # Field name made lowercase. address_line_1 = models.CharField(db_column='address_Line_1', max_length=200) # Field name made lowercase. address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase. p_o_box = models.CharField(max_length=20, blank=True, null=True) city = models.CharField(max_length=50) country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk') # Field name made lowercase. gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK') # Field name made lowercase. bdate = models.DateField() def __str__(self): return 'User: ' + self.user_name class Meta: managed = False db_table = 'buyer' and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page -
Django - details of one account showing up on another account
I've have a pet registration system where the customer can log into their account and register their animals. However once you have registered the animal and log out and another user logs in that user can see all the pets of all users. I'm not sure what's causing this. my views.py def customer_profile(request): if request.method == "GET": if request.user.is_authenticated: get_pets = PetRegistration.objects.filter() context = { "pets": get_pets, } return render( request, "registration/customer-profile.html", context=context ) return redirect("login") if request.method == "POST": context = {} return render(request, "registration/customer-signup.html", context=context) def pet_register(request): if request.method == "GET": if request.user.is_authenticated: form = PetRegistrationForm() context = { "form": form, } return render(request, "registration/pet-register.html", context=context) return redirect("login") if request.method == "POST": form = PetRegistrationForm(request.POST, request.FILES) context = { "form": form, } if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect("customer_profile") return render(request, "registration/pet-register.html", context=context) model.py class PetRegistration(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) name = models.CharField(max_length=30) image = models.ImageField(null=True, blank=True) age = models.CharField(max_length=30) animal_type = models.CharField(max_length=30) vaccination_status = models.CharField(choices=STATUS, max_length=20) def __str__(self): return self.name -
Create relation number based on PK in Django
I am trying for a couple of days to find a way to create a relation number based on the PK in models.py when I make a new object. The reason why I try this is, is to have a 8 digit number starting from 00000001 till 999999999. I already tried the following: client.objects.latest('pk') Result NameError: name 'client' is not defined from clients.models import client Result: ImportError: cannot import name 'client' from partially initialized module 'clients.models' (most likely due to a circular import) def save(self, *args, **kwargs): self_pk = self.objects('pk') self.relation_number =self_pk self.save(*args, **kwargs) Result: AttributeError: Manager isn't accessible via Section instances Hope someone can help me with this. -
ValueError: invalid literal for int() with base 10: '-----'ValueError: invalid literal for int() with base 10: ''
Product(product_id2=prod_id2,shop=request.user,product_name=prod_name,category=category.objects.get(id=int(cat)),subcategory=subcategory,price=price,price_not=price_not,desc=desc,gst=gst_l,image1=image1).save() i tried int(float(Cat)) but its showing could not convert string to float: '-----' -
Why django can't recognize 2 path convertors from each other?
I have a django application and I have 2 url paths that are only different in the last part which is the path convertors: path('questions/<pk>', views.QuestionDetailView.as_view(), name='question_detail'), path('questions/<slug:tag_slug>', views.QuestionListView.as_view(), name='questions_by_tag') When I go to 127.0.0.1:8000/questions/1 it's ok and it shows the correct results, but when I go to 127.0.0.1:8000/questions/something(something is a slug) it says page not found!(It must use the seconed url path but it does not!) When I change the paths order it shows the second one correctly and the other one is a problem! Can anybody help me please? -
How to Check data is int, float in python
I know similar questions have been asked and answered before like here: How do I check if a string is a number (float or Int ) in Python? However, it does not provide the answer I'm looking for. What I'm trying to do is this: def is_int_or_float(s): try: a = float(s) return 1 if s.count('.')==0 else 2 except ValueError: return -1 val = input("Enter your value: ") data = is_int_or_float(val) print(data) What if User enters => "22" # Then Above code will gives -1.Please help me to resolve this -
How to save data from an online API to display it in Django rest framework?
I am trying to get pricing API from coinmarketcap and save them or display them locally in Django Rest framework on localhost? What different things should I do in my models.py? What different thing should I do in my views.py? I have created a requests.py with the header from which I want to get data/ API endpoint? How will I connect or store it in my models.py? At the moment my request.py file inside my API folder also gives an error of module import for requests? I have just simply created a request.py with endpoint url for getting data from coinmarketcap, where should I save it to display on drf frontend? import requests headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': ' MY API KEY', } res = requests.get("https://pro-api.coinmarketcap.com/v1/fiat/map", headers=headers) print(res.json()) print(res.text) Views.py from django.shortcuts import render from rest_framework.response import Response from rest_framework.decorators import api_view @api_view(['GET']) def getUrls(request): api_urls = { 'Crypto Prices': '/prices', } return Response(api_urls) models.py from django.db import models class Prices(models.Model): symbol = models.CharField(max_length=50) def __str__(self): return self.name -
Redirect to same page after form submitted in views.py not working while using Django paginator
I want to redirect to same page after submitting form which fetches view from views.py. The problem is paginator. After submitting Django form page reloads to page 1. I want browser to stay on the same page after submitting form. Error I get: django.urls.exceptions.NoReverseMatch: 'http' is not a registered namespace. Help would be greatly appreciated! Code calling path in js: let path = window.location.href Fetching api: subedit[i].addEventListener('click', () => { fetch(`/edit/${content[i].id}`, { method: 'POST', headers: {'X-CSRFToken': csrftoken}, mode: 'same-origin', body: JSON.stringify({ post: textarea[i].value, page: path })}).then(() => { editdiv[i].style.display = 'none'; post[i].style.display = 'block'; })}) views.py: def edit(request, post_id): data = json.loads(request.body) content = data.get("post", "") post=Post.objects.get(id=post_id) page = data.get("page", "") if request.method == "POST": if post.user == request.user: post.post=content post.save() return HttpResponseRedirect(reverse(str(page))) -
CSRF verification failed. Request aborted in Django rest framework sending the request from flutter
I've followed everything mentioned in both documentation of Django rest-framework and Flutter http but still getting the error ..here is my code : Django Settings REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ] } View @csrf_exempt @permission_classes(["isAuthenticated"]) @api_view(['POST']) def chanage_image(request): data = {} if request.method == "POST": token = request.META['HTTP_AUTHORIZATION'][6:] lang = request.META['HTTP_LANG'] image = request.data['image'] main_user = Token.objects.get(key=token).user app_user = AppUser.objects.get(main_user=main_user) format, imgstr = image.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext) # You can save this as file instance. app_user.image = data app_user.save() data = {"success": True, "details": AppUserSerializer( app_user).data, "message": "Image changed" if lang == "en" else "تم تغيير الصورة"} return Response(data, headers=get_headers()) URLS path('chanage_image/', chanage_image,name="chanage_image"), Flutter Request Map<String, dynamic> body = { "image": base64Image, }; Future<UserModel> changePlayerImage(Map<String, dynamic> body) async { return await httpClient.post('api/user/change-image', body: body, headers: {'referer': 'https://www.l-dawri.com/'}).then((response) { print(response.body); return UserModel.fromJson(response.body); }); } but still in the end am always getting this error : CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. -
Django Notify user execution state
When making a call to server I want the server to notify each time a "stage" has been completed instead of waiting complete execution. Let's say I have a call in views.py def some_call(request): final_body = long_process_with_stages() return HttpResponse(json.dumps(finalbody)) # I need to change this # return StreamingHttpResponse(long_process_with_stages()) where def long_process_with_stages(): sleep(30) print("Stage 1 completed") sleep(30) print("Stage 2 completed") sleep(30) print("Stage 3 completed") sleep(30) return "This is the final response" I tried the StreamingHttpResponse but method kept being called even after it finished Is it possible to achieve this? -
Resetting password in authenticationApp
I need the users to give their old password too while resetting the password using the link they receive from django backend. How do I implement this? Thanks in advance. -
Create a register in another table with the id as FK of the first table automatically after creating the register in the first table Django
Models.py class Email(models.Model): id = models.CharField(max_length=200, primary_key=True) subject = models.CharField(max_length=200) message = models.CharField(max_length=2000) time = models.CharField(max_length=50) read = models.BooleanField() starred = models.BooleanField() hasAttachments = models.BooleanField() class Attachments(models.Model): type = models.CharField(max_length=200) filename = models.CharField(max_length=200) preview = models.CharField(max_length=200) url = models.CharField(max_length=200) size = models.CharField(max_length=200) referring_email = models.ForeignKey(Email, related_name='email',on_delete=models.CASCADE, null=True, blank=True) Serializers.py class AttachmentSerializer(serializers.ModelSerializer): class Meta: model = Attachments fields = '__all__'#·('type','filename','preview','url','size') class EmailSerializer(WritableNestedModelSerializer): #to = ToSerializer(many=True) #froms = FromsSerializer() attachments = AttachmentSerializer(many=True, required=False) class Meta: model = Email fields = '__all__' def create(self, validated_data): #Popeo del JSON los campos Foreign Keys hayAttachments = False if(validated_data.get('attachments') != None): attachments_data = validated_data.pop('attachments') hayAttachments = True #Creo el objeto email a partir del JSON tocado email = Email.objects.create(**validated_data) if(hayAttachments): for attachment_data in attachments_data: attachment = Attachments.objects.create(**attachment_data) attachment.referring_email = email return email When I create an email, I want to automatically create an attachment and put the current email id as foreign key in the attachment table. I tried with this but only creates the attachment and set the FK=NULL, any help will be apreciated. (If you need anymore information, I'll update it) This is the Json from wich I load the data: { "id": "15459251a6d6b397565", "subject": "Commits that need to be pushed lorem ipsum dolor … -
Response.status_code 400 for a simple view test
I'm passing a simple json body to my view but I'm getting a 400 instead of a 200. It should be a really straightforward test but I can't quite figure out what is wrong. Thanks. Url: "api/v2/ada/send", views.sendView.as_view(), name="ada-send", ), View: class sendView(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated,) def post(self, request, *args, **kwargs): body = request.data return Response(body, status=status.HTTP_200_OK) View Test: class AdaSendGet(APITestCase): url = reverse("ada-send") def test_choice_type_valid( self,): user = get_user_model().objects.create_user("test") self.client.force_authenticate(user) response = self.client.post( self.url, { "contact_uuid": "49548747-48888043", "choices": 3, "message": ( "What is the issue?\n\nAbdominal pain" "\nHeadache\nNone of these\n\n" "Choose the option that matches your answer. " "Eg, 1 for Abdominal pain\n\nEnter *back* to go to " "the previous question or *abort* to " "end the assessment" ), "step": 6, "value": 2, "optionId": 0, "path": "/assessments/assessment-id/dialog/next", "cardType": "CHOICE", "title": "SYMPTOM" }, content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_200_OK) Error: self.assertEqual(response.status_code, status.HTTP_200_OK) AssertionError: 400 != 200 -
How to display 2 months in my calendar in Django?
so I'm making a calendar application based on this calendar design and this is how it currently looks However I want to display 2 months side by side in this calendar (in the example above I would want April to be right next to March and the days would go from March 30th, 31st and then April 1st - April 30th). Does anyone know how to do this. utils.py from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'{week}' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' #cal += f'{self.formatweekheader()}\n' months … -
Django FOREIGN KEY constraint failed, when adding Many To Many Association to Instance for the second time
i am currently trying to teach myself the django framework. Something really odd is happening when trying to connect to object instances via a ManyToManyField. Starting from a fresh Database (object creation in Shell, but same problem in Code): When i create the first object (Product) everything works fine. I create the object and add the other object (ProductTag) to the ManyToManyField of the first one. Now here comes the Problem: after I did that, and try the same thing again with different Instances (or the same ones, as last time) I get an django.db.utils.IntegrityError, which says "FOREIGN KEY constraint failed" Console In/Output of the problem: (InteractiveConsole) >>> from onlineShop.apps.products.models import Product, ProductTag >>> from django.contrib.auth.models import User >>> from onlineShop.apps.profiles.models import Profile >>> p = Profile.objects.first() >>> t = ProductTag.objects.create(name="outdoor", name_verbose="Outdoor") >>> p.save() >>> p <Profile: superuser> >>> t.save() >>> t <ProductTag: Outdoor> >>> prod1 = Product.objects.create(vendor=p, title="test1", price=123.42, description="test1-desc") >>> prod1.save() >>> prod1 <Product: test1> >>> prod2 = Product.objects.create(vendor=p, title="test2", price=223.42, description="test2-desc") >>> prod2.save() >>> prod2 <Product: test2> >>> prod1.tags.add(t) >>> prod1.save() >>> prod1 <Product: test1> >>> prod2.tags.add(t) Traceback (most recent call last): File "C:\Users\lukas\.virtualenvs\Django_Shop-2dmIjN-v\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above …