Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Issues with RDS Aurora Postgres
I have utility cron jobs working on thousands of records at a time (read/write). They keep getting the following error, randomly, and without a pattern: django.db.utils.InternalError: cannot execute UPDATE in a read-only transaction The database is RDS Aurora Postgres -- I have two instances in that cluster -- one Writer/One Reader. I created a single endpoint that includes both of them, thinking read/write usage from my application will be routed and managed intelligently by the cluster. I may have have been wrong here. Is there anything else I (besides Exception handling.......) that I can use to make continuous read/write requests from the cluster more robust? It's really unusable this way. -
Obtaining user location - Django, GeoIP2
I am trying to get user locations. Everything looks good if I turn on the development server on my server, using: python manage.py runserver 157.245.228.127:8000 But if I'm trying to get locations by going to the site, for exapmle: http://157.245.228.127/ this is not working properly. Of course, this results in the correct location being obtained http://157.245.228.127:8000/ . Why when I try to enable my server through python manage.py runserver can recive locations correctly and in the other case not? My file: views.py from django.contrib.gis.geoip2 import GeoIP2 [...] ip = request.META.get('REMOTE_ADDR', None) if ip: city = g.city(ip)['city'] else: city = 'Not work' -
Display name along with the count in descending order in Django
I have two models within my models.py file as described below: class Company(models.Model): company_name = models.CharField(max_length=100) def __str__(self): return f"{self.company_name}" Class Jobs(models.Model): job_title = models.CharField(max_length=100) job_company = models.ForeignKey(Company, models.on_delete=CASCADE) job_location = models.CharField(max_length=50) job_salary = models.CharField(max_length=20) def __str__(self): return f"{self.job_title}" The data present within these tables is as shown below: COMPANY -------------------- | COMPANY_NAME | -------------------- | Google | | Facebook | | Microsoft | | Amazon | -------------------- JOBS ------------------------------------------------------------------- | JOB_TITLE | JOB_COMPANY | JOB_LOCATION | JOB_SALARY | ------------------------------------------------------------------- | ENGINEER | GOOGLE | SAN JOSE | 5000 | | MANAGER | AMAZON | NYC | 8000 | | DELIVERY MAN | AMAZON | WASHINGTON DC | 2000 | | ACCOUNTANT | MICROSOFT | SFO | 4000 | | SALES LEAD | GOOGLE | SFO | 5000 | | DESIGNER | GOOGLE | NYC | 3500 | | CHEF | GOOGLE | NYC | 2500 | ------------------------------------------------------------------- I would like to display the following output on my template: COMPANY NAME ALONG WITH THE NUMBER OF JOBS BEING OFFERED AT THE COMPANY IN DESCENDING ORDER AS SHOWN BELOW. GOOGLE (4) AMAZON (2) MICROSOFT (1) Thank you so much for your time and help! -
take a choice off if the name starts with A Django
thanks for your time: i'd like to take one choice option off if the name of the People starts with letter 'a': basically if People.nome or (Animal.pessoa) starts with letter 'A' i'd like to take the choice (2,'GATO') off. is there a way to do that or should i try another aproach besides a ChoiceField from django.db import models from django.core.validators import RegexValidator class People(models.Model): nome = models.CharField(max_length=200) birthday_date = models.DateField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) def cant_have_cat(self): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] self.maiusculo = self.pessoa.upper if self.maiusculo[0] == 'A': self.tipo != 2 return field_choices class Animal(models.Model): pessoa = models.ForeignKey(People, on_delete=models.CASCADE) name = models.CharField(max_length=100) tipo = models.IntegerField(choices=cant_have_cat) custo = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return '%s %s' % (self.pessoa, self.name) forms.py class AnimalForm(forms.ModelForm): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] name = forms.CharField(max_length=100) tipo = forms.ChoiceField(choices=field_choices) custo = forms.DecimalField(max_digits=7, decimal_places=2) class Meta: prefix = 'animal' model = Animal fields = ('name', 'tipo', 'custo') def clean(self): people_name = self.People.nome upper = people_name.upper() if upper[0] == 'A': Animal.tipo != 2 -
How do I create a date range filter in a class based view?
My class based view in "views.py" class PostListView(ListView): model = Post.objects.filter(created__range=["2020-03-09", "2020-03-31"]) template_name = 'main/problems.html' context_object_name = 'posts' ordering = ['-created'] I have a variable "created" for when the post is created but dont know how to filter the post within a range. -
Django migrations for custom types
I would like to extend django migrations functionality - for legacy project. I am trying to do is create migrations for example for custom Enum types, which are already defined inside the DB. I used django's customized introspection command to extract all the details required to build up Enum structure inside my django project. The important thing is that Enum type inside my django project is a customized django.db.models.fields.Field. The structure of the Enum type and its implementation details are not that important to this issue. The problem is when it comes to executing makemigrations and migrate. Django django.apps.apps registry stores only models, which are registered in the ModelBase metaclass. Which in turn does not allow me to inspect my Enum types. How could I extend django migrations functionallity without monkey patching all things suchas django.apps.Apps, django.db.migrations.state.ProjectState etc. ? The only other way I can think of is to create totally custom app that would mirror all files from Django migrations system, with customized classes for registry and state etc. But this would probably break if there is an update of Django, not to mention its not ideall solution to copy&paste all modules. Update 1 I thought I create a … -
Django filter relationship in models.py
Assuming the following scenario at 2 seperated apps where i want to count() the number of posts at my template: Categories/models.py class Category(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=20, verbose_name="Title") ... @property def posts(self): return Post.objects.filter(category_id=self.id).count() Posts/models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title") content = models.TextField(verbose_name="Content") tag = models.CharField(verbose_name="Meta", max_length=70, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) template.html: <h5>Number of Post elements: {{ category.posts }}</h5> sadly this always results in the following error: ImportError: cannot import name 'Post' from partially initialized module 'Posts.models' (most likely due to a circular import) -
Django migrations throws ORA-00955 error when using oracle database
I'm stuck in a weird situation where I have to be using an oracle database along with Django. Before I get started I would like to mention that I run the database from inside a docker container. The problem that I've stumbled upon is that even though the database is up and running, I initialised a connection with DataGrip to it and it works just fine when it comes to Django everything blows up. This is how I configured the database inside Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'localhost:1521/ORCLCDB.LOCALDOMAIN', 'USER': 'terkea', 'PASSWORD': 'test', } } But when I run python manage.py makemigrations python manage.py migrate it throws up this error Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 335, in execute output = self.handle(*args, **options) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle fake_initial=fake_initial, File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\Terkea\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, … -
How to correctly show tags from TaggableManager via Crispy forms?
When I edit the form, then unloading the attached tags to this object and get a list on the HTML template <div class="col-md-6"> {{ form.tags|as_crispy_field }} </div> [<Tag:Sport> ,<Tag:Music>] models.py class NewsForm(ModelForm): class Meta: model = News fields = ['Title', 'tags',] widgets = { 'tags': forms.TextInput(attrs={'data-role': 'tagsinput'}) } I think need to somehow call this method def get_tags(self): return self.tags.names() -
Creating sign in for custom model in Django
There are lots of methods to realize user authentication in Django. And I used model form to create a form and sign up process. Now I really have no idea about signing in. I can't use built-in login, because there is no relation between my model (it's called Account) and django's built-in User model. I want to get some advice about the way. Here are my codes: views.py: def sign_up(request): context = {} form = SignUpForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('/') else: form = SignUpForm(request.POST or None, request.FILES or None) context['form'] = form return render(request, "sign_up.html", context) models.py: class Account(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=60) username = models.CharField(max_length=30) password = models.CharField(max_length=60) university_name = models.ForeignKey( University, on_delete=models.CASCADE, blank=True, null=True) isPhysicalAccount = models.BooleanField(default=False) def __str__(self): return self.username forms.py: lass SignUpForm(forms.ModelForm): class Meta: model = Account fields = "__all__" def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) -
ManyToManyField breaking in Admin screens and shouldn't be
I have some models like this: class Category(models.Model): class Meta: ordering = ['name'] name = models.CharField(max_length=100) text = models.TextField(blank=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Tool(models.Model): name = models.CharField(max_length=30, null=True, default='') url = models.URLField(max_length=250, null=True, default='') image_url = models.URLField(max_length=250, null=True, default='', blank=True) about = models.TextField(default='', null=True, blank=True) tags = models.ManyToManyField( Tag, related_name="tools" , blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category1") altcategory = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True, related_name="category2") And everything seem ok, except when I go to add a tag to a Tool in the Admin screens. I can create a Tool and Tag but when I select a tag in the taglist in the Admin screens and Save I get: The above exception (syntax error at or near "ON" LINE 1: ...ls_tool_tags" ("tool_id", "tag_id") VALUES (1, 2) ON CONFLIC... ^ ) was the direct cause of the following exception: with the sql: ('INSERT INTO "tools_tool_tags" ("tool_id", "tag_id") VALUES (%s, %s) ON ' 'CONFLICT DO NOTHING') The DEBUG screen is saying the error is at "tag_id", is strange... I hope it's not a version thing, since I'm using Heroku and have been really impressed with how everything "just works". My Django version is '3.0.4' … -
How to use timenow to fetch objects with two dates even if one of the dates is in the past in Django?
I have a trips model that has in_flights and out_flights associated to a Client. I wanted to show which Clients have trips after now so I did the following: ls= Clients.objects.get(nif=nif ClientsDash = (Clients.objects.filter(trip__in_flight__date__gt=timezone.now()).filter(trip__out_flight__date__gt=timezone.now()).distinct()) The problem is, if one Client has one of the flights in the past, or only one of the flights, it won't display the trip. -
Item not checkout using stripe
I am trying to submit a stripe payment using python/django/jquery but with no success. I am not sure where is the problem since I am using the same checkout function from the course I am doing. Therefore, I have print(order_form.is_valid(), payment_form.is_valid()) giving me the outcome of True, False in which payment_form is not valid. follow the code checkout/views.py from django.shortcuts import render, get_object_or_404, reverse, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import MakePaymentForm, OrderForm from .models import OrderLineItem from django.conf import settings from django.utils import timezone from tour_store.models import Destinations import stripe # Create your views here. stripe.api_key = settings.STRIPE_SECRET @login_required() def checkout(request): if request.method == "POST": # call the two forms that will be used order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # Then will check if both forms are valid if yes, save print(order_form.is_valid(), payment_form.is_valid()) if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price order_line_item = OrderLineItem( order=order, destination=destination, quantity=quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: … -
Can no longer drop database and reapply migrations in Django?
Throughout writting my app many times I have had to delete my database and re run my migrations. This has always worked by simply deleteing the database file then just running manage.py migrate . However now when I try to do this, I get an error saying django.db.utils.OperationalError: no such table: Planner_course where Planner is my app name and Course is one of my class schemas. What I am doing essentially follows this answer.I am unsure why less than a week ago I was able to reset my database using this method and now I cannot. Does anybody have any ideas? I get error wether I run makemigrations migrate or even runserver, where as everyother time it would simply remake the db and apply the migrations when I reran the migrations with no db. Here is the full error code: "C:\Program Files\JetBrains\PyCharm 2019.3.3\bin\runnerw64.exe" C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\python.exe "C:\Program Files\JetBrains\PyCharm 2019.3.3\plugins\python\helpers\pycharm\django_manage.py" migrate C:/Users/cabra/OneDrive/Desktop/CoursePlanner Tracking file by folder pattern: migrations Traceback (most recent call last): File "C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\cabra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: Planner_course The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
docker-compose up hangs performing system checks
I entered "docker-compose up". It executes but hangs after this line of output: app_1 | Applying sessions.0001_initial... OK I've tried pruning my containers and rerunning but always get stuck here. Here is the entire console output: recipe-app-api on master [⇡!?] on 🐳 v19.03.5 () via 🐍 3.8.1 took 7s ➜ docker-compose up recipe-app-api_db_1 is up-to-date Creating recipe-app-api_app_1 ... done Attaching to recipe-app-api_db_1, recipe-app-api_app_1 db_1 | The files belonging to this database system will be owned by user "postgres". db_1 | This user must also own the server process. db_1 | db_1 | The database cluster will be initialized with locale "en_US.utf8". db_1 | The default database encoding has accordingly been set to "UTF8". db_1 | The default text search configuration will be set to "english". db_1 | db_1 | Data page checksums are disabled. db_1 | db_1 | fixing permissions on existing directory /var/lib/postgresql/data ... ok db_1 | creating subdirectories ... ok db_1 | selecting default max_connections ... 100 db_1 | selecting default shared_buffers ... 128MB db_1 | selecting default timezone ... UTC db_1 | selecting dynamic shared memory implementation ... posix db_1 | creating configuration files ... ok db_1 | running bootstrap script ... ok db_1 | sh: … -
Construct QueryDict from string representation
I have a QueryDict in string form: "<QueryDict: {'order_by': ['-time_updated'], 'page_size': ['500']}>" I wish to construct a QueryDict object from this string. Does QueryDict have a built in way to accomplish this? (the docs don't seem to point towards that) If not, what would be the best way to create it manually? -
Using both Django and Express
I have this problem. I'm working on this app with Express and I have an API made with Django. Now, what I want is to get the API response on my NodeJs app. For example router.get('/v1/users', (req, res) => { res.send('Django Data') }) I'm using cors and it seems everything is alright but I have no idea how can I get the data. // ./app.js const express = require('express') const cors = require('cors') ... const apiRouter = require('./routes/api') const app = express() app.use(cors({ origin: 'http://127.0.0.1:8000/' })) ... app.use(express.json()) ... app.use('/api', apiRouter) ... module.exports = app Does someone have an idea of what can I do to get the data from my Django API? -
save some model field from form django
I'm new in django. i have a question ... i have a model with some fields and i want to get just some of these fields from a form and store in db ... is it possible?! models.py class motors(models.Model): agent = models.ForeignKey(agent_model.agents, on_delete=models.CASCADE) users = models.ManyToManyField(user_model.users, through='user_motors') price = models.FloatField(default=0) serial = models.TextField() produce_date = models.DateField(default=now) name = models.CharField(max_length=200, blank=False, default='') pic = models.ImageField(upload_to='motor images/', null=True) forms.py class MotorSignUpForm(forms.Form): name = forms.CharField() serial = forms.CharField() price = forms.FloatField() pic = forms.ImageField() class Meta: model = models.motors fields = ('name', 'serial', 'price', 'pic', ) views.py def motor_register(request): if request.method == 'POST': form = forms.MotorSignUpForm(request.POST) if form.is_valid(): motor = form.save(commit=False) motor.refresh_from_db() motor.motors.name = form.cleaned_data.get('name') motor.motors.serial = form.cleaned_data.get('serial') motor.motors.price = form.cleaned_data.get('price') motor.motors.pic = form.cleaned_data.get('pic') motor.save() return redirect('user/index') else: form = forms.MotorSignUpForm() return render(request, 'motor/signup.html', {'form': form}) -
Django self.save() not updating the status of the model
I have a very simple model and view py file for cats (trying to test out/learn basic features of django. However the cat's happiness status never really updated. class Cats(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) name = models.CharField(max_length = 200) description = models.TextField() happiness = 6 def pet(self): self.happiness = self.happiness+1 self.save() from django.shortcuts import render, get_object_or_404 from .models import Cats def cat_detail(request, pk): cat = get_object_or_404(Cats, pk=pk) return render(request, 'cats/cat_detail.html', {'cat': cat}) def cat_interact(request, pk, action): cat = get_object_or_404(Cats, pk=pk) pet = False if(action == 1): cat.pet() pet = True return render(request, 'cats/cat_interact.html', {'cat': cat, 'pet': pet}) action will always be 1 (that's the only current action possible). Inside the html file of both "detail" and "interact" I print out the happiness status of the cat. When I go to the interact page, the cat's happiness status is printed as 7 (since default/start happiness is 6). I expect this value (7) to be saved to the database and when I go to the detail page again it also prints 7. However, even after running the function cat.play() on the detail page it still prints 6, which is the default. Is the 7 never saved to the data base? … -
Chained drop down fileds
lets say that i have this 3 tables class Dhmos(models.Model): name = models.CharField(max_length=100,verbose_name='Πελάτης', blank=False) address = models.CharField(max_length=100,verbose_name='Διεύθυνση', blank=True,default='-') city = models.CharField(max_length=100,verbose_name='Πόλη', blank=True,default='-') phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) fax = models.CharField(max_length=50, verbose_name='Fax', blank=True) teamviewer = models.CharField(max_length=60, verbose_name='TeamViewer', blank=True) email = models.EmailField(blank=True) website = models.URLField(max_length=250, blank=True, null=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Meta: verbose_name = 'Πελάτες' verbose_name_plural = 'Πελάτες' ordering = ['id'] def __str__(self): return self.name class Employee(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', null=True) firstname = models.CharField(max_length=150, verbose_name='Όνομα', null=True) lastname = models.CharField(max_length=150, verbose_name='Επώνυμο', null=True) tmhma = models.CharField(max_length=100, choices= tmhma_choice, verbose_name='Υπηρεσία', blank=True) phone = models.CharField(max_length=100, verbose_name='Τηλέφωνο', blank=False) cellphone = models.CharField(max_length=30, verbose_name='Κινητό', blank=True) email = models.EmailField(blank=True) info = models.TextField(max_length=1000, verbose_name='Πληροφορίες', blank=True) is_visible = models.BooleanField(default=False,verbose_name='Κατάσταση') class Ergasies(models.Model): dhmos = models.ForeignKey('Dhmos', on_delete=models.CASCADE, verbose_name='Πελάτης', default='-') importdate = models.DateField(default=datetime.date.today,verbose_name='Ημ. Κατ.') app = models.CharField(max_length=100, choices=app_choice,verbose_name='Εφαρμογή', blank=True) jobtype = models.CharField(max_length=100, choices=job_choice, verbose_name='Τύπος Εργασίας', default='TeamViewer') info = models.TextField(max_length=1000, verbose_name='Περιγραφή') text = models.TextField(max_length=1000, verbose_name='Σημειώσεις', blank=True) employee = models.ForeignKey('auth.User', max_length=100, verbose_name='Υπάλληλος', on_delete=models.CASCADE,default='-')#delete kai time = models.CharField(max_length=20,verbose_name='Διάρκεια', default=0) name = models.CharField(max_length=100, verbose_name='Υπάλληλος Επικοιν.', null=True,help_text='Επώνυμο-Όνομα', blank=True) ticketid = models.CharField(max_length=50,verbose_name='Αίτημα OTS', blank=True) When i add a record to Ergasies table i want when i choose Dhmos to filter the Employees and display only employees related to Dhmos. How can i do that, … -
dash_bootstrap_components.min.js not found when running Dash inside Django
I am getting dash_bootstrap_components.min.js not found when i try to integrate Dash with Django. Installed dash_bootstrap_components for Dash css Dash Python: external_stylesheets = ['https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'] app = DjangoDash('SIPPage',external_stylesheets=external_stylesheets) -
Django model.delete() reseed primary key
Busy developing my Django app and as it goes I have test data that I would like to delete from some of my tables. How can I delete the entries and "reset" the primary keys so that the next time an element is inserted, it has id=1? When I run .delete() I am able to delete the row, but the primary key is not reset. According to a bit of research this is standard with databases and I need to truncate the table. Some suggestions are to Truncate the table with raw SQL code: import sqlite3 conn = sqlite3.connect('db.sqlite3') cur = conn.cursor() cur.execute("TRUNCATE TABLE 'table'") which does not seem to work and just gives the following error: OperationalError: near "Truncate": syntax error Other suggestions are to comment out the model and redo migrate. This is not an option either as there are multiple dependent foreign keys across the tables. Is there no way to reset the primary key of a table? -
Restrict options to a ChoiceField Django
thanks for your time: i'd like to know if there is a way to restrict an option on a choicefield if other field starts with a letter 'A': basically i want to don't let the user set the choice (2, 'GATO') on Animal.tipo if his name starts with letter 'a' on People.nome models.py: from django.db import models from django.core.validators import RegexValidator class People(models.Model): nome = models.CharField(max_length=200) birthday_date = models.DateTimeField() cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')]) def __str__(self): return '%s' % (self.nome) class Animal(models.Model): field_choices = [ (1, 'CACHORRO'), (2, 'GATO'), (3, 'OUTRO'), ] pessoa = models.ForeignKey(People, on_delete=models.CASCADE) name = models.CharField(max_length=100) tipo = models.IntegerField(choices=field_choices) custo = models.DecimalField(max_digits=7, decimal_places=2) def __str__(self): return '%s %s' % (self.pessoa, self.name) def cant_have_cat(self): self.maiusculo = self.pessoa.upper if self.maiusculo[0] == 'A': self.tipo != 2 -
PostgreSQL psycopg2 error: there is no unique constraint / InvalidForeignKey
I have the following models: class Contact(models.Model): email = models.EmailField() class EventList(models.Model): event_contacts = models.ManyToManyField(Contact, through=EventMembership) class EventMembership(models.Model): event_list = models.ForeignKey(EventList, null=True, on_delete=models.PROTECT) event_contact = models.ForeignKey(Contact, null=True, blank=False, on_delete=models.PROTECT) However, when applying migrations for EventMembership on a completely clean database I get the following error: psycopg2.errors.InvalidForeignKey: there is no unique constraint matching given keys for referenced table "contacts_contact" class Migration(migrations.Migration): initial = True dependencies = [ ('lists', '0001_initial'), ('contacts', '0002_auto_20200308_2253'), ] operations = [ migrations.CreateModel( name='EventMembership', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('event_contact', apps.utils.django_multitenant.fields.TenantForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='contacts.Contact')), ('event_list', apps.utils.django_multitenant.fields.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='lists.EventList')) ] ] Table contacts_contact clearly has a unique constraint in id as the primary key. What could be causing this error? / How do I debug this? -
How to create a subscriber with PubSub on Google Cloud App Engine that listens to a message via Publisher from a Google Cloud App Engine Flex?
I have a Django Application running on Google App Engine. There is another time consuming application running in Google App Engine Flex that is triggered from the Google App Engine Application. When the Google App Engine Flex Application finished its execution, I want it to trigger a message and send it to Google App Engine Django Application, so Django can update the database item accordingly. How can I use Google Cloud PubSub to achieve this?