Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - At least one inline formset filled out of multiple inline formsets
is there a way to validate that at least 1 of the many different formsets are not empty inside forms.py? I have a working validation inside views.py but this validation don't apply to admin form. I want my code to be DRY and so my idea is to write the validation inside forms.py, so that both admin and HTML form share the same validation. models.py, Person can have multiple PersonAddress and PersonEmail class Person(models.Model): ... class PersonAddress(models.Model): person = models.ForeignKey( Person, null=True, on_delete=models.SET_NULL, related_name="person_address", ) ... class PersonEmail(models.Model): person = models.ForeignKey( Person, null=True, on_delete=models.SET_NULL, related_name="person_email", ) ... forms.py, PersonAddressFormSet and PersonEmailFormSet will become inline formsets of PersonForm class PersonForm(forms.ModelForm): ... class PersonAddressForm(forms.ModelForm): ... class PersonEmailForm(forms.ModelForm): ... PersonAddressFormSet = forms.models.inlineformset_factory( Person, PersonAddress, form=PersonAddressForm, can_delete=False, extra=1, ) PersonEmailFormSet = forms.models.inlineformset_factory( Person, PersonEmail, form=PersonEmailForm, can_delete=False, extra=1, ) views.py, under form_valid method, if both address and email formset are not has_changed, I will return form error class PersonCreateView(SuccessMessageMixin, MetadataMixin, LoginRequiredMixin, CreateView): model = Person form_class = PersonForm template_name = "person/person_form.html" def get_context_data(self, **kwargs): context = super(PersonCreateView, self).get_context_data(**kwargs) if self.request.POST: context["addresses"] = PersonAddressFormSet(self.request.POST, self.request.FILES) context["emails"] = PersonEmailFormSet(self.request.POST, self.request.FILES) else: context["addresses"] = PersonAddressFormSet() context["emails"] = PersonEmailFormSet() return context def form_valid(self, form): form.instance.created_by = self.request.user context = … -
Django: Execution order of multiple decorators login_required and permission_required
This question is asked here. However, I am still confused with the answers as the Django behavior does not follow Python's decorators execution order behavior. In summary, in Django you have to use the order for login_required and permission_required from top to bottom like below: @login_required @permission_required('perm.create', raise_exception=True) def my_view(request): ... However, looking at decorators in Python, it is the other way around. The first decorator closest to the function will be run first. Look at the following example taken from here (I modified it a bit). # code for testing decorator chaining def decorTop(func): def inner(): x = func() print("in decorTop: x =",x,"; output would be x^2 =",x*x) return x * x return inner def decorBottom(func): def inner(): x = func() print("in decorBottom: x =",x,"; output would be 2x =",2*x) return 2 * x return inner @decorTop @decorBottom def num(): return 10 print(num()) This is the output: in decorBottom: x = 10 ; output would be 2x = 20 in decorTop: x = 20 ; output would be x^2 = 400 400 Can somebody please explain more why the behavior in Django is the other way around? -
In Django, what is the difference between "{% load i18n %}" and "{% load i18n static %}"
I noticed that in password_reset_confirm.html, Django uses {% load i18n static %}. However, I have always used {% load i18n %} for translation. What is the difference between the two? What does adding static keyword achieve here? -
Django: A Case has many Person as debitor and has one Person as creditor
guys! I'm doing a test and I have some questions. The basic structure: Case case_number creditor debitors Person name document The test says that a person can be a creditor/debitor, and a case can have multiple debitors and one creditor. It is possible to do this with a single person table or I'm overthinking it and have to divide it into two? -
Django `request.query_params.get("page")` returns None?
I use Next.js for front end and this is how I send the query params. export const getServerSideProps = wrapper.getServerSideProps( async (context) => { const { store, query } = context; console.log("params", query); store.dispatch(fetchProductsStart(query)); store.dispatch(END); await (store as SagaStore).sagaTask.toPromise(); const state = store.getState(); const productListState = state.productList ? state.productList : null; return { props: { productListState } }; } ); console.log("params", query) returns this object:"{ keyword: 'g', page: '1' }". This is what I am sending to backend. This is how I tried to get the params in the backend: @api_view(['GET']) def getProducts(request): q=request.query_params.get("page") print("page query param",q) query = request.query_params print("query_params",query) print("page query param",q) returns "None" print("query_params",query) returns "<QueryDict: {'[object Object]': ['']}>" I cannot figure out how to reach "keyword" and "page" query paramters inside django queryDict. -
How add categories in my webside with django?
Im beginner in django and im trying to make a webside. I want to filter the categories in my webside but i have a error (UnboundLocalError) when introduce the url in browser. models.py from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): nombre=models.CharField(max_length=50) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='categoria' verbose_name_plural='categorias' def __str__(self): return self.nombre class Post(models.Model): titulo=models.CharField(max_length=50) contenido=models.TextField() imagen=models.ImageField(upload_to='blog', null=True, blank=True) autor=models.ForeignKey(User, on_delete=models.CASCADE) categorias=models.ManyToManyField(Categoria) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='post' verbose_name_plural='posts' def __str__(self): return self.titulo urls.py from django.urls import path from . import views urlpatterns = [ path('',views.blog, name='Blog'), path('categoria/<int:categoria_id>/', views.categoria, name='categoria'), ] views.py from django.shortcuts import get_object_or_404, render from blog.models import Categoria, Post def blog(request): posts=Post.objects.all() return render(request, 'blog/blog.html', {'posts':posts}) def categoria(request, categoria_id): categoria=get_object_or_404(Categoria, id=categoria_id) return render(request, 'blog/categorias.html', {'categoria':categoria, 'posts':posts}) blog.html {% extends 'ProyectoWebApp/base.html' %} {% load static %} {% block content %} {% for post in posts %} <div class="intro"> <img class="intro-img img-fluid mb-3 mb-lg-0 rounded" src="{{post.imagen.url}}" alt="" style="width: 50%;"> <div class="intro-text left-0 text-center bg-faded p-5 rounded"> <h2 class="section-heading mb-4" > <span class="section-heading-lower">{{post.titulo}}</span> <span class="section-heading-upper">{{post.contenido}}</span> </h2> <div style="text-align: left; font-size: 0.8em;"> Autor: {{post.autor}} </div> </div> </div> </div> </section> {% endfor %} <div style="width: 75%; margin: auto; text-align: center; color: white;"> Categorias: {% for post in posts %} {% for … -
I'm not sure why im getting this async error in python
I managed to get my api request asynchronous but then received this error when trying to implement it into the main project. What does this mean that I have done wrong? ERROR Exception has occurred: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 124, in main await asyncio.wait([sigBuy(count) for count, bot in enumerate(activeBots)]) File "C:\Users\Admin\Desktop\djangoProjects\dguac\Signal.py", line 126, in <module> loop.run_until_complete(main()) I don't understand what this error means and how I would be able to fix it. Here is my code async def sigBuy(count): bot_dict = Bot.to_dict(activeBots[count]) sigSettings_dict = Bot.to_dict(activeBots[count].sigSettings) # Binance API and Secret Keys Bclient = CryptoXLib.create_binance_client(sigSettings_dict['API_key'], sigSettings_dict['API_secret_key']) p = round(float(percentage(7, bot_dict['ct_balance']) / (float(bin_asset_price['price']) / 1)), 8) # Round and Asign the asset_amount asset_amount = round(p, 2) # shouldILog = await makeBuy(market, asset_amount, Bclient, sigSettings_dict['base_currency']) shouldILog = 2 if shouldILog == 2: asset_amount = int(asset_amount) last_trade = await Bclient.get_all_orders(pair = Pair(market, sigSettings_dict['base_currency'])) last_trade = last_trade['response'][-1] print(last_trade) # asset_price = float(last_trade['cummulativeQuoteQty']) / float(last_trade['executedQty']) asset_price = 0.00000123 buyInPrice = float(last_trade['cummulativeQuoteQty']) for otrade in activeBots[count].opentrades.all(): trade = Bot.to_dict(otrade) del trade['id'] otradesUpdate.append(trade) openTrades_dict = {'bot_ID': bot_dict['id'], 'date': date, 'market': market, 'trade_mode': 'Buy', 'price': asset_price, 'amount': asset_amount, 'amount_in_base_currency': buyInPrice, 'result': 0} otradesUpdate.append(openTrades_dict) BotsUpdate.append(bot_dict) SigSettingsUpdate.append(sigSettings_dict) … -
Deploy Django on Docker app to PythonAnyWhere
I tried to deploy my project django on Docker app to (Python Anywhere) after i deployed when i press in the link it didn't open and this error appeared (Something went wrong 🙁 This website is hosted by PythonAnywhere, an online hosting environment. Something went wrong while trying to load it; please try again later There was an error loading your PythonAnywhere-hosted site. There may be a bug in your code. Error code: Unhandled Exception) These are the steps that I took: I changed the settings.py in api first--> ALLOWED_HOSTS = ['localhost','roka5.pythonanywhere.com'] and then in DATABASES 'NAME': str(BASE_DIR / 'db.sqlite3') then --> STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') and in terminal make collectstatic then i made a zip file and upload it in pythonAnywhere then decompressed it and then added a new web app and put source code in it and add some changes to configuration file related to Django and install library djangorestframework then i made a reload and then i tried to open the link but it didn't you can find settings.py code here: https://ideone.com/RjbfVp and configuration file code here: https://ideone.com/XPYOSb -
Why form with the ImageField is not valid in DJango?
I have model in Django which name is "User": class User(models.Model): user_id = models.AutoField(auto_created = True, primary_key = True, serialize = False, verbose_name ='ID') surname = models.CharField(max_length=100) name = models.CharField(max_length=100) patronymic = models.CharField(max_length=100) email = models.CharField(max_length=100) avatar = models.ImageField(upload_to='store/static/store/user_avatars/') Also I include columns of this model into my form: class UserForm(forms.Form): surname = forms.CharField(max_length=100) name = forms.CharField(max_length=100) patronymic = forms.CharField(max_length=100) email = forms.CharField(max_length=100) password = forms.CharField(max_length=100) avatar = forms.ImageField() View which gets that data: def sign_up(request): if request.method == 'GET': return render(request, 'store/sign_up.html') elif request.method == 'POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): user = User(surname=form.cleaned_data['surname'], name=form.cleaned_data['name'], patronymic=form.cleaned_data['patronymic'], email=form.cleaned_data['email'], avatar=form.cleaned_data['avatar']) user.save() return HttpResponse("Alright, you signed up! " + form.cleaned_data['email']) else: print(form.as_table()) return HttpResponse("Data is error!") And, finally, front of this view: <form method="post"> {% csrf_token %} <div class="user_data"> <div class="user_data_grid"> <input type="text" name="surname" placeholder="Surname" id="surname" style="grid-row: 2 / span 1"> <input type="text" name="name" placeholder="Name" id="name" style="grid-row: 3 / span 1"> <input type="text" name="patronymic" placeholder="Patronymic" id="patronymic" style="grid-row: 4 / span 1"> <input type="email" name="email" placeholder="Enter your mail" id="email" style="grid-row: 5 / span 1"> <input type="password" name="password" id="password" placeholder="Enter password" style="grid-row: 6 / span 1"> <input type="checkbox" id="checkbox" onclick="seePassword()" style="grid-row: 6 / span 1"> <label for="checkbox" style="grid-row: 6 / span 1"></label> <p … -
How can I define a ModelSerializer ChoiceField's choices according to object attribute?
My Beta model's stage field provides 5 choices. I want my serializer to not always accept all these choices but only some of them according to the serialized object's actual stage value. For example, if my_beta_object.stage == 1, then the serializer should expect (and offer) only stages 2 and 3, if my_beta_object.stage == 2, only stages 2 and 4, etc. # models.py class Beta(models.Model): class BetaStage(models.IntegerChoices): REQUESTED = (1, "has been requested") ACCEPTED = (2, "has been accepted") REFUSED = (3, "has been refused") CORRECTED = (4, "has been corrected") COMPLETED = (5, "has been completed") stage = models.ChoiceField(choices=self.BetaStage.choices) # serializers.py class BetaActionSerializer(serializers.ModelSerializer): stage = serializers.ChoiceField( # choices=? ) class Meta: model = Beta fields = ("stage",) How can I dynamically limit the choices of that field according to the serialized object's field value? -
How to trigger allauth.account.signals.user_signed_up signal using pytest?
I have a OneToOneField between my UserTrust model and django.contrib.auth.models.User that I would like to create whenever a new User registers. I thought on creating the UserTrust instance using the user_signed_up signal. I have the following code in my AppConfig def ready(self): # importing model classes from .models import UserTrust @receiver(user_signed_up) def create_usertrust(sender, **kwargs): u = kwargs['user'] UserTrust.objects.create(user=u) ... and this is in my pytest test @pytest.fixture def test_password(): return 'strong-test-pass' @pytest.fixture def create_user(db, django_user_model, test_password): def make_user(**kwargs): kwargs['password'] = test_password if 'username' not in kwargs: kwargs['username'] = str(uuid.uuid4()) return django_user_model.objects.create_user(**kwargs) return make_user @pytest.mark.django_db def test_my_user(create_user): user = create_user() assert user.usertrust.available == 1000 Still, the test fails with django.contrib.auth.models.User.usertrust.RelatedObjectDoesNotExist: User has no usertrust. What did I miss? -
python/django can't deploy to heroku
i get this error when i try to deploy my project on heroku i have followed a tutorial for proshop for him it worked fine without any issues but i get this error below -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed i already tried some of the mentioned stuff like heroku buildpacks:set heroku/python and have requirments.txt and procfile in my project -
Docker and Zappa: Wrong python path
I'm trying to run Django in a Lambda using Zappa and Docker, I'm following the instructions outlined here. Wwhen I run zappa deploy dev I keep getting the FileNotFound error below. It looks like my pythonpath and virtual environment path is wrong, and I've no idea how it got in there. I tried setting the pythonpath in my Dockerfile but with no luck. ============== Traceback (most recent call last): File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 2779, in handle sys.exit(cli.handle()) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 509, in handle self.dispatch_command(self.command, stage) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 546, in dispatch_command self.deploy(self.vargs['zip']) File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 718, in deploy self.create_package() File "/var/task/venv/lib/python3.7/site-packages/zappa/cli.py", line 2216, in create_package archive_format='tarball' File "/var/task/venv/lib/python3.7/site-packages/zappa/core.py", line 544, in create_lambda_zip copytree(cwd, temp_project_path, metadata=False, symlinks=False, ignore=shutil.ignore_patterns(*excludes)) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 63, in copytree copytree(s, d, metadata, symlinks, ignore) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 63, in copytree copytree(s, d, metadata, symlinks, ignore) File "/var/task/venv/lib/python3.7/site-packages/zappa/utilities.py", line 65, in copytree shutil.copy2(s, d) if metadata else shutil.copy(s, d) File "/var/lang/lib/python3.7/shutil.py", line 248, in copy copyfile(src, dst, follow_symlinks=follow_symlinks) File "/var/lang/lib/python3.7/shutil.py", line 120, in copyfile with open(src, 'rb') as fsrc: FileNotFoundError: [Errno 2] No such file or directory: '/var/task/env/bin/python' ============== This is my Dockerfile: FROM lambci/lambda:build-python3.7 LABEL maintainer="email@gmail.com" WORKDIR /var/task # Fancy prompt to remind you are in zappashell … -
no such table: app_user
im currently making a django rest framework web app for a client, the thing is that an error ocurred: File "E:\Co2\Trabajos\WarDogs\pagina-reload\env\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: api_usuario This is my Usuario model: from django.contrib.auth.models import AbstractUser from django.core.files import storage from django.db import models from api.utils import OverwriteStorage from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token # Create your models here. class Usuario(AbstractUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] def imgUsuario(self, *args, **kwargs): if self.usuario_img: data = {} for elemento in self.usuario_img.all(): if elemento.img: data["url"] = elemento.img.url data["id"] = elemento.id else: data["url"] = "" return data else: return "" And this my settings.py # Autenticacion de usuarios AUTH_USER_MODEL = 'api.Usuario' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.AllowAllUsersModelBackend', 'api.backends.CaseInsensitiveModelBackend', ) I tried this on python manage.py shell >> user = Usuario.objects.all() >> for u in user: >> u.id >> >> Error: django.db.utils.OperationalError: no such table: api_usuario Thank you guys! -
Ordering data, Paginator on django
The program I'm making is to display information about a product from the database. The program works fine, the problem is that I want to order by last name and not the "owner". For example. If the customer username is ewOI, which this is the "owner", and his name is Robert and last name is Bosh, I want to order the queryset by the last name and not the owner. Here is the views code: class ExpView(ListView): context_object_name = 'product' queryset = Product.objects.filter(prod__isnull=True).order_by('owner') template_name = 'productrecords.html' paginate_by = 10 there are two models, the one in product, and the one in user The product models: class Product(models.Model): owner = models.ForeignKey( User, on_delete=models.PROTECT, related_name='products' ) id_subscription = models.CharField(max_length=30, unique=True) amount = models.DecimalField(max_digits=11, decimal_places=2, null=True) interest_rate = models.DecimalField(max_digits=4, decimal_places=2) start_date = models.DateField(null=True) And the user models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True) second_name = models.CharField(max_length=32, blank=True) last_name2 = models.CharField(max_length=32, blank=True) recovery_email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=16, unique=True, null=True) Which for example if i go to the terminal and try to bring the query from the db: But I want to order_by('last_name') but that doesn't work. How can I order it? Thank you very much -
Django: Auto generate ID when form loads in a read only field
I want to generate a unique code base on month, year and number sequence for each transaction. Example 052101 Where 05 is the month, 21 is the year, and 01 is the count of number. The next code will be 052102 in that order. l want the generated code as value in a read only field when the form loads. -
Django - How to create a TableView out of many models that inherit same abstract class?
I'm trying to create a TableView that displays all objects in my project that inherit from the same abstract class. I know I may have needed to make the original class not abstract, but the project is already running and I'd rather not change the models now. The abstract class is this: class WarehouseBase(models.Model): region = models.ForeignKey(Region, on_delete=models.PROTECT, null=True, blank=False, verbose_name='Región') name = models.CharField(max_length=50, verbose_name='Nombre', unique=True) class Meta: abstract = True And the classes that inherit from it are: class SaleWarehouse(WarehouseBase): TYPES = ( (0, 'Autotanque'), (1, 'Estación de carburación') ) type = models.IntegerField(choices=TYPES, null=False, blank=False, verbose_name='Tipo') # price = models.ForeignKey(SpecificPrice, on_delete=models.SET_NULL, null=True, blank=True, related_name='warehouse') lat = models.DecimalField(max_digits=9, decimal_places=6, null=True) lng = models.DecimalField(max_digits=9, decimal_places=6, null=True) price = models.FloatField(verbose_name='Precio', validators=[MinValueValidator(0.0), MaxValueValidator(1000.0)], null=True, blank=True) price_date = models.DateField(verbose_name='Fecha de precio', null=True, blank=True, auto_now_add=True) def __str__(self): return '{} - {}'.format(str(self.pk), self.name) class GeneralWarehouse(WarehouseBase): @property def total_capacity(self): capacity = 0.0 for tank in self.tanks: capacity += tank.max_capacity return capacity def __str__(self): return "Almacén general '{}'".format(self.name) The new requirement for a view that enlists all warehouses was just added, but when the project was made this was not needed. I've been searching and I've found ways to change the database models so that I can make … -
Problem with AWS signature version 4 using Boto3 to send email
I'm trying to send an email using Django 2.2 and Boto3 (v 1.17.72) through SES. I created a new SMTP Credential (following this tutorial https://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html) and called the Boto3 service: client = boto3.client('ses', region_name=settings.AWS_SES_REGION_NAME, aws_access_key_id=settings.AWS_SES_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SES_SECRET_ACCESS_KEY) But when the applications try to send the email AWS return me this error message: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Could anyone help me to know how to fix it please? Thank you in advance, Andre. -
Generic detail view ProductListView must be called with either an object pk or a slug in the URLconf
can someone help me found the mistake with my code? I'm studing Django that's why can be possible that i made some stupid mistake or i forgot to write something. In my homepage i would like just to show a list of products but i immediately got this error! I already checked the topics here in SoF but i didn't found a solution. Models: from django.db import models class Manufacturer(models.Model): name = models.CharField(max_length=120) location = models.CharField(max_length=120) active = models.BooleanField(default=True) def __str__(self): return self.name class Product(models.Model): manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE, related_name="products") name = models.CharField(max_length=120) description = models.TextField(blank=True, null=True) photo = models.ImageField(blank=True, null=True) price = models.FloatField() shipping_cost = models.FloatField() quantity = models.PositiveSmallIntegerField() def __str__(self): return self.name This is my views: from django.views.generic.detail import DetailView from django.views.generic.list import ListView from .models import Product, Manufacturer class ProductDetailView(DetailView): model = Product template_name = "products/product_detail.html" class ProductListView(DetailView): model = Product template_name = "products/product_list.html" and this is the urls of my app: from django.urls import path from .views import ProductListView, ProductDetailView urlpatterns = [ path('', ProductListView.as_view(), name="product-list"), path('products/<int:pk>/', ProductDetailView.as_view(), name="product-detail"), ] Thanks for the help! -
How to get POST parameters in a Django view protected by @login_required?
Django's login_required decorator requires a login before proceeding to any functionality in a view function. If a user is not logged in, they will be redirected through a login screen. If the HTTP request is a GET, Django sometimes puts the GET destination in a parameter ("next"). Or, Django also has a LOGIN_REDIRECT_URL setting that is a URL a user is forwarded to after login. If the HTTP request is a POST, that POST data is lost during the login process. What is the best way to preserve the original URL and POST data for the original POST request, and re-post that data after the user is logged in? I imagine putting something in a session, but I'd have to intercept the POST data and URL on the way through login_required. The best practice is not obvious to me. -
How to make the login page the first page
I want to make the login page the first page appear to the user what should I write in the path? urlpatterns = [ # path('', views.home, name='home') #path('', HomeView.as_view(), name='home'), path('', ??? ,name='login'),# what I should I put here to make login page the first page appear path('like/<int:pk>',LikeView,name='like_post'), path('article/<int:pk>', ArticleDetailView.as_view(), name='article-details'), path('add_post/', AddPostView.as_view(), name='add_post'), path('add_category/', AddCategoryView.as_view(), name='add_category'), path('article/edit/<int:pk>', UpdatePostView.as_view(), name='update_post'), path('article/<int:pk>/remove', DeletePostView.as_view(), name='delete_post'), path('category/<str:cats>/', CategoryView, name='category'), path('category-list/', CategoryListView, name='category-list'), ] -
Unique constraints between two fields, no matter the order
The program has a table that represent the relation between two users: class Contact(models.Model): user_from = models.ForeignKey( "User", on_delete=models.CASCADE, related_name="rel_to_from", help_text=_("Person who sent the contact request"), ) user_to = models.ForeignKey( "User", on_delete=models.CASCADE, related_name="rel_to_set", help_text=_("Person who receive the contact request"), ) .... The problem is in the constraint, the constraints that i have defined so far are: .... class Meta: constraints = [ models.UniqueConstraint( fields=("user_from", "user_to"), name="%(app_label)s_%(class)s_unique_user_field", ), models.CheckConstraint( check=~models.Q(user_from=models.F("user_to")), name="%(app_label)s_%(class)s_unique_user_field", ), ] The first one check the unique constraint between (user_from, user_to) and the second check that the user_from is is different from user_to, but neither of the two prevents a contact from being created with the reversed roles, that is, if a relationship already exists where user_from=user1 and user_to=user2, nothing prevents user_from=user2 and user_to=user1 from being created. Exists some form to add this constraint? or the solution is to create the constraint only in the application layer?, like override the save method and check this constraints. -
How can I hide Celery tasks return
I'm working on a small project using Django / Celery for the first time, and my task return an object return user.objects.all() but i'm getting another thing also: Task apps.teams.tasks.createUserTenant[9cf731a8-b44f-4ac7-8b9f-3162df1b77ee] succeeded in 2.438217582181096s: <user: xyz@domain.com> how can i hide that and get just my own object since i'm using return user.objects.all() -
Passing a json count query, but only the amount counted for django
So basically, my issue is this json for the queried data2 passes the count number with the counted car brand, is there anyway i could only pass the counted part? Here is my view, with the queries class DadosDeGrafico1(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): data1 = DataDB.objects.values_list('marca').distinct() data2 = DataDB.objects.values_list('marca').annotate(marcas=Count('marca')) contexto = { 'data1':data1, 'data2':data2 } return Response(contexto) Basically the result of the query should be only 2 and 6 -
Verifying oauth users with custom backend in react native
My question is if we use @react-native-google-signin/google-signin then do we need to use both androidClientId from google console and webClientId? Because if we need to verify token from React.js web app we use the same token webClientId from console const { OAuth2Client } = require('google-auth-library') const client = new OAuth2Client(process.env.CLIENT_ID) as CLIENT_ID in backend here in above snippet as well as in front end as a client id. Do we need to create three clientId(s) in google console(ios, android, web), where web is for our backend so that we can send token from react-native front end to get verified?