Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST - rest_auth custom fields not being serialized
I'm using Django REST with the rest_auth package, and I'm having an issue with serializing custom fields when registering a new user. The field "is_employer" is always set to false even when you set it to true. Also in the API if you set the is_employer checkbox to true, it doesn't change anything. I added it in models, serializers and adapter, what am I missing? MODELS: class MyUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): username = None first_name = None last_name = None email = models.EmailField(verbose_name='email address', max_length=255, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_employer = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = MyUserManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(selfself, app_label): return True; SERIALIZERS: from django.contrib.auth.hashers import make_password from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from users.models import CustomUser class CustomRegisterSerializer(RegisterSerializer): def get_cleaned_data(self): … -
django multiple models with same foreign key
I have django app that is tracking contracts, locations, and products for various clients. Contracts, Locations each reference the client with a ForeignKey. class Location(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) ... class Contract(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) ... I also have a product that will be deployed in a location, on a contract, for a client. I need to include client in product because the reference is used to secure the record to that client. class Product(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) contract = models.ForeignKey(Contract, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) .... What is the best way to make sure a product is never created that contains a different client reference across all 3 models? I was thinking I could use a pre_save signal but I would rather use a database constraint but I don't see a database constraint to force this. -
Can't login as a user or admin in Django project even though password is right
In the admin panel when my password is right and I click on login it just reloads me to the same page and when my password is wrong it shows an error and in my project when I log in it takes me to the home page but not logged in. My settings file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECRET_KEY = '4uo!kh!^)!lc^xb0!&4aym-=%2(guhdfr^!2ly+rb0_!=@qnhx' SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '4uo!kh!^)!lc^xb0!&4aym-=%2(guhdfr^!2ly+rb0_!=@qnhx') # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['.herokuapp.com','127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'catalog' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'locallibrary.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'locallibrary.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators … -
TypeError in view: Field expected a number but got ' '
it's my first time posting a question in stack overflow so bear with me :D I'm trying to create a staff model from a form but an error keep persisting This is my models file : class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Consultant")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Consultant(models.Model): CHOICES = ( ('P', 'au paiement'), ('J15', 'J+15'), ('J30', 'J+30'), ) id = models.AutoField(primary_key=True) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) client_id=models.ForeignKey(Client,on_delete=models.CASCADE,default=1) tarif_facturation = models.IntegerField(blank=True, null=True) tarif_Consultant = models.IntegerField(blank=True, null=True) cnss = models.IntegerField(blank=True, null=True) rib = models.IntegerField(blank=True, null=True) paiement = models.CharField(max_length=300, choices=CHOICES) profile_pic = models.FileField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) objects = models.Manager() @receiver(post_save,sender=CustomUser) def create_user_profile(sender,instance,created,**kwargs): if created: if instance.user_type == 1: AdminHOD.objects.create(admin=instance) if instance.user_type == 2: Consultant.objects.create(admin=instance, client_id=Client.objects.get(id=1), tarif_Consultant="", tarif_facturation="", cnss="", rib="", paiement="") @receiver(post_save,sender=CustomUser) def save_user_profile(sender,instance,**kwargs): if instance.user_type==1: instance.adminhod.save() if instance.user_type==2: instance.consultant.save() My views: def add_staff_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: email=request.POST.get("email") password=request.POST.get("password") first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") client_id=request.POST.get("client") tarif_facturation=request.POST.get("tarif_facturation") tarif_Consultant=request.POST.get("tarif_Consultant") cnss = request.POST.get("cnss") rib = request.POST.get("rib") paiement = request.POST.get("paiement") #try: user=CustomUser.objects.create_user(username=username,password=password,email=email,last_name=last_name,first_name=first_name,user_type=2) client_obj=Client.objects.get(id=client_id) user.consultants.client_id=client_obj user.consultant.tarif_facturation=tarif_facturation user.consultant.tarif_Consultant=tarif_Consultant user.consultant.cnss=cnss user.consultant.rib=rib user.consultant.paiement=paiement user.save() Here is the Traceback : ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gestion'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'gestion.LoginCheckMiddleWare.LoginCheckMiddleWare'] Traceback (most recent call last): File "C:\Users\WD\Miniconda3\lib\site-packages\django\db\models\fields\__init__.py", … -
How to use saved card to pay with stripe?
I'm trying to build a checkout flow where the user can pay using a new card or a card that is saved to the customer object. I'm struggling on how to actually use the saved card details to create a charge. This is what I'm working with at the moment. I want for the user to be able to select one of the payment methods from radio and use that to create the payment, and if they choose new card, be able to use that form to add details view.py customer_id = user.userdetails.customer_id stripe.Customer.create_source( customer_id, source=token, ) charge = stripe.Charge.create( amount=standard_price, currency='usd', description=desc, receipt_email=request.user.email, customer=customer_id ) var stripe = Stripe('key'); // Create an instance of Elements. var elements = stripe.elements(); // Custom styling can be passed to options when creating an Element. // (Note that this demo uses a wider set of styles than the guide below.) // Create an instance of the card Element. var card = elements.create('card', { style: style }); // Add an instance of the card Element into the `card-element` <div>. card.mount('#card-element'); // Handle real-time validation errors from the card Element. card.on('change', function (event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } … -
Update profile with nested user in django rest framework
I need to update the Administrator object with the user in one request using a nested serializer. My views.py: class AdministratorDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Administrator.objects.all() serializer_class = AdministratorSerializer permission_classes = ( permissions.IsAuthenticated, custom_permissions.IsAdministrator | custom_permissions.IsHR | permissions.IsAdminUser, ) def put(self, request, *args, **kwargs): serializer = AdministratorSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status.HTTP_400_BAD_REQUEST) And serializers.py: class AdministratorSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Administrator fields = '__all__' def create(self, validated_data): user_data = validated_data.pop('user') password = User.objects.make_random_password() user = User.objects.create_user( password=password, is_administrator=True, **user_data ) admin_obj = Administrator.objects.create(user=user, **validated_data) send_password.delay(user.email, password) return admin_obj def update(self, instance, validated_data): user_data = validated_data.pop('user') print(user_data) user = instance.user for k, v in user_data.items(): setattr(user, k, v) user.save() for k, v in validated_data.items(): setattr(instance, k, v) instance.save() return instance But I got 400 Bad Request: { "user": { "email": [ "user with this email address already exists." ] } } Where had I gone wrong? Why does it want to create a new user on put request? -
Importing contents of text file into postgresql database using Django
I am currently working on a project where I need to import contents of text file(with no-header & fixed width fields) into a database table (postgresql) using Django Framework. What is the best way to make the imports or any other utility that would suffice the requirements? -
How to implement some feature? [closed]
I want to create the social network that should work as Reddit, but idk how to implement one thing. I did Communities model(subreddits) and also did Posts model. And it works fine, but i want to add the feature that will let you to create posts not only for one of the communities, but also for your profile, I mean that check this image class Community(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, null=True, blank=True) description = models.TextField(max_length=500) cover = models.ImageField(upload_to='c_covers/', blank=True, null=True) admins = models.ManyToManyField(User, related_name='inspected_c') subscribers = models.ManyToManyField(User, related_name='subscribed_c') banned_users = models.ManyToManyField(User, related_name='forbidden_c') created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, null=True, blank=True) body = models.TextField(max_length=5000, blank=True, null=True) photo = models.ImageField(upload_to='post_photos/', verbose_name=u"Add image (optional)", blank=True, null=True) author = models.ForeignKey(User, related_name='posted_p', on_delete=models.CASCADE) community = models.ForeignKey(Community, related_name='submitted_p', on_delete=models.CASCADE) points = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='liked_p', blank=True) mentioned = models.ManyToManyField(User, related_name='m_in_posts', blank=True) rank_score = models.FloatField(default=0.0) active = models.BooleanField(default=True) created = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now=True) -
OperationalError at /admin/login/ no such table Django
I am getting the following error whenever I try to sign in into Django's admin dashboard, I type in my username & password to login, I get the following error: OperationalError at /admin/login/ no such table: myapp_myuser Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such table: myapp_myuser settings.py AUTH_USER_MODEL = 'myapp.MyUser' models.py class MyUser(AbstractUser): id = models.UUIDField(primary_key= True, default= uuid.uuid4, editable= False) first_name = models.TextField(max_length= 25) last_name = models.TextField(max_length= 25) email = models.EmailField(unique= True) class MyModel(models.Model): user = models.ForeignKey(AUTH_USER_MODEL, on_delete= models.CASCADE, null= True) user_folder = models.FileField(upload_to= create_user_folder, null= True) Thanks in advance. -
Heroku duplicate key value violates unique constraint (django)
Today I deployed my django app on Heroku for the first time (following this tutorial). The problem is that when I want to modify or add something to the database, I get an Integrity Error which says: duplicate key value violates unique constraint "app_professore_pkey" Where Professore is the name of the Model I tried to modify. I’ve searched a bit online and I’ve seen that probably is because I developed the app on my PC using SQLite and now, on Heroku, it uses PostgreSQL, and those 2 databases works differently. Actually, I don’t have a lot of experience with databases (almost no experience) so I don’t know how to fix this... Maybe modifying something on the Professore model? Or typing something in the Heroku console? This is the error screen I get, if you need it to help me :) Thanks in advance and tell me if I wasn’t clear on something (I’m new to StackOverflow too) -
How can I submit html5 user location to django view using ajax or form?
I am trying to submit a user location to Django class based view using either ajax or form. But my understanding of Javascript and ajax is limited. How can i submit html5 user location to django cbv? views.py: class UserProfileView(CreateView): model = UserProfile fields = ['user_location'] template_name = 'rent_app/user_profile.html' html: {% block content %} <body> {% leaflet_map "map" callback="ourfunction" %} <div id="sidebar" class="sidebar collapsed"> <form method="POST" action="{% url 'rent_app:add-location' %}"> {{ csrf_token }} {% form.as_p %} </form> </div> <script type="text/javascript"> var collection = {{ object_list|geojsonfeature:"popupContent"|safe }}; console.log(collection); function onEachFeature(feature, layer) { if (feature.properties && feature.properties.popupContent) { layer.bindPopup(feature.properties.popupContent); } } function ourfunction(map, options) { map.locate({setView: true, maxZoom: 16}); map.on('locationfound', onLocationFound); function onLocationFound(e) { var radius = e.accuracy; var position= e.latlng; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point").openPopup(); L.circle(e.latlng, radius).addTo(map); } function onLocationError(e) { alert(e.message); } map.on('locationerror', onLocationError); L.geoJson(collection, {onEachFeature: onEachFeature}).addTo(map); } </script> forms.py: class UserProfileModelForm(forms.ModelForm): class Meta: model = UserProfile fields = ('id', 'user_location') widgets = {'geom': LeafletWidget(),'e':forms.HiddenInput()} -
Troubling accessing media on AWS S3, ERROR 403, on Django app
I am having trouble accessing media files uploaded on AWS S3 for my Django app. I was attempting to use Boto3 and Django-Storages libraries and followed these tutorials: https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html https://www.youtube.com/watch?v=kt3ZtW9MXhw Both the Django Admin website and my front-end website are not able to load any of the static and media content. The Django admin is rendered without any CSS, and similarly my front-end has no images. AWS Configurations were added to the settings.py file: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_S3_REGION_NAME = "me-south-1" AWS_STORAGE_BUCKET_NAME = 'jooler-mea' AWS_S3_CUSTOM_DOMAIN = '%s.s3.me-south-1.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_STATIC_LOCATION = 'static' STATICFILES_STORAGE = 'joole.storage_backends.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION) DEFAULT_FILE_STORAGE_LOCATION = 'media' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'joole.storage_backends.MediaStorage' The relevant storages in storage_backends.py file: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.AWS_STATIC_LOCATION class MediaStorage(S3Boto3Storage): location = settings.DEFAULT_FILE_STORAGE_LOCATION file_overwrite = False I added S3FullAccess: The files are successfully uploading to the AWS website, I can download the files from there to my computer. I tried playing around with CORS and custom policies but have not been successful. I've hit a dead end or not sure where to go from here. Any help would … -
Possible to use distinct() with attributes created via extra() in Django ORM?
Let's say you have the following Django ORM query: cars = CarModel.objects.only( 'car__car_id', 'car__cardate', 'car__title', 'car__location', 'car__quote', 'car__key', 'car__cartype_id', 'maker__lastname', 'maker__firstname', 'maker__middlename', 'maker__nickname', ).select_related( 'car', 'maker', ).extra( select={ 'is_position_paper': 'cartype_id = 7', 'is_null_date': 'cardate IS NULL', 'shorttitle': extra, }, ).filter(**kwargs).distinct(sort_order_for_distinct, 'car__car_id').order_by(sort_order, 'car__car_id') My understanding is that, whatever I've included in order_by() I have to also include, in the same order, in distinct(). However, distinct doesn't like the attributes being created in extra(). If I try and include these attributes in the order_by() as I would like, such as: .order_by('is_position_paper', 'is_null_date', sort_order, 'car__car_id') I get the error: Cannot resolve keyword 'is_position_paper' into field So that means that the attributes created via extra() just aren't going to be available to use with distinct()? Is there any alternative approach here? Really all I'm trying to do is dedupe this entire queryset by car__car_id, that's it, whilst having order_by('is_position_paper', 'is_null_date', sort_order, 'car__car_id') Unfortunately I'm stuck on Django 2.1 with this. Also, using Postgres as the db. -
How can i have multiple dictionaries inside dictionary with same key? [closed]
Title: multiple dictionaries inside dictionary with same key example: all_dict={'a':{{'id':1},{'id':2},{'id':3}}} -
How to check multiple states before transition in python django finite state machine
Below is my code a.py: from django.db import models from django_fsm import transition, FSMIntegerField from django_fsm import FSMField, transition import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import django django.setup() from django.core.management import call_command class Order(models.Model): STATUS_STARTED = 0 STATUS_SLOW =1 STATUS_FAST=2 STATUS_JUMP=3 STATUS_CHOICES = ( (STATUS_STARTED, 'STARTED'), (STATUS_SLOW,'SLOW') (STATUS_FAST,'FAST') (STATUS_JUMP,'JUMP') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices=STATUS_CHOICES, default=STATUS_STARTED, protected=True) A person STARTED from a point & he is either FAST or SLOW. @transition(field=status, source=[STATUS_STARTED], target=STATUS_FAST) def fast(self): print("person run fast") @transition(field=status, source=[STATUS_STARTED], target=STATUS_SLOW) def slow(self): print("person run slow ") Person in FAST state can switch to SLOW state & can JUMP: @transition(field=status, source=[STATUS_FAST], target=STATUS_SLOW) def switch(self) print("state switched") @transition(field=status, source=[STATUS_FAST, STATUS_SLOW], target=STATUS_JUMP) def jump(self) print("person jumpped") but I have condition that person who STARTED from the point with SLOW state cannot JUMP. from FAST state, he can SLOW & JUMP, but not directly from STARTED--> SLOW-->JUMP is possible. But when i run above code: >>person = Order() #input >>person.slow() # Input >> person run slow # output >>person.jump() # Input >>person jumpped # output but expected transition error. And i found that its because, FSM will maintain the last state alone & as per jump(), from SLOW to JUMP get executed.. Got stuck … -
Conection Agular 10 + Django Api Rest no render objetcs
im trying use Django rest + angular 10, i will show a list of providers in the browser, could someone explain to me why my django api rest objects are not rendering? appear in console but not in html. im using angular 10, django 2.7, cors, and my localhost. this is my code. // app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } //app.component.html <div *ngFor='let provider of providers'> <h2>{{ provider.name | uppercase }}</h2> <p>{{ provider.procedence }}</p> <p>{{ provider.email }}</p> <p>{{ provider.telephone }}</p> </div> // app.component.ts import { Component, OnInit } from '@angular/core'; import { ProviderService } from './provider.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'conexion'; providers: any[] = []; constructor( protected ProviderService: ProviderService ) { } ngOnInit() { this.ProviderService.getProviders() .subscribe( (data) => { // Success this.providers = data['results']; console.warn(data) }, (error) => { console.error(error); } ); } } // app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule} from '@angular/common/http'; import { ProviderService } from './provider.service'; import { AppComponent } from … -
Relational field not updating from Django view
Foreign Key field doesn't update from django view. When i run my test cases, all model test cases runs successfully. When same code is utilized in view, my test case Fail. What am I doing wrong ? I'm using django 3.1.1 and djangorestframework 3.11.1. # models.py class Request(models.Model): status = models.CharField(max_length=1, choices=( ('I', 'Initiating'), ('C', 'Connecting'), ('P', 'Peered')), default='I') class Client(models.Model): name = models.CharField(max_length=100, blank=False, null=False) request = models.ForeignKey(Request, on_delete=models.CASCADE, related_name='clients') class Server(models.Model): type = models.CharField(max_length=100, blank=False, null=False) client = models.OneToOneField(Client, on_delete=models.CASCADE) # views.py # view path ( app_name:path_name ) --> domain:server-peer-request class ServerViewSet(viewsets.ViewSet): model = models.Server .... @action( detail=True, methods=['post',], url_name='peer-request', url_path='peer-request') def peer_server_to_clientrequest(self, request, pk): """This view updates a server instance underlying request status""" server = get_object_or_404(self.model, pk=pk) server.client.request.status = 'P' server.client.request.save() print(server.client.request.status ) # outputs **P** return Response(status=status.HTTP_200_OK) # test_models.py class ServerModelTestCase(TestCase): def setUp(self): # some model instances here e.g (self.client_one -- Client model), (self.request -- Request model) def test_relational_fields_can_update(self): server = models.Server.objects.create(type='microT2', client=self.client_one) self.assertEqual(server.client.request.status, 'I') # 'I' is the default, so test passes server.client.request.status = 'P' server.client.request.save() self.assertEqual(server.client.request.status, 'P') # This test pass # These other test are just to confirm the the instance is updated globally self.assertEqual(self.request.status, 'P') # This test pass self.assertEqual(self.client.request.status, 'P') # … -
django adds unwanted key to my users table. How do I get rid of it at the source?
Latest Django. When I look at the database I see the following keys created for my users table: I am responsible for explicitly adding the user_unique_email_delete_token using the UniqueConstraint on my User model -- as my Users are soft-delete, but I have no idea where users_email_key comes from or how I can stop it from being created. It gets in the way of me having two records with identical email but different delete_token (on soft deleted rows). This should be perfectly ok in my app. Any ideas how I can get rid of this key, and not by modifying the database schema externally? I need it not to be created in the first place with migrate. -
AWS-Xray SDK is not getting disable in Python
I have a XRAY_RECORDER dict in the setting.py file of Django. Where I have different settings for AWS Xrays like Daemon address, tracing name etc. In the same dict I also mentioned 'AWS_XRAY_SDK_ENABLED': False. In short, I want to disable AWS Xray SDK for my application. But it still sends traces in spite of setting it to False. Although I can turn it off using global_sdk_config.set_sdk_enabled(False) but due to requirements constraint, I have to enable or disable it via environment variables. Can anyone please suggest a solution to turn it off? -
Getting error as: SchoolDetailsView is missing or override SchoolDetailsView.get_queryset, what should I fix in below code?
Model.py class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School, related_name='students', on_delete=models.CASCADE) def __str__(self): return self.name Views.py class SchoolDetailsView(DetailView): context_object_name = 'school_detail' models = models.School template_name = 'basic_app/school_details.html' html code code looks like below mentioned in comments Can anyone suggest what am I missing here? -
How to add a ForeignKey to an unmanaged model in Django?
I have 2 models as shown below: class Client(models.Model): name = models.CharField(max_length=50) class Meta: managed=False class Store(models.Model): name = models.CharField(max_length=50) match = models.ForeignKey('Client', on_delete=models.CASCADE) When I run migrations, I get the below error. django.db.utils.ProgrammingError: relation "client" does not exist How can I fix this? I am using django 3.1 and Postgres 12 as my production db. -
Django how to change a form field based on failed validation
I'm trying to protect a signup process in Django using Recaptcha. Currently I am using the django-captcha library for this. Unfortunately v2 of ReCaptcha annoys a lot of people, why I switched to v3. Now looking for the form to adopt based on a failed score in Recaptcha v3 to fall back to v2. Code looks currently something like this: from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 class AccountForm(forms.ModelForm): name = forms.CharField(validators=[MinLengthValidator(3)], error_messages={'invalid':_("Please enter a name.")}) terms = forms.BooleanField() # ReCaptcha v2 #captcha = ReCaptchaField( # public_key= settings.RECAPTCHA_PUBLIC_KEY, # private_key= settings.RECAPTCHA_PRIVATE_KEY, #) # Recaptcha v3 captcha = ReCaptchaField( public_key=settings.RECAPTCHA_PUBLIC_KEY_V3, private_key=settings.RECAPTCHA_PRIVATE_KEY_V3, widget=ReCaptchaV3( attrs={ 'required_score': 1.0, } ) ) So nothing there yet. What I try to achieve is a failing v3 to show the v2 instead. This is more a general question if it is possible and where to start. Thanks -
Angular universal SSR not displaying the angular assets folders images while serving it from Django
I have used Angular Universal for SSR(Server Side Rendering) of my angular application. The steps that I followed so far: First I created my angular app and then add angular universal and run "npm run build:ssr" to build it and "npm run serve:ssr" to test it. Untill this point all good. I got 2 folders namely "browser" "server" and "server.js" file. Browser folder contents are equivalent to dist folder content what we usually get by ng build --prod. But I have done the same but using Angular Universal. Now coming to the Django part: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, '<my_proj_dir>/static'), ] I have also created a simple app to render the index.html page of angular: class FrontEndRenderView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) Next I copy my browser i.e dist folder content inside the above app template(only the index.html) and static files(different js scripts) Next I ran the python manage.py collectstatic to get all my static files into the root directory static folder which I already set in the settings.py and serve it from there. Modified the index.html: {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> … -
Getting function from model and putting it to serializer
I have Django project. I have model and serializer and I'm trying to send the result of my function "increase_id" from model to serializer. What I'm doing wrong? How I can to implement it? class Person(models.Model): age = models.PositiveIntegerField() first_field = models.CharField() second_name = models.CharField() def increase_id(self): own_id = self.id magnifier = own_id + 50_000 return magnifier serializer: class PersonSerializer(serializers.ModelSerializer): magnifier = serializers.IntegerField(source='increase_id') class Meta: model = Person fields = ('id', 'first_name', 'second_name', 'age', 'magnifier') -
Sidebar not working fine in Django html template
Problem - When i reload the web page first the menu of sidebar will display then proper view of sidebar will display. how to overcome this problem . i'm not able to post the code because its too complex . if any body have an idea about the issue please suggest me