Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In a mysql-django-axios-react setup.... how to update a column in the db using its own value
Long time listener, first time caller.... learned so much from the forum and its community and many thanks to the platform and the community. Hopefully can get my skills up to contribute. Have a Mysql - Django - Axios - React setup. I can use Axios PATCH easy enough in react to issue an update through Django RFW to update a column in the db. But I'm stuck on how to update the column using the existing value in the column. For example in db language: table.column1=table.column1+x I tried a few things like passing a string as the data object but get a 400/bad request/"column requires an integer value" error from django RFW. Rookie mistake with db background... Last thing I tried was using the django F() expression to construct the data object to pass through axios.patch, and although no errors and get status 200 back from django, nothing happens, no update to the column. const col = (column1=F('column1')+${x}) axios.patch(localhost:8000/Model/${id},col) When I look at the browser console/network traffic I see FormData that is getting passed from axios to django as: (column1: F('column1') 9) /* 9=x */ Which is why I'm guessing nothing happens without the "+" Obviously I could axios.fetch, … -
is there any way to make possible the post request in my django and react project?
the frontend code is `import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import Select from "react-select"; function AddDetails() { const [formData, setFormData] = useState({ first_name: '', last_name: '', mobile_number: '', services: [], years_of_experience: '', license_certificate: null, min_charge: '', charge_after_one_hour: '', street_name: '', house_number: '', ward: '', panchayath_municipality_corporation: '', taluk: '', district: '', state: '', country: '', }); const [services, setServices] = useState([]); const [selectedServices, setSelectedServices] = useState([]); useEffect(() => { // Fetch the list of services from the Django backend axios .get('http://127.0.0.1:8000/services/') .then((response) => { setServices(response.data.results); }) .catch((error) => { console.error(error); }); }, []); const handleChange = (e) => { const { name, value } = e.target; if (name === 'services') { const selectedServices = Array.from(e.target.selectedOptions, (option) => option.value ); console.log('Selected Services:', selectedServices); setFormData({ ...formData, services: selectedServices, }); } else { setFormData({ ...formData, [name]: value, }); } }; const serviceOptions = services.map((service) => ({ value: service.id, label: service.Title, })); const handleSelectChange = (selectedOptions) => { setSelectedServices(selectedOptions); const selectedServiceIds = selectedOptions.map((option) => option.value); setFormData({ ...formData, services: selectedServiceIds, }); }; const handleFileChange = (e) => { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload … -
How to get FCM_SERVER_KEY in Django 2023.11
I got firebase json file then want to get FCM_SERVER_KEY FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": "wbhsfvbyewfuibwerugbjdsnugvbrfdfhbvjhbsdufhgvgtfhghuyhyuljhblkjhbliukjhiubbhfuvbkhersbfvcuhefhyuer" } I am expecting answers with pictures -
Django 4.2.6: Installing Different Admin Templates for Different Custom Admin Sites
I'm facing an issue while trying to install different admin templates for different custom admin sites in Django. Specifically, I want to use the default django.contrib.admin template for the default admin site and enable django-jet-reboot for a custom admin site. The problem I'm encountering is that when I install django-jet-reboot, it gets enabled for all admin sites, including the default one. Could someone please guide me on how to correctly install and apply different admin templates for distinct custom admin sites in Django? Thank you in advance for your assistance! I have tried to write a custom djanto template loader that reads a field from the settings: The following is a configuration that assiciate a given admin site with a corresponding template #settings.py ............. ADMIN_TEMPLATE_ASSOCIATION = { 'admin': { "template": "django.*", "exclude_templates": [ 'jet.*', 'jet.forms', 'jet.dashboard', ] }, 'first_admin': { "template": "jet.*", "exclude_templates": [ ] }, } .............. """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ #myapp.loader.py from pathlib import Path import re from django.template.utils import get_app_template_dirs from .filesystem import Loader as FilesystemLoader """ Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ from django.template.utils import get_app_template_dirs from .filesystem import Loader as FilesystemLoader from … -
how to set dynamically summernote value on dropdown change using jquery?
models.py class Other(models.Model): desc = models.TextField(default=None) create_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) form.py class OtherForm(forms.ModelForm): class Meta: model = Other fields = "__all__" exclude = ['create_by','create_at','update_at'] widgets = { 'desc':SummernoteWidget(attrs={'summernote': {'width': '100%', 'height': '400px'}}), } index.html <div class="card-body"> <label for="">Templates</label> <select class="form-control form-control-sm form-select" name="template" id="id_template"> <option value="">--</option> {% for i in data %} <option value="{{i.id}}">{{i.name}}</option> {% endfor %} </select> <form method="post" action=""> {% csrf_token %} {{form}} <div class="row"> <div class="col-6"> <button type="submit" class="btn btn-soft-primary">{{btn_type}}</button> <a href="{% url tree_url %}" class="btn btn-soft-gray">Bank</a> </div> </div> </form> </div> Js.file $('#id_template').change(function () { var id_template = $("#id_template").val() $.ajax({ type:'GET', url:'{% url "templates_find" %}', data:{id_template:id_template}, success:function (data, status) { var h_content = data.t_data console.log(h_content) } }); When I'm change dropdown jQuery ajax call and get right template value but can't set on summernote editor I have try using this $('.summernote').summernote('code', data.message); but still not working please guide. -
Improving Deployment Time for Django Project on Azure Web App
I have a Django project deployed on an Azure Web App (Linux, P2v2, Python 3.10, Django 4.2), which is functioning as expected. However, the deployment time is extremely slow, taking between 15 to 20 minutes to complete even a small change in the code. This is significantly longer than the deployment times I have experienced with other services. Here is a snippet of the deployment log: 2023-10-31T12:50:59.953Z - Updating branch 'master'. 2023-10-31T12:51:04.983Z - Updating submodules. 2023-10-31T12:51:05.086Z - Preparing deployment for commit id 'XXXXXXXXX'. 2023-10-31T12:51:05.338Z - PreDeployment: context.CleanOutputPath False 2023-10-31T12:51:05.432Z - PreDeployment: context.OutputPath /home/site/wwwroot 2023-10-31T12:51:05.535Z - Repository path is /home/site/repository 2023-10-31T12:51:05.638Z - Running oryx build... 2023-10-31T12:51:05.644Z - Command: oryx build /home/site/repository -o /home/site/wwwroot --platform python --platform-version 3.10 -p virtualenv_name=antenv --log-file /tmp/build-debug.log -i /tmp/8dbda100b9921ec --compress-destination-dir | tee /tmp/oryx-build.log 2023-10-31T12:51:06.599Z - Operation performed by Microsoft Oryx, https://github.com/Microsoft/Oryx 2023-10-31T12:51:06.614Z - You can report issues at https://github.com/Microsoft/Oryx/issues 2023-10-31T12:51:06.643Z - Oryx Version: 0.2.20230508.1, Commit: 7fe2bf39b357dd68572b438a85ca50b5ecfb4592, ReleaseTagName: 20230508.1 2023-10-31T12:51:06.658Z - Build Operation ID: 10aafab84d551a74 2023-10-31T12:51:06.664Z - Repository Commit : XXXXXXXXXXXXXX 2023-10-31T12:51:06.670Z - OS Type : bullseye 2023-10-31T12:51:06.677Z - Image Type : githubactions 2023-10-31T12:51:06.695Z - Detecting platforms... 2023-10-31T12:51:15.575Z - Detected following platforms: 2023-10-31T12:51:15.608Z - nodejs: 16.20.2 2023-10-31T12:51:15.613Z - python: 3.10.8 2023-10-31T12:51:15.618Z - Version '16.20.2' of platform 'nodejs' is … -
Make env file as .gitignore in djangp project?
image How to move my broenv (env folder) folder inside gitignore. I don't want to store my broenv folder to Github. How can I remove that from github? Plzzz help! Is that okay to store env folder in github?. I don't want to store my broenv(env) folder to Github repository. -
How to create mongodb models with multiple dictionaries for django
So i have a databases which stores players positions in time in mongoDB, then i connect to it with django and this works fine. _id: "", timeline: { "1":{ "Player 1":{ "x":"554", "y":"581" }, "Player 2":{ "x":"554", "y":"581" }, } "2":{ "Player 2":{ "x":"554", "y":"581" }, "Player 1":{ "x":"554", "y":"581" }, } ... } team1: "ABC" team2: "BCD" in models.py i have class Game(models.Model): _id = models.CharField(max_length=100, primary_key=True) timeline = JSONField() team1 = models.CharField(max_length=100) team2 = models.CharField(max_length=100) and i get the error "the JSON object must be str, bytes or bytearray, not OrderedDict" is there a problem with my data? Or how should i define it in my model.py? -
Email Verificationl is not sent after registration. Django + Celery
I use Windows without WSL. Recently I have installed Redis for caching in my Django project. I've done it without some problems using this link: https://github.com/microsoftarchive/redis/releases Next task was working with Celery for registration optimization (If I understand correctly, I'm watching a development course). I've done everything as in my course. But Email Verification didn't worked. I have the same code like author code. But author use MacOS. I don't fully understand the work with Celery, but I need to do it. I will be grateful for your help! base - root directory users - app for working with users base/_init_.py: from .celery import app as celery_app __all__ = ('celery_app',) base/celery.py: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') app = Celery('base') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() base/settings.py: CELERY_BROKER_URL: str = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND: str = 'redis://127.0.0.1:6379' users/forms.py: class UserRegistrationForm(UserCreationForm): first_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the name', })) last_name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the surname', })) username = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control py-4', 'placeholder': "Enter the user's name", })) email = forms.CharField(widget=forms.EmailInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the email address', })) password1 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', 'placeholder': 'Enter the password', })) password2 = forms.CharField(widget=forms.PasswordInput(attrs={ 'class': 'form-control py-4', … -
How do I Link the following two tables in Django?
I have two models; Employee and Product. The two tables already have data. All I need to do is Assign each Employee to a Product(eg. Computer) and then be able to retrieve the data and display it. Here are the models. from django.db import models from django.utils import timezone from django.dispatch import receiver from more_itertools import quantify from django.db.models import Sum # Create your models here. class Employee(models.Model): address = models.EmailField(max_length=100,null=True) first_name = models.CharField(max_length=50,null=True) sec_name = models.CharField(max_length=50,null=True) department = models.CharField(max_length= 50,null=True) company = models.CharField(max_length= 50,null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name + ' - ' + self.department class Product(models.Model): model=models.CharField(max_length=50, null=True) serial=models.CharField(max_length=50, null=True) hd_size=models.CharField(max_length=50,null=True) ram=models.CharField(max_length=50, null=True) processor=models.CharField(max_length=50, null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.serial + ' - ' + self.model -
How to make classes separately for each word in django
To begin with I would like to say that I write with the help of django. The question itself. I have models in the folder models.py, there is specified in fact all that I output in the post, I also have a file views.py and in general everything works fine, the posts are displayed on the page that I need. But! I need to modify the posts, for example, change the color of the header, make that one was after the other, but I can not assign just a class or an idi to a certain header or a certain piece of text, because they are all united in one line, look at the code and understand. <body> {% for post in post_list %} <h3>{{post.title }}</h3> <p>{{ post.description}}</p> <p>{{ post.time_posts}}</p> {{ post.author }} {% endfor %} </body> If i put a class front example <div class="prjclass"><p>{{ post.time_posts}}</p></div> Then I have that when working in css with this prjtitle class I move absolutely all headings and they just merge 1 in 1. How can I make it so that I can edit almost every word with css classes or idi. -
Issues with django file logger
I have a created a django logger settings. It is intended that console django.db.backends should not be applied to console. But it is printing in console as well. LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": { "format": "%(levelname)s %(asctime)s %(module)s " "%(process)d %(thread)d %(message)s" } }, "handlers": { "file": { "level": "DEBUG", "class": "logging.handlers.TimedRotatingFileHandler", "filename": "debug/debug.log", 'when': 'W0', # Weekly log staring from Monday 'interval': 1, 'backupCount': 10, }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", }, }, "root": {"level": "INFO", "handlers": ["console"]}, "loggers": { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['file'], } }, } This is my logger configuration. With this it is logging sql commands in file as well as console. I want this to be logged only for file. Please help if you have encountered this issue before. -
django-allauth and django-phone-auth clash on EmailAdress.User mutual accessors
I have my auth app in Django and a custom user defined as #auth/models.py class User(AbstractUser): pass And it is set as the user_model in settings: AUTH_USER_MODEL = 'auth.User' I'd like to use django-phone-auth for authenticating with phone or email, and django-allauth to authenticate with social providers. After I add the both to my virtual environment and try migrate I get the error: account.EmailAddress.user: (fields.E304) Reverse accessor 'User.emailaddress_set' for 'account.EmailAddress.user' clashes with reverse accessor for 'phone_auth.EmailAddress.user'. The problem is in the same-named models having foreign key relation to the user model in the two packages. #allauth/account/models.py class EmailAddress(models.Model): user = models.ForeignKey( allauth_app_settings.USER_MODEL, verbose_name=_("user"), on_delete=models.CASCADE, # # !!!! related_name='accountuser' would solve the conflict ) ... vs. #phone-auth/models.py class EmailAddress(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ... The clash is due to reverse reference conflict, and adding related_name='accountuser' to any of the user fields does solve it. But changing original code of installed packages is not a good idea. Can anyone advise how it should be sorted out, please. Many thanks! -
Django rest framework nested data receiving from JavaScript nested form-data
My problem is that creating nested form-data and receiving them. Here is my models.py: class BridgeReport(models.Model): bridge = models.ForeignKey(Bridgedata, on_delete=CASCADE, related_name='report') title = models.TextField(blank=True, null=True) def __str__(self): return self.title class MajorInspection(models.Model): major_inspection = ForeignKey(BridgeReport, related_name='major_inspection', on_delete=CASCADE) damaged_member = models.TextField(blank=True, null=True) grade = models.TextField(blank=True, null=True) # choice class MajorInspectionReport(models.Model): major_inspection_report = ForeignKey(MajorInspection, related_name='major_inspection_report', on_delete=CASCADE) defect_type = models.TextField(blank=True, null=True) cause = models.TextField(blank=True, null=True) maintenance_and_reinforcement_plan = models.TextField(blank=True, null=True) special_note = models.TextField(blank=True, null=True) attached_file = models.ImageField(upload_to = custom_upload_to_MajorInspection, blank=True) Here is my serializers.py class MajorInspectionReportSerializer(serializers.ModelSerializer): class Meta: model = MajorInspectionReport exclude = ['major_inspection_report'] def create(self, validated_data): # Handle the creation of a MajorInspectionReport instance here return MajorInspectionReport.objects.create(**validated_data) class MajorInspectionSerializer(serializers.ModelSerializer): major_inspection_report = MajorInspectionReportSerializer(many=True, read_only=True) major_inspection_reports = serializers.ListField( child = CustomField(), write_only = True, required=False ) def create(self, validated_data): print("1Validate data", validated_data) major_inspection_reports = validated_data.pop("major_inspection_reports") major_inspection_report = MajorInspection.objects.create(**validated_data) if major_inspection_reports: print("2major_inspection_reports: ",major_inspection_reports) for dic in major_inspection_reports: print("3mana:",dic.get('[defect_type]', '')) print("dic is ", dic) MajorInspectionReport.objects.create( major_inspection_report=major_inspection_report, defect_type=dic.get('[defect_type]', ''), cause=dic.get('[cause]', ''), maintenance_and_reinforcement_plan=dic.get('[maintenance_and_reinforcement_plan]', ''), special_note=dic.get('[special_note]', ''), attached_file=dic.get('[attached_file]', ''), ) return major_inspection_report return MajorInspection.objects.create(**validated_data) class Meta: model = MajorInspection exclude = ['major_inspection'] class BridgeReportSerializer(serializers.ModelSerializer): major_inspection = MajorInspectionSerializer(many=True, read_only=True, required=False) model_3d = ThreeDModelSerializer(many=True, read_only=True, required=False) upload_major_inspections = serializers.ListField( child = CustomField(), write_only = True, required=False ) class Meta: model = BridgeReport exclude … -
Django Rest Framework: Unable to Retrieve Authorization Token from Header on Hosted Server
I have hosted a Django Rest Framework API on a domain. In my code, I retrieve the Authorization token from the header using the following line: request.headers.get('Authorization', None) This code works perfectly fine on my local server and when I run the server using python manage.py runserver with an IP address. However, when deployed on my hosted server, I'm getting None as a result. Any help or insights would be greatly appreciated. Thank you! I have already added my domain to the ALLOWED_HOSTS setting in Django's settings file. The server is hosted on a Linux environment. Is there any additional configuration that I need to apply for a hosted deployment, specifically on a Linux server, to ensure that the Authorization header is correctly received? -
Seeking Guidance on Building an Online Compiler with Django and Testing Features [closed]
Hello Stack overflow community, I have an ambitious project in mind, and I'm seeking guidance and insights from experienced developers. I'm interested in creating an online compiler similar to platforms like HackerRank, and I'd like to use Django, a web framework, to help achieve this. Here's the vision: Users can access a code editor on the platform. I can provide questions or coding challenges to users. Users write and run their code within the platform. After running the code, the system should automatically check it against various test cases, just like HackerRank. The code is evaluated, and it's marked as either "pass" or "fail." My question is, are there any existing open-source projects, codebases, or tutorials that can help me get started on this project, specifically using Django as the foundation? I'd appreciate any advice or resources that can assist me in building this platform, including insights on how Django can be utilized for this purpose, along with technologies and libraries that could complement it. I'm aware that this is a substantial project, and I'm excited to take on the challenge with Django. Your expertise and guidance would be invaluable to me as I embark on this journey. Thank you … -
Django, MySQL, JSONField - Filtering Issue with JSON Data
I'm encountering an issue with filtering JSON data stored in a Django JSONField. While attempting to filter data using the icontains lookup, it seems to treat the JSON data as a string field, and the filtering doesn't work as expected. Here's a brief overview of my setup: Model: I have a Django model with a JSONField like this: from django.db import models class ChatMessage(models.Model): template_message = models.JSONField(null=True) The JSON data is stored in the following format in the database: { "header": { "type": "text", "content": "Hello" }, "body": "Hi there", "footer": "Hello there" } Problem Description: The problem I'm facing is with the filtering code. I want to filter objects based on values within the JSON data, but the icontains lookup seems to be treating it as a string field rather than a JSON field. ChatMessage.objects.filter( Q(template_message__header__content__icontains=search_key) | Q(template_message__body__icontains=search_key) | Q(template_message__footer__icontains=search_key) ) Expected Outcome: I expect the filtering to consider the JSON structure and filter based on the presence of search_key within any of the JSON values, such as in the content, body, or footer fields. Error Messages: I haven't received any error messages, but the filtering doesn't work as expected. -
UnboundLocalError at /subscribe/ local variable 'customer' referenced before assignment in stripe payment
else: try: customer = stripe.Customer.create( email = request.user.email, plan = order.plans, description = request.user.email, card = payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") return redirect(reverse('subscribe')) finally: subscription = Subscription( user = request.user, plan = plan_ids[order.plans], customer_id = customer.id ) -
django-distill not exporting URL's correctly
I am using django-distill to create a static HTML output of my Django site. I am having an issue with how distill converts {% static %} and {% url %} tags into relative HTML URLs. Worth noting that I have also tried Django-bakery and am encountering exactly the same problem. Let's start with the homepage. This is an 'index.html' file in the parent directory. This is the output I get from distill: <link rel="stylesheet" href="/static/css/styles.css"> The '/' at the front of the URL appears to be causing a problem. With the code above, the style sheet does not load in the browser. But if I manually remove the '/', the following code works: <link rel="stylesheet" href="static/css/styles.css"> For HTML pages nested in subdirectories, the same problem is occurring but the solution is more complex. Distill outputs the code as below: ` However, I believe the correct output should start with "../../" to indicate to the browser that the static folder is up 2 levels in the parent directory. The following code works correctly when I edit it manually: <link rel="stylesheet" href="../../static/css/styles.css"> The same problem occurs with both static links and URL links. As I'm struggling to pinpoint where in my django … -
How to Override Django ManyRelatedManager Methods and Enforce Validations
I have the following two models that have a Many-to-Many (m2m) relationship. I want to implement validation rules when creating a relationship, particularly when the Field object is controlled. class Category(models.Model): name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=50, unique=True, editable=False) fields = models.ManyToManyField("Field", related_name="categories") class Field(models.Model): controller = models.ForeignKey( "self", models.CASCADE, related_name="dependents", null=True, blank=True, ) label = models.CharField(max_length=50) name = models.CharField(max_length=50) When creating a relationship between a Category and a Field objects via the add() method, I would like to validate that, for a controlled field, the controller field must already be associated with the category. When creating via the set(), I would like to validate for any controlled field in the list, the controller field must also be in the list, OR is already associated with the category. # Category category = Category.objects.create(name="Cars", slug="cars") # Fields brand_field = Field.objects.create(name="brand", label="Brand") model_field = Field.objects.create(name="model", label="Model", controller=brand_field) # controller should already be associated or raises an exception category.fields.add(model_field) # Controller must be inclded in the list as well, # OR already associated, or raise an exception category.fields.set([model_field]) Where can I enforce this constraints? I'm thinking of overriding ManyRelatedManager's add() and set() methods but I do not understand how they're coupled to … -
Image uploaded via CKEditor in Django extends beyond the div
I'm working on my very first Django project, a blog, and I'm almost done with it. However, I've got this quirky issue: the images I upload through CKEditor spill out of the div they're supposed to stay in. Any ideas on how to fix that? This is how I upload the image: I understand that when uploading, I am able to set the image size. However, I would like the image width to be 100% of the div automatically, while maintaining the original image's aspect ratio for the height. This is how it is displayed: Here is the template: {% extends "mainapp/base.html" %} {% block content %} <div id="main-container"> <div id="second-container"> {% if article.article_image %} <img src="{{article.article_image.url }}" id="article-image"> {% endif %} <p>Published: {{article.publication_date}} {% if article.last_edit_date != None %} Last edit: {{article.last_edit_date}} {% endif %} </p> <h1>{{article.title}}</h1> <p>{{article.body|safe}}</p> {% if user.is_superuser %} <a href="{%url 'mainapp:edit_article' article.id %}"><button type="button">Edit</button></a> <a href="{%url 'mainapp:delete_article' article.id %}"><button type="button">Delete</button></a> {% endif %} </div> <br> <br> <div id="second-container"> <h3>Comments section</h3> {% for comment in comments %} <p> {{comment.publication_date}} {% if comment.author == "ravdar (op)" %} <span style="color: orangered; font-weight: bold;">{{ comment.author }}</span> {% else %} {{ comment.author }} {% endif %} <p>{{comment.text}}</p> {% endfor %} … -
Django & Djoser - AttributeError: 'NoneType' object has no attribute 'is_active' when registering a new user
I am trying to implement user registration using djoser. I believe I am passing in all the correct data in the body but I return a 500 error: "AttributeError: 'NoneType' object has no attribute 'is_active'" I have tried overwriting list_display and list_filter in BaseUserAdmin. I also have tried moving the is_active attribute to different areas of the model. models.py from django.contrib.auth.models import AbstractUser, AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ # managing the creation and user and superuser class UserAccountManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): # first_name, last_name, if not email: raise ValueError('Users must provide an email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_active', True) extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_active') is not True: raise ValueError('Superuser must have is_active=True.') if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email serializers.py from djoser.serializers import UserCreateSerializer from django.contrib.auth import get_user_model … -
Website fails to load after db data upload
The website I am working with is based on django v3.2.19 with a mysql v8.0.32 back end, in a windows 10 environment. The database had limited data, so I updated the db from a backup of the same db set up on a different system (AWS, linux). The website, up until an hour ago was up and running. After the data upload, I was unable to start the server with 'python manage.py runserver'. The stacktrace that is displayed ends with: C:\Users\jw708\Documents\Gain\gain>python manage.py test Traceback (most recent call last): File "C:\Users\jw708\Documents\Gain\gain\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Program Files\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Program Files\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Program Files\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'dal' Several online sites suggested that 'dal' needs be installed. The 'dal' is the first app listed in the INSTALLED_APPS list of the settings.py file … -
rabbitmq returns [Errno 111] Connection refused when connecting to celery
In my app I have rabbitmq as message broker and celery to manage the tasks from BE. When trying to run any Celery @shared_task im getting this error: kombu.exceptions.OperationalError: [Errno 111] Connection refused This is my docker-compose.yml file: version: "3.9" services: app: build: context: . args: - DEV=${IS_DEV} restart: always ports: - "${APP_PORT}:8000" volumes: - "./src:/app/src" - "./scripts:/app/scripts" - "./Makefile:/app/Makefile" - "./pyproject.toml:/app/pyproject.toml" - "./Dockerfile:/app/Dockerfile" depends_on: - postgres-main - celery command: > sh -c ". /app/venv/firewall_optimization_backend/bin/activate && python3 /app/src/manage.py migrate && python3 /app/src/manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - IS_DEV=${IS_DEV} - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - DEFAULT_LOOKUP_CONFIG_FILE=${DEFAULT_LOOKUP_CONFIG_FILE} postgres-main: image: postgres:15-alpine3.18 restart: always volumes: - postgres-main-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${POSTGRES_DB} - POSTGRES_USER=${POSTGRES_USER} - POSTGRES_PASSWORD=${POSTGRES_PASSWORD} rabbitmq: image: "rabbitmq:management" ports: - "${RABBIT_MQ_MANAGEMENT_PORT}:15672" - "${RABBIT_MQ_PORT}:5672" celery: build: . command: > sh -c ". /app/venv/firewall_optimization_backend/bin/activate && celery -A src.celery_config worker --loglevel=info" volumes: - "./src:/app/src" - "./scripts:/app/scripts" - "./Makefile:/app/Makefile" - "./pyproject.toml:/app/pyproject.toml" depends_on: - rabbitmq environment: - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - IS_DEV=${IS_DEV} - DJANGO_SECRET_KEY=${DJANGO_SECRET_KEY} - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672// volumes: postgres-main-db-data: -
Informix "21005 Inexact character conversion during translation" error
currently am working on a django project that connect to an informix database using (CSDK/ODBC) and the connection is established correctly, but when i try inserting data in darabic language i get this error: "21005 Inexact character conversion during translation". The thing is that some arabic letters are inserted without any problem (the arabic characters from U+060C to U+063A in ascii code) but onece i insert one of the characters after the unicode U+063A i get the error. i have tried changing client_local and db_local variables (maybe i didn't do it correctly) but nothing seems to work. i would be very greatfull if you could help me even with a hint or a suggestion. thank you in advance.