Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-safedelete 1.3.0 - Cannot migrate
I built an internal app that used django-safedelete. I was working fine for months, until i recently upgraded my distro, and tried to add a field to my model. I also upgraded my python modules, everything is up-to-date, and no errors during the upgrade. Now I cannot migrate anymore: if I "makemigrations" I get an error message "django.db.utils.OperationalError: (1054, "Unknown column 'gestion_ltqmappsetting.deleted_by_cascade' in 'field list'")" if I add a boolean "deleted_by_cascade" field in my ltqmappsetting table, then the "makemigration" works, but the "migrate" fails with "MySQLdb.OperationalError: (1060, "Duplicate column name 'deleted_by_cascade'")" I tried removing the field after makemigrations, but the migrate fails with the first error message. I also tried removing the "migration" operations in the 0087...migration.py file, but it does not have any impact. Is there anyway to update the migration file between the makemigrations and the migrate commands ? Thanks a lot for any help on this. jm -
Is this security concept suitable for ehealth records webapp?
I'd like to hear your opinion on my application design regarding data security. Context & Build Steps Personal electronic health records, main purpose of app is storage (read-only). The application will be used by staff. data exchange with third parties. Users will extend to external staff. Mobile App for visualisation of health records. Users will have access to their data (read-only) Stack Backend: python+django (webapplication) DB: postgresql // Divided in two groups personal data (like name, age, adress, ...) and health records (reports, lab values, ...). health records are only files, no database records in that sense (db will have path reference in on column). All of the health records are stored in the aws S3 bucket. Host: heroku + aws S3 bucket for file storage Thoughts & Considerations The app will come with a authentification and authorisation functionality. I consider the health records with higher priority regarding data security than personal data. So what I was thinking is to upgrade my heroku server with heroku shield services which would add security features server-side and make breaches from that side harder. Additionaly I would like to use the encryption service of aws bucket to encrypt all the files in the … -
no module named pars when executing python3 script directly
pars in the django app I have made under INSTALLED_APPS within settings.py When i run this python script directly from bash that includes: from django.db import models from pars.models import tbl1, tbl2, etc technologytitle=soup.find("h1").text try: technology=CMS(nm=technologytitle) technology.save() print("saved techology: {}".format(technologytitle)) except IntegrityError as e: print("Integrity error occurring with saving: {} {}".format(technologytitle, e)) Im getting an error of: ModuleNotFoundError: No module named 'pars' ive done a ton of research, but cant seem to figure out why this is happening. Thanks -
IntegrityError at / null value in column "last_name" violates not-null constraint
I have web app which includes authentication. I have form, but when I enter my credentials and click submit I get an error: IntegrityError at /accounts/professor_register/ null value in column "last_name" violates not-null constraint. view from .forms import ProfessorSignupForm class ProfessorSignup(CreateView): model = User form_class = ProfessorSignUpForm template_name = 'authentication/dubai.html' def form_valid(self, form): user = form.save() login(self.request, user) return redirect('/') form class ProfessorSignUpForm(UserCreationForm): first_name = forms.CharField() last_name = forms.CharField() phone = PhoneNumberField() class Meta(UserCreationForm.Meta): model = User @transaction.atomic def save(self): user = super().save(commit=False) user.is_professor = True user.is_staff = True user.save() professor = Professor.objects.create(user=user) professor.first_name = self.cleaned_data.get('first_name') professor.last_name = self.cleaned_data.get('last_name') professor.username = self.cleaned_data.get('username') professor.email = self.cleaned_data.get('email') professor.password = self.cleaned_data.get('password') professor.save() return user models class User(AbstractUser): is_pupil = models.BooleanField(default=False) is_instructor = models.BooleanField(default=False) class Professor(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) first_name = models.CharField(max_length=20, null=False) last_name = models.CharField(max_length=30, null=True) username = models.CharField(max_length=30, unique=True, null=True) email = models.EmailField(unique=True, null=False) password = models.CharField(max_length=60, null=False) phone_number = PhoneNumberField(null=False, blank=False, unique=True) I am using postgresql as database. I have no idea why this is happening. Every stack answer I tried to replicate gives me another error:( -
How to display data from Rest API in a template
I made an API using Django Rest Framework and I've been able to use it to create come charts using ChartJS. In the same API, after the data used for the charts I have some other data that I want to be displayed simply as a number in the same Django template, but I'm really unsure on how to do that. My API: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { (...CHARTS.JS DATA...) "total_employees": 1, "total_vehicles": 3, } I have already imported the data into the template together with the data I used for the charts. Template: <script> {% block jquery %} var endpoint = '/api/chart/data/' (Chart.JS part) var totalemployees = [] var totalvehicles = []; $.ajax({ method: "GET", url: endpoint, success: function(data){ (Chart.JS data here...) totalemployees = data.totalemployees totalvehicles = data.totalvehicles (ChartJS stuff here...) }, error: function(error_data){ console.log("error") console.log(error_data) } }) (Other ChartJS stuff here...) {% endblock %} </script> I would like to do something like this in the template: <h3 class="text-center m-4">Total number of employees: ("total_employees" value (which in this case is 1)</h3> <h3 class="text-center m-4">Total number of vehicles: ("total_vehicles" value (which in this case is 3)</h3> -
Django Sessions Loose Data with url containing target="_blank"
In my django app, I store the current breadcrumb data (an array) in the session object. When I have a link that includes target="_blank", the session data is lost. I assume this is normal operation, but just want to check that this is true. Any suggestions on where to store the breadcrumb array if I need to retrieve it when I use target="_blank" in my urls as well as whenever a page loads? Keep in mind, the breadcrumb data is on a per user basis. Thanks! -
GitHub App - User Authentication/Authorization through GitHub APIs
I am new to GitHub Apps. I have used GitHub OAuth before, but finding it a bit difficult to understand the user authentication and authorization for GitHub Apps. My use case is as follows - A user will visit my website, login with their GitHub credentials and at that time the user needs to accept the permission I seek from their profile (ex. Repository, PRs, etc.) and display those repositories and PR on my website and perform some actions on them. I have primarily 1 question at a high level. The API endpoints and what all keys are needed to authenticate and authorize a user so as to get all the requested items like repositories etc. and more importantly the next time the user logs in he should not need to accept the permission to access his repositories. (Similar to this codefactor site) I would like to have an architecture level solution if not a code example. I am using Python (Django) to build my project but code examples in other languages are also welcomed. -
success_url not working with url that-has/<int:pk>
The success_url is workin fine with a url that has-no/int:pk but does not work with a url that has /int:pk throws an error NoReverseMatch: Reverse for 'read_bty'. Views.py class HBTYOrderView(BSModalCreateView): template_name = 'accounts/modals/hairbty/create_hbty.html' form_class = HairbtyOrderForm success_message = 'Success: Order was created.' success_url = reverse_lazy('read-bty') Urls.py path('create_btyorder/', views.HBTYOrderView.as_view(), name='create_btyorder'), path('read_bty/<int:pk>', views.HBTYReadView.as_view(), name='read_bty'), -
ajax response can be seen fine in the alert box but can't print it out get undefined instead
I am trying to print out the response to an ajax request. I am getting a "undefined" when (down there) I write ${obj[property][0]} it follows the index to 1, 2 etc I can see both in the console and by alert-ing the response (data) that it does send the correct data in the form of a dictionary although it surely is json because that is what I send as response (and that is what web tools shows). However if I alert-out the "obj" I get "object" but can't see real values This is the ajax call: $(document).ready(function(){ // open document ready $('.botontest').on('click',function(){ // opening click function var value = $(this).val() alert(value); $.ajax({ // opening ajax obviously url:"{% url 'bill' %}", type:'POST', data:{'name':value, csrfmiddlewaretoken: '{{csrf_token}}'},// closes data field datatype:'json' }).done(function(data) { obj = JSON.parse( data); alert(data); // it prints me all data alright in the "alert" box // I leave out the headers. for (const property in obj) { tableHTML += "<tr><td>" tableHTML += `${property}</td> <td>${obj[property][0]}</td><td>${obj[property][1]}</td>\ <td>${obj[property][2]}</td><td>${obj[property][3]}</td><td>${obj[property][4]}</td><td>${obj[property][5]}</td>\ <td>${obj[property][6]}</td><td>${obj[property][7]}` tableHTML += "</td></tr>" } tableHTML += "</tbody></table>" //place the tableHTML in the document $("#respuesta").html(tableHTML); }); // closing ajax group console.log(value); }); // closing the click function });// closing document ready </script> My response … -
Custom manager in Django MultiDB
I'am using MySQL and PostgreSQL in my Django project. Below are the settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysql_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname', 'PORT': '3306', }, 'postgres_db': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'pgsql_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'hostname', 'PORT': '5432', } } And this is the sample model from postgres_copy import CopyManager class Items(models.Model): class params: db = "postgres_db" sales_value = models.CharField(max_length=255, null=True, blank=True) primary_email = models.CharField(max_length=255, null=True, blank=True) objects = CopyManager() I want to use Items.objects.all().to_csv('./path/to/csv) this ORM to export model data to CSV. I have used this before in exporting large dataset to csv. But in this configuration it gives below error psycopg2.errors.SyntaxError: syntax error at or near "." LINE 1: COPY (SELECT `sales_item`.`id`, `sales_item`.`sales_value`,... This seems to be an issue with multiDB. If I run this ORM in single DB configuration, or even if I set default alias on PostgreSQL this works fine. CopyManager seems to be getting default alias somehow which I have no idea about. How can I run this ORM in current settings without any issues? Any help would be appreciated. Thanks in advance. -
Building a dynamic asynchronous filesystem in django: best practices
I am trying to rebuild our website in Django, and I am currently facing a series of rather difficult challenges for which I am not prepared. I was hoping to get some help in the matter. The website I am building is an online archival platform for artists called Lekha. The core of Lekha is the dashboard page (which you can check out on this link, just sign in with the email stacko@test.com and the password test if you have the patience). On the dashboard page, users have access to a hierarchical filesystem that we would like to function like a desktop filesystem for ease of use. Users can use the filesystem to organize their 'artworks' into folders. These artworks themselves are a collection of media, along with the metadata of the artwork. To upload this media and fill in the metadata, users will use a form. If users want to edit an artwork's metadata, they can do so through an auto-populated form on the same page. The issue that I am facing is that I am struggling to find an elegant way to make all of this happen without reloading the page. Users need to be able to add, … -
relation does not exist while testing django tenant
I would like to use Selenium for my test. But when I try to connect to my tenant and then create a basic django User, I got the relation does not exist error. I suppose that because I'm in a test, the migrations to my tenant are not made but I can't figure out how to do this. my test.py class VisitCreationTestCase(StaticLiveServerTestCase): fixtures = ['save.json'] def check_connect(self, driver): driver.get(self.live_server_url.split("localhost")[0] + Domain.objects.first().domain + self.live_server_url.split("localhost")[1]) title = driver.title username = driver.find_element(by=By.NAME, value="login") password = driver.find_element(by=By.NAME, value="password") submit_button = driver.find_element(by=By.CSS_SELECTOR, value="button[type='submit']") connection.set_tenant(Client.objects.first()) User.objects.create(username="demo", password="testmdpusee") username.send_keys("demo") password.send_keys("testmdpusee") submit_button.click() driver.implicitly_wait(1) driver.find_element(by=By.XPATH, value="//p[contains(text(),'Aucun dossier ou fichier')]") def setUp(self) -> None: service = ChromeService(executable_path=ChromeDriverManager().install()) self.driver = webdriver.Chrome(service=service) self.check_connect(self.driver) my save.json [ { "model": "client.client", "pk": 1, "fields": { "schema_name": "demo", "nom": "demo", "logo": "", "raison_social": "a", "SIRET": "b", "TVA": "c", "adresse": "d", "code_postal": "e", "ville": "f", "numero_de_telephone": "g", "adresse_email": "h", "credit": 999998, "iparco_token": "i", "sender_password": null, "sender_mail": null, "sender_host": "ssl0.ovh.net", "sender_port": "587", "created_on": "2022-09-06" } }, { "model": "client.domain", "pk": 1, "fields": { "domain": "demo.localhost", "tenant": 1, "is_primary": true } } ] If anyone has ever encountered this problem, I have no more idea to solve this... -
How to get logged in user in django from custom users model
I want to get username from custom users model My Custom Users model: class Account(AbstractBaseUser, PermissionsMixin): nickname = models.CharField(max_length=150, unique=True) name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) phone = models.CharField(max_length=50, unique=True) date_of_birth = models.DateField(blank=True, null=True) picture = models.ImageField(blank=True, null=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) last_login = models.DateTimeField(null=True) admin_of_company = models.ForeignKey('companies.company', on_delete=models.CASCADE, default=None, blank=True, null=True) objects = AccountManager() USERNAME_FIELD = 'nickname' REQUIRED_FIELDS = ['name', 'last_name', 'phone'] def get_full_name(self): return self.name, self.last_name def get_short_name(self): return self.name.split()[0] and products model: class products(models.Model): name = models.CharField(max_length=150) about = models.TextField() price = models.IntegerField() picture = models.ImageField(default=None) admin = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) in products.admin I want to set default logged in user but I don't know how to get this data from custom users model -
Error in deploying Django app on Google cloud using appengine "django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable"
I am trying to deploy my own django app on google cloud. I'm following this documentation by Google Cloud to deploy the app. I have changed the settings.py file of my app according to the settings.py file of the sample app provided by Google. I have created a Django environment file as a Secret Manager secret by following the same documentation. its format is echo DATABASE_URL=postgres://DATABASE_NAME:DATABASE_USER_PASSWORD@//cloudsql/PROJECT_ID:REGION:INSTANCE_ID/CRRathod > .env echo GS_BUCKET_NAME=my-portfolio-361305_crrathod-bucket >> .env echo SECRET_KEY=$(cat/dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env After entering next command as documentation python manage.py makemigrations I'm getting errors as (env) C:\Program Files (x86)\Google\Cloud SDK\Portfolio-blog>python manage.py makemigrations Invalid line: echo DATABASE_URL=postgres://DATABASE_NAME:DATABASE_USER_PASSWORD@//cloudsql/PROJECT_ID:REGION:INSTANCE_ID/CRRathod > .env Invalid line: echo GS_BUCKET_NAME=my-portfolio-361305_crrathod-bucket >> .env Invalid line: echo SECRET_KEY=$(cat/dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env Invalid line: echo DATABASE_URL=postgres://CRRathod:CRroot@123@//cloudsql/my-portfolio-361305:asia-south1:crrathod/CRRathod > .env Invalid line: echo GS_BUCKET_NAME=my-portfolio-361305_crrathod-bucket >> .env Invalid line: echo SECRET_KEY=$(cat/dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env Invalid line: echo DATABASE_URL=postgres://CRRathod:CRroot@123@//cloudsql/my-portfolio-361305:asia-south1:crrathod/CRRathod > .env Invalid line: echo GS_BUCKET_NAME=my-portfolio-361305_crrathod-bucket >> .env Invalid line: echo SECRET_KEY=$(cat/dev/urandom | LC_ALL=C tr -dc '[:alpha:]'| fold -w 50 | head -n1) >> .env Traceback (most recent call last): File … -
Convert multiple level list of nested dictionaries into single list of dictionaries
I want to convert multiple level list of nested dictionaries into a single list of dictionary input: list_ = [ {'Name': 'Paras Jain', 'Student': [{'Exam': 90, 'Grade': 'a', 'class': [{'age': 10, 'subject': 'hindi'}, {'age': 11, 'subject': 'maths'}]}, {'Exam': 99, 'Grade': 'b', 'class': [{'age': 14, 'subject': 'evs'}, {'age': 15, 'subject': 'science'}]}, {'Exam': 97, 'Grade': 'c', 'class': [{'age': 10, 'subject': 'history'}]}]}, {'Name': 'Chunky Pandey', 'Student': [{'Exam': 89, 'Grade': 'a', 'class': [{'age': 9, 'subject': 'no'}]}, {'Exam': 80, 'Grade': 'b', 'class': []}]} ] Required output: [{'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 10, 'subject': 'hindi'}, {'Exam': 90, 'Grade': 'a', 'Name': 'Paras Jain', 'age': 11, 'subject': 'maths'}, {'Exam': 90, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 14, 'subject': 'evs'}, {'Exam': 90, 'Grade': 'b', 'Name': 'Paras Jain', 'age': 15, 'subject': 'science'}, {'Exam': 97, 'Grade': 'c', 'Name': 'Paras Jain', 'age': 10, 'subject': 'history'}, {'Exam': 89, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 9, 'subject': 'no'}, {'Exam': 89, 'Grade': 'a', 'Name': 'Chunky Pandey', 'age': 'NA', 'subject': 'NA'}] -
Can we Add Two foreign key in one class in django?
hey Guyzz i am new in django so can anybody help me out in this i want to add two foreign key in one class how can i do it? -
create a manual queryset with objects that are not present in database
So I have some objects that are not present in database and I need to create a query set from them. obj = MyModel(field1='foo', field2='bar') qs = MyModel.objects.none() and clearly I don't want to create and delete objects. so now how can i add that obj to my qs ? -
Page 404 error after running Django server
I have just started learning django and was trying to make a smartnotes App project by following a course. I updated the setting.py file to add website into Instaled_Apps. Then have written a function named home in views.py Finally I added it's entry into urls.py fie "welcome.html is insdie homeApp/templates/home directory" But when I run the server, I am getting following error on webpage: views.py from django.shortcuts import render from django.http import HttpResponse from django.http import HttpRequest # Create your views here. def home(request): return render(request, 'home/welcome.html', {}) settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # apps that I created 'home', ] urls.py from django.contrib import admin from django.urls import path from django.urls import path from home import views urlpatterns = [ path('admin/', admin.site.urls), path('home', views.home), ] welcome.html <html> <head> <title> welcome Page </title> </head> <body> <h1>Hello world !!!</h1> <h2>this is my first ever django project....</h2> </body> </html> -
Django model info not being rendered
I am trying to create an educational website using Django, so when I am trying to render {{ profile.institution }} or {{ profile.grade }} they are not being rendered. Although {{ user.username }} is being rendered. I don't know why they aren't. Can anyone help me solve this? My models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) institution = models.CharField(max_length = 100) grade = models.CharField(max_length=100, choices= YEAR_IN_SCHOOL_CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' My views.py: def User_Profile(request, user): model = Profile user = request.user profile = Profile.objects.filter(user=user) context = {'profile': profile} return render(request, 'class/profile.html', context) My html: <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-7"> <div class="card p-3 py-4"> <div class="text-center"> <i class='fas fa-user-alt' style='font-size:36px'></i> <!-- <img src="" width="100" class="rounded-circle"> --> </div> <div class="text-center mt-3"> <span class="bg-secondary p-1 px-4 rounded text-white">Pro</span> <h5 class="mt-2 mb-0">{{ user.username }}</h5> <span>{{ profile.institution }}</span> <span>{{ profile.grade }} Grade</span> <div class="px-4 mt-1"> <p class="fonts">{{ profile.bio }}</p> </div> <div class="buttons"> <button class="btn btn-outline-primary px-4">Message</button> <button class="btn btn-primary px-4 ms-3">Contact</button> </div> </div> </div> </div> </div> </div> -
FCM push notifications with AWS Lambda function
I have a Django project (Django 3.1.2) using fcm-django(version 0.3.7) to send push notifications. The application is deployed in AWS Elastic Beanstalk and the notifications are sent with no problems. I have the same code deployed in a AWS Lambda Function to run 3 cron jobs that check some conditions (each 15 minutes) and to send push notifications if necessary. But on the Lambda Function the notifications are not send. After some digging I understood that the function couldn't communicate with the outside because it was in a VPC. Which made absolute sense since I could see in the logs new HTTPS connections starting towards fcm.googleapis.com:443 and then "Task timed out after 30 seconds" To give internet access to an Amazon VPC-connected Lambda function, we would need to route its outbound traffic to a NAT gateway in a public subnet. So I followed the steps in How do I give internet access to a Lambda function that's connected to an Amazon VPC? to give internet access to the Lambda Function. I added a call to http://dog-api.kinduff.com/api/ to my code. That call now goes through so the NAT configuration worked! However, I continue to have a timeout to fcm.googleapis.com... What can … -
How do I display my form in a Django template?
I am trying to display my stat update form in my Django template, however it isn't displaying. My stats below show up correctly, just not the form. {{ stats.user }} | {{ stats.weight }} | {{ stats.date }} Template: {% block content %} <div class="container-fluid"> <div class="row"> <div class="col-sm-12 text-center"> <h1>My Health</h1> </div> </div> </div> <div class="container-fluid"> <div class="col-auto text-center p-3 form-group"> <form method="post" style="margin-top: 1.3em;"> {{ update_form }} {% csrf_token %} <button type="submit" class="btn btn-signup btn-lg">Submit</button> </form> </div> <div class="row justify-content-center"> <div class="col-auto text-center p-3"> <p class="text-center"> {{ stats.user }} | {{ stats.weight }} | {{ stats.date }} </p> </div> </div> </div> {% endblock content %} forms.py: class StatUpdateForm(forms.Form): class Meta: model = Stats fields = ('user', 'weight', 'date') models.py: class Stats(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateField(auto_now=True) weight = models.DecimalField(max_digits=5, decimal_places=2) class Meta: db_table = 'health_stats' ordering = ['-date'] def __str__(self): return f"You currently weigh {self.weight}, {self.user}" views.py: from django.shortcuts import render from .models import Stats from .forms import StatUpdateForm from django.views import generic, View from django.shortcuts import get_object_or_404 # from django.contrib.auth import authenticate # from django.core.exceptions import ValidationError # from .forms import RegistrationForm, LoginForm def home(request): return render(request, 'home.html') class MyHealth(View): def get(self, request, *args, **kwargs): … -
Can't scroll a dropdown menu in a Bootstrap navbar
I have a fairly simple home page that currently contains a navbar with two dropdown menus. One of menus contains a large number of entries but it doesn't allow me to scroll to the end of the list. I created a fixed-top navbar with a navbar-brand, a home link and two dropdown menus. One of the menus is short with just 2 items and the other contains about 32 items. Everything renders fine but when I open the larger of the two menus, it displays most of the items but will not allow me to scroll to the rest. I expected the navbar to stay fixed to the top of the page while I could scroll all the way to the bottom of the large menu. -
How to convert time to different timezone in django python
I am trying to convert time from America/New_York to other(any) timezone using from django.utils import timezone I tried finding references on web but couldn't find it -
Does this Python ABC interface, implementations, factory pattern make sense?
I've got a Django app and a message queue and I want to be able to switch between queue services easily (SQS or RabbitMQ for example). So I set up a BaseQueue "interface": class BaseQueue(ABC): @abstractmethod def send_message(self, queue_name, message, message_attributes=None): pass And two concrete classes that inherit from BaseQueue: class SqsQueue(BaseQueue): def send_message(self, queue_name, message, message_attributes=None): # code to send message to SQS class RabbitMqQueue(BaseQueue): def send_message(self, queue_name, message, message_attributes=None): # code to send message to RabbitMQ Then in settings.py I've got a value pointing to the implementation the app should use: QUEUE_SERVICE_CLS = "queues.sqs_queue.SqsQueue" Because it's a Django app it's in settings.py, but this value could be coming from anywhere. It just says where the class is. Then I've got a QueueFactory whose job is to return the queue service to use: class QueueFactory: @staticmethod def default(): return import_string(settings.QUEUE_SERVICE_CLS)() The factory imports the class and instantiates it. I would then use it like so: QueueFactory.default().send_message(queue_name, message) It works, but I was wondering if there's a more Python way to do it? Like with some magic methods? -
I receive an error when I try to login to an account on my website
I cannot login to any account, because I receive an error: Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.(for an admin user) And Please enter a correct email and password. Note that both fields may be case-sensitive. That happens after I update a profile through the profile-detail page. It just throws me to the login page after I press the Update button on the profile-update page. Here is all the related code: models.py class Customer(AbstractUser): USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = UserManager() customer_id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50, null=True, blank=True) username = models.CharField(max_length=30, null=True, blank=True) phone = models.CharField(max_length=10, default='', null=True, blank=True) email = models.EmailField(validators=[validators.EmailValidator()], unique=True) description = models.TextField(max_length=1000,blank=True, null=True) gender = models.CharField('Gender', max_length=10, choices=Gender.choices, default='Male', null=True) featured_img = models.ImageField(verbose_name='A profile image', upload_to='profiles', default='products/profile_default.jpg') password = models.CharField(max_length=100, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return f'{self.email} {self.username} {self.customer_id}' @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def exists(self): if Customer.objects.filter(email=self.email): return True return False class Meta: verbose_name = 'Customer' verbose_name_plural = 'Customers' # unique_together = ['email'] class Profile(models.Model): # USERNAME_FIELD = 'email' profile_id = models.AutoField(primary_key=True) date_created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, …