Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sort based on multiple models and properties
I have two models as bellow: class Source: user = ForeignKey(User) title = models.CharField(max_length=300) class Post: source = ForeignKey(Source) like = ManyToMany(User) title = models.CharField(max_length=300) Each post has a source, and a user can choose multiple or all sources that created by the admin. users can like posts. Firstly, I wanna limit posts to just the sources chosen by the logged in user, and then sort them based on the number of likes that each post has, How? Thanks in advance -
How to order in django on two columns when one of the column is null
I would like to order the dataset based upon the two columns let's say created_date and updated_date. If updated_date is null it should order be using created_date otherwise using updated_date column. -
Django atomic transaction works on sqlite but doesn't work on postgresql
I'm currently using a sqlite db for testing and everything works fine but I realize when I switch to postgresql db the atomic transaction doesnt work properly. if bool(airplane): if airplane[0].is_ready==True: service=ServiceModel.AirplaneService.objects.get(airplane=pk,is_next=True) serializer=ServiceSerializer.AirplaneServiceList(service) with transaction.atomic(): next_service.do_service(airplane[0]) data={ 'service':service.id, 'airplane':airplane[0].id, 'company':request.auth.payload.get('company'), 'tt':airplane[0].tt, 'ct':airplane[0].ct, 'dt':airplane[0].dt, } log=ServiceSerializer.AirplaneServiceLog(data=data) log.is_valid() log.save() return Response(serializer.data,status=200) else: return Response("The airplane is not ready to fly",status=500) -
Show field in template but dont allow it to be edited (Django)
Say I have a model class MyModel(model.Models): name = model.CharField() age = model.IntField() Then in my template I want to display the name but only allow age to be changed i.e the user should not be able to modify what is written in the name field but it should just be there to show, which name they are editing the age for. My template is as the following {% extends "myapp/base.html" %} {% load static %} {% block content %} {% load crispy_forms_tags %} <div class="content-section"> <div class="form-group"> {{form.name|as_crispy_field}} <!-- Can still edit this field --> <form method="POST"> {% csrf_token %} {{form.age|as_crispy_field}} <button class="btn btn-outline-success" type="submit">Update</button> <a role="button" class="btn btn-outline-info" href="{% url 'my_list' %}"> Wups, take me back!</a> </div> </form> </div> {% endblock content %} -
How to response image? in Django
I'm new to Django. This is my Chatbot made by Django. I'd like to answer two things at once, text and photo. But I can't. I tried to input this module import base64 with open(image_path, "rb") as image_file: image_data = base64.b64encode(image_file.read()).decode('utf-8') ctx["image"] = image_data return render(request, 'index.html', ctx) But I failed to change 'return Jsonresponse(''')' properly. views.py @csrf_exempt def chatanswer(request): context = {} questext = request.GET['questext'] import pickle import colorama colorama.init() from colorama import Fore, Style, Back file = open(f"./static/intents.json", encoding="UTF-8") data = json.loads(file.read()) def chat3(inp): # load trained model model = keras.models.load_model('static/chat_model') # load tokenizer object with open('static/tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle) # load label encoder object with open('static/label_encoder.pickle', 'rb') as enc: lbl_encoder = pickle.load(enc) # parameters max_len = 20 # while True: print(Fore.LIGHTBLUE_EX + "User: " + Style.RESET_ALL, end="") # inp = 'What is name' result = model.predict(keras.preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences([inp]), truncating='post', maxlen=max_len)) tag = lbl_encoder.inverse_transform([np.argmax(result)]) for i in data['intents']: if i['tag'] == tag: txt1 = np.random.choice(i['responses']) print(Fore.GREEN + "ChatBot:" + Style.RESET_ALL, txt1) return txt1 anstext = chat3(questext) print(anstext) context['anstext'] = anstext context['flag'] = '0' return JsonResponse(context, content_type="application/json") I don't know what should I do.. Thanks a lot -
Login form writes that the ' ' already exists
So, i have a problem. I have a login form, but when i try to login it writes that ' ' is already exists. How is it possible?If user has an account it means that it'll exists. But why i get this mistake? views.py def login(request): if request.method == 'POST': form = LoginForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): cd = form.cleaned_data user = authenticate(email=cd['email'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: return HttpResponse('Form is not valid') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) I get a mistake: <ul class="errorlist"><li>email<ul class="errorlist"><li>User with this already exists.</li></ul></li></ul> Login form class LoginForm(ModelForm): class Meta: model = User fields = ['email', 'password'] widgets = { 'email': EmailInput(attrs={ 'class': 'form-email', 'placeholder': 'email' }), 'password': PasswordInput(attrs={ 'class': 'form-password', 'placeholder': 'password' }) } User model class User(models.Model): CHOICES = ( ('1', 'Author'), ('2', 'Customer'), ('3', 'Author and Customer') ) first_name = models.CharField(max_length=64, blank=False, verbose_name='') last_name = models.CharField(max_length=64, blank=False, verbose_name='') patronymic = models.CharField(max_length=64, blank=False, verbose_name='') age = models.PositiveSmallIntegerField(verbose_name='', blank=False) email = models.EmailField(unique=True, max_length=128, blank=False, verbose_name='') password = models.CharField(max_length=32, blank=False, verbose_name='') role = models.CharField(max_length=32, choices=CHOICES, default='Customer') about = models.TextField(max_length=512, verbose_name='', blank=True) -
Use model in models.py -> fix 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'
I have the following models.py code: class SlackAccountMatching(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True) slack_user_id = models.CharField(default=None, null=True, max_length=50) class SlackNotifications(models.Model): organization = models.ForeignKey(Organization, on_delete=models.CASCADE) slack_notification_name = models.CharField(default=None, null=True, max_length=255) slack_notification_time = models.TimeField(default=datetime.time(16, 00)) Below in the same file I want to use both SlackNotifications and SlackAccountMatching to make queries in the respective model. I was looking into the [ready()][1] and therefore am doing: from django.apps import AppConfig class SlackApplicationConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'slack_application' def ready(self): from .models import SlackAccountMatching, SlackNotifications However, the error is still showing up: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. Any ideas on how to fix this? Thank you. [1]: https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig.ready -
Django + AJAX abort executing funtion
I am using ajax to run a django function. In this function, I connect to the database and run a sql statement, the result of which is saved to a csv file. This sql takes a long time to run at times, and I would like to be able to interrupt this function on demand. Is it possible? Can I get the id of the running process or request and use it to kill it? -
How to efficiently Rank model obj in django
I have a model called 'Student' and it has a field 'score' that stores the total marks attained by a student. I would love to know a fucntion that will enable me to rank students based on their respective scores -
Django Rest Framework Hiding the JSON data
I have just started learning Django Rest Framework. Most of the tutorials I follow use drf with react. Now I want to hide the api so that no one can see any data whenever they enter that url. I just need the url to post data (for ex- from a membership form...name email and stuff). How can I achieve this. Most of the questions here only talk about hiding browsable api. Please do tell if I am thinking in the wrong direction. The idea behind this is that I don't want the information I ask from a user to be visible to everyone through that url. I tried achieving this in the following way. Is this a fine way of doing this or is this going to mess up the application, because I don't see any errors and the post requests are working. I am using React for the frontend. This is my first time posting a question. Please tell if you need any other information. Thanks a lot in advance. I have only done this in the first if block {if request.method == 'GET':}, I returned a string instead of serializer.data and now whenever i go to membershipform/ it … -
Form Not Clearinng after submit
I created a booking form using Django's modelformset_factory and when I fill up the form and click on submit, it successfully stores data in database but there arise a problem the form doesnt clears instead it creats new form. But when I clears data from database the forms clears automatically. Can somebody tell me the problems. Here is my models.py code: class Booking(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100) nationality = models.CharField(max_length=100) passport = models.CharField(max_length=100) email = models.CharField(max_length=100) phnumber = models.CharField(max_length=100) checkin = models.DateTimeField(max_length=20) checkout = models.DateTimeField(max_length=20) roomtype = models.CharField(max_length=100) def __str__(self): return self.name class Meta: db_table = "room_book" Here is the code of views.py def form(request): BookForm = modelformset_factory(Booking, fields=( 'name', 'address', 'nationality', 'passport', 'email', 'phnumber', 'checkin', 'checkout', 'roomtype'),extra=2) if request.method == 'POST': form = BookForm(request.POST or None, request.FILES or None) form.save() form = BookForm() return render(request, 'form.html', {'form': form}) Here is my code of form.html: <form id="mainForm" method="post"> {% csrf_token %} {{ formset.management_form }} {{form.as_p}} <input type="submit"> -
Django DRF serializer return duplicate objects while query_set is unique
I have a model LessonsData and I am trying to serialize LessonsData.objects.filter(creator=request.user) The result of query set is <QuerySet [<LessonData: LessonData object (22)>]> This means only one object is returned in query_set. Then I pass this to my model serializer that returns the duplicate result containing three same objects [OrderedDict([('creator', OrderedDict([('user', OrderedDict([('created_at', 'Saturday, 01 May 2021'), ('first_name', 'Hashir'), ('last_name', 'Hassan'), ('email', 'mhashirhassan@gmail.com'), ('phone_no', '+923228080110'), ('user_type', 'CR'), ('is_active', True), ('last_login_ip', None)])), ('profession', 'Fitness Trainer2'), ('profile_image', None), ('year_of_experience', None), ('subdomain', 'eddygrero'), ('bio', 'Testing the web'), ('intro_video', None), ('avg_rating', 3.0)])), ('name', 'lorem'), ('description', 'pesum'), ('no_of_participants', 2), ('language', ['English']), ('lesson_type', 'GROUP'), ('session_type', 'SINGLE'), ('meeting_type', 'HOST_LESSON'), ('meeting_link', 'https://us05web.zoom.us/j/81870334516?pwd=VWxYSFdEMXpLVmFNUTJTS0J2QS9OZz09'), ('lesson_uuid', '2145fa1e-b5a7-4d76-8c0e-a1a4555642c2'), ('cover_image', None), ('learnings', ['abc']), ('requirements', ['abc']), ('status', 'ACTIVE'), ('price', {'type': 'pricePerSession', 'value': '10', 'currency': 'USD'}), ('upcoming_slot', {'creator': OrderedDict([('user', OrderedDict([('created_at', 'Saturday, 01 May 2021'), ('first_name', 'Hashir'), ('last_name', 'Hassan'), ('email', 'mhashirhassan@gmail.com'), ('phone_no', '+923228080110'), ('user_type', 'CR'), ('is_active', True), ('last_login_ip', None)])), ('profession', 'Fitness Trainer2'), ('profile_image', None), ('year_of_experience', None), ('subdomain', 'eddygrero'), ('bio', 'Testing the web'), ('intro_video', None), ('avg_rating', 3.0)]), 'lesson': OrderedDict([('id', 22), ('name', 'lorem'), ('description', 'pesum'), ('no_of_participants', 2), ('language', ['English']), ('lesson_type', 'GROUP'), ('session_type', 'SINGLE'), ('meeting_type', 'HOST_LESSON'), ('price', {'type': 'pricePerSession', 'value': '10', 'currency': 'USD'}), ('timezone', 'America/Juneau'), ('meeting_info', {'id': 81870334516, 'type': 3, 'uuid': '+7wO45guSrmgEa4ynQDpMw==', 'topic': 'lorem', 'status': 'waiting', 'host_id': 'PTU0xTJjTOOAi_iFUZZa-g', 'join_url': 'https://us05web.zoom.us/j/81870334516?pwd=VWxYSFdEMXpLVmFNUTJTS0J2QS9OZz09', … -
I want to load a static file from django template like.. {% static {{post.image}} %}
I want to load a static file from django template like.. {% static {{post.image}} %} but is error Can you show me code like this? Did you understand? Need more clarification? -
No CSRF input field in html form of dajngo rest framework in put method
PUT, DELETE method is generating this error when submitted from the api webpage { "detail": "CSRF Failed: CSRF token missing or incorrect." } But POST method is working fine in the same API modal created using viewsets.ModelViewSet So I inspect the form and found that the post method has CSRF input field but PUT html form doesn't have the CSRF so the error is showing how can I fix this issue. Package used: Django==2.2.5 djangorestframework==3.7.7 django-rest-auth==0.9.5 django-filter==2.2.0 settings.py file REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_FILTER_BACKENDS': [ 'django_filters.rest_framework.DjangoFilterBackend', ], } Why DRF template adds the CSRF field in POST HTML form but doesn't add that field in PUT HTML form. I am ready to provide any additional info if required is there anything I had missed in the setup. -
python variable having , between like this: (order_item, created = ...)
order_item, created = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) now here I can't understand how it will work I tried searching the web but had no luck :( -
Can not query foreign key related objects using _set | Django?
can not access foreignkey related objects , showing error i have crated instance of Hospital and Availablity , But while querying using H1.availablity_set.all() //error 'Hospital' object has no attribute 'availablity_set' models.py class Hospital(models.Model): name = models.CharField(max_length = 256) address = models.CharField(max_length=256,null=True, blank=True) phone = models.CharField(max_length=10) city = models.ForeignKey(City, on_delete=models.CASCADE, related_name = 'City') def __str__(self): return self.name class Availablity(models.Model): hospital = models.ForeignKey(Hospital, on_delete = models.CASCADE, related_name='availablities') facility = models.ForeignKey(Facility, on_delete= models.CASCADE, related_name='facilities') updated_at = models.DateTimeField(auto_now=True) total = models.IntegerField(default=0) available = models.IntegerField(default=0) code -
Tabula-py split row depending on the condition
I have a csv like below and i want to split rows base on header 2 and 3, how can i do that in tabula-py? sample csv below is the code i used in converting from pdf to csv then i am displaying it in html table tabula.convert_into("PDFTest_index\static\\test.pdf", "PDFTest_index\static\\output.csv", output_format="csv", pages='all',lattice=True, stream=True) df = pd.read_csv('PDFTest_index\static\\output.csv') df.columns = df.columns.str.replace(' ', '') json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} I have no idea, on how to do this in python tabula -
HTML table not fetching data from Django only showing heading
I'm using HTML, CSS, and Javascript for the frontend and Django for the backend, and PostgresSQL for DB. Actually, I have successfully loaded data from the EXCEL file to Django and I'm trying to fetch data from Django to HTML Table. But, I'm getting only headers of the table, not the data. How to fix it. index.html {%extends "base.html"%} {%block content%} <html> <table> <thead> <th>Brand</th> <th>Name</th> </thead> <tbody> <tr> <td><strong>{{pro.brand}}</strong></td> <td><strong>{{pro.name}}</strong></td> </tr> </tbody> </table> {%endblock%} views.py def product(request): pro = Product.objects.all() return render(request, 'index.html',{'pro': pro}) urls.py (App file) urlpatterns = [ path('product/', views.product, name='product'), ] -
Annotation syntax error when migrating from 2.2.x to 3.x
I am in the process of migrating from Django 2.2 to 3.2. After fixing most deprecation issues, an annotation I rely on throughout my project is throwing a syntax error. It does not appear to matter which 3.x version I use, and this annotation has worked throughout most of 2.2.x's versions: Journal.objects.annotate( p_user=F('assignment__courses__participation__user'), can_have_journal=F('assignment__courses__participation__role__can_have_journal'), ).filter( Q(assignment__is_group_assignment=True) | Q(p_user__in=F('authors__user'), can_have_journal=True), ) This yields the following error: django.db.utils.ProgrammingError: syntax error at or near ""VLE_assignmentparticipation"" LINE 1: ...ave_journal" AND "VLE_participation"."user_id" IN "VLE_assig... Part of the trace: venv/lib/python3.8/site-packages/django/db/models/query.py:317: in __getitem__ qs._fetch_all() venv/lib/python3.8/site-packages/django/db/models/query.py:1324: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.8/site-packages/django/db/models/query.py:51: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py:1169: in execute_sql cursor.execute(sql, params) venv/lib/python3.8/site-packages/sentry_sdk/integrations/django/__init__.py:434: in execute return real_execute(self, sql, params) venv/lib/python3.8/site-packages/django/db/backends/utils.py:66: in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) venv/lib/python3.8/site-packages/django/db/backends/utils.py:75: in _execute_with_wrappers return executor(sql, params, many, context) venv/lib/python3.8/site-packages/django/db/backends/utils.py:84: in _execute return self.cursor.execute(sql, params) venv/lib/python3.8/site-packages/django/db/utils.py:90: in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value For good measure a link to the models file If I eliminate the or in the filter block: | Q(p_user__in=F('authors__user'), can_have_journal=True), the annotation works without issues. I cannot find anything in the release/deprecation notes about annotations changing, does anyone have a recommendation on what the underlying issue could be? -
500 Internal server error "populate() isn't reentrant"
I am having issues with deploying some recent work on a Django app to my server. On deployment, I updated a few pip modules, and there was also some restructuring of the directories. Once done, I restarted apache2, but was greated by the below error messages which proved unhelpful [Thu May 13 13:12:09.846428 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] mod_wsgi (pid=8385): Target WSGI script '/var/www/stage.admin.agile.coop/web/mysite/wsgi.py' cannot be loaded as Python module. [Thu May 13 13:12:09.846751 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] mod_wsgi (pid=8385): Exception occurred processing WSGI script '/var/www/stage.admin.agile.coop/web/mysite/wsgi.py'. [Thu May 13 13:12:09.847024 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] Traceback (most recent call last): [Thu May 13 13:12:09.847174 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/web/mysite/wsgi.py", line 16, in <module> [Thu May 13 13:12:09.847275 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] application = get_wsgi_application() [Thu May 13 13:12:09.847363 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/venv/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu May 13 13:12:09.847460 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] django.setup(set_prefix=False) [Thu May 13 13:12:09.847561 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] File "/var/www/stage.admin.agile.coop/venv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup [Thu May 13 13:12:09.847655 2021] [wsgi:error] [pid 8385:tid 140483483444992] [remote 2a02:c7f:6c19:2c00:4150:e3c6:fe11:d603:34690] apps.populate(settings.INSTALLED_APPS) [Thu May 13 13:12:09.847755 … -
UnboundLocalError:local variable 'final_result' referenced before assignment..django
I am a beginner in Programming and Django. I am making a calculator. but I am getting an error(UnboundLocalError:local variable 'final_result' referenced before assignment).The code is from django.http import HttpResponse from django.shortcuts import render import re def clculator(request): pass def calculation(request): if request.method == "POST": values = request.POST['values'] print(values) vals = re.findall(r"(\d+)", values) operators=['+','x','÷','-','.','%'] opr = [] for v in values: for o in operators: if v == o: opr.append(o) print(opr) print(re.findall(r"(\d+)", values)) for o in (opr): if o=='.': i=opr.index(o) res=vals[i]+"."+vals[i+1] vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=res print(vals) print(opr) for o in opr: if o == '%': i = opr.index(o) res =(float(vals[i])/100)*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]= res print(vals) print(opr) for o in opr: if o == '÷': i = opr.index(o) res = float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == 'x': i = opr.index(o) res = float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == '+': i = opr.index(o) res = float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) for o in opr: if o == '-': i = opr.index(o) res = float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i] = str(res) print(vals) print(opr) if len(opr) != 0: if opr[0] == '÷': result = float(vals[0])/float(vals[1]) … -
Django's validation level
I have a model level validation: class MyModel(models.Model): # some fields def clean(self): pass But how can I get a request.user in clean method so the model to be validated as via django's default admin forms as via views (REST api)? Or what is the best practice in which level to validate: Model, ModelForm, Serializer, View? -
How can I populate a form field from a list of elements in JavaScript?
I've got a fantasy football project that I built in Django that generates a list of HTML elements. Like this... <tbody id="page1"> {% for q in QBpage %} <tr> <td><h6 id="qbname">{{ q.player_name }}</h6></td> <td><button onclick="selectPlayer()" type="button" id="qbackbutton" class="btn btn-success btn-sm m-0 waves-effect" data-player-name="{{ q.player_name }}" data-position="{{ q.position }}">Add</button></td> <td><h6> {{ q.team }} </h6></td> <td><h6> {{ q.position }} </h6></td> <td><h6>{{ q.points }}</h6></td> </tr> {% endfor %} </tbody> It's a list of players (all quarterbacks) pulled from an API. What I'm trying to do is from each player's corresponding "Add" button, is add that player's name to a form field that's also on the same page. I can do that using this JavaScript function... function selectPlayer (){ let d = document.getElementById("qbname"); document.getElementById("QB_name").value = document.getElementById("qbname").innerHTML; } Problem is though, I can only get the name of the first player in the list because all players end up with the same id. Therefore, you can only retrieve the first element. Even if I click on a player further down the list, that first player's name is the only one that is returned. Assigning a class won't work because, as far as I understand, you can only "getElementsByClass" so you end up retrieving all the … -
Django and pytest, multiple databases, use only one database
I have 2 databases in my project: DATABASES = { 'default': env.db('DEFAULT_DATABASE_URL'), 'second': env.db('SECOND_DATABASE_URL'), } When I had only one database, then all tests that required access to the database passed fine, but when I connected the second one, then all tests began to fail with an error - django.db.utils.IntegrityError: duplicate key value violates unique constraint. As I understand it, the test runs twice for each database and crashes because of this. Is there some way to tell pytest to only take one database for tests? Example of one test: @pytest.mark.django_db def test_complaint_reasons(client: APIClient): reasons_count = 12 Profile.create_batch(reasons_count) client.force_login(Factory()) response = client.get(reverse('url')) assert response.status_code == status.HTTP_200_OK assert len(response.data) == reasons_count jsonschema.validate(response.data, ProfileComplaintReasonsSchema) -
Django global ManyToMany Relation (more than symmetrical)
I have trouble on how to make a ManyToMany relation where every object is connected to every other object. Here's my example for better understanding: class Animal(models.Model): animaux_lies = models.ManyToManyField("self", verbose_name="Animaux liés", blank=True) If y have only two animals linked together, it works fine, thez I correctly linked together in both ways (because the relation is symmetrical). But if I have 3 or more animals, I don't get the result I want. If Animal1 is linked to Animal2 and Animal3, I would like Animal2 to not only be linked to Animal1 but also to Animal3 (and Animal3 linked to 1 and 2). How can I do that? Even with a through table I don't see how to do this correctly