Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
correct incorrect serilization in django
After serialization,I tried to call Django-rest api by connecting 3 tables, then I got issue Original exception text was: 'Store' object has no attribute 'Storeimage'., I'm expecting to get api by connecting 3 models. My models class Store(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) address = models.ForeignKey(Address, null=True,on_delete=models.CASCADE) store_name = models.CharField(max_length=255) store_about = models.CharField(max_length=255,null=True) store_location = models.CharField( max_length=255) #store_address = models.TextField() store_phoneno = models.CharField(max_length=12) class Storeimage(models.Model): store = models.ForeignKey(Store, null=True, on_delete=models.SET_NULL) picture = models.ImageField(upload_to='store_image/%Y/%m/',max_length=255,null=True) class Address(models.Model): street = models.TextField() country = models.ForeignKey(Country, default=1,null=True, on_delete=models.CASCADE) state = models.ForeignKey(State, default=1,null=True, on_delete=models.CASCADE) my serilzation class StoreGetSerialiser(serializers.ModelSerializer): #store_product = StoreproductSerializer(many=True) address = AddressSerializer() Storeimage = StoreImage(many=True) owner = UserPublicSerializer(source='user', read_only=True) class Meta: model = Store fields = [ 'pk', 'owner', 'store_name', 'Storeimage', 'store_location', 'address', 'store_phoneno', 'store_website', ] Myexpected output: { "pk": 2, "owner": { "id": 1 }, "store_name": "", "store_location": "", "address": { "id": 14, "street": "1", "country": 1, "state": 1, "city": 1 }, "store_phoneno": "", "store_image": [{"pk":1,"picture":"/location/abcd"},{"pk":2,"picture":"/location/abcd"}] }, -
The post counter not working in my Django project
I am doing a project for my Django course and I hit a wall that I cannot overcome. I tried to find the answer here, but the seems similar to what I already have put in place. So, my project is a forum and posts can be made inside a category. The index page shows the different categories and the amount of posts inside each category. However, no matter how many posts are created the counter does not change. This is the model for the category and for the post class Category(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) posts = models.ManyToManyField( 'Post', related_name='categories', blank=True) class Meta: ordering = ['created_on'] def __str__(self): return self.title def number_of_posts(self): return self.posts.count() class Post(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts_list") content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) likes = models.ManyToManyField(User, related_name='post_likes', blank=True) favourite = models.ManyToManyField( User, related_name='favourite', blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='category') class Meta: ordering = ['created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def number_of_comments(self): return self.comments.count() this is … -
how to connect Django project to mongoDB?
i have django project where its connected to the default sqlite3 database i want to change the database to the mongoDB but its not working i am using the below packages settings.py: DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': '3DHologram', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://testdevleb:JmqUI7qNMB4hvfil@cluster0.dofcak0.mongodb.net/3DHologram?retryWrites=true&w=majority', 'username': 'testdevleb', 'password': 'JdcdUI7kNMB4hvfil', 'authMechanism': 'SCRAM-SHA-1', 'authSource': 'admin', } } } packages: Django==4.1.13 djongo==1.2.3 dnspython==2.4.2 pymongo==3.10.1 pytz==2023.3.post1 once i try the below command python manage.py migrate error: File "F:\private_projects\videoproject\myvenv\Lib\site-packages\django\db\utils.py", line 126, in load_backend raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: 'djongo' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' -
Customized Parsing Text in Django Framework
I'm developing an application using Django to provide an issue content from JIRA, issue tracking system developed by Atlassian. My question is how can I parse an inner content of a field of the issue efficiently saving my time? Now I pull all the content of an issue using the below code: issue = jira.issue('issue_no') print(issue.raw['fields']['issuetype']) print(issue.fields.status) print(issue.fields.description) When I print the issue.fields.description, it shows all text in that description field. BTW, my goal is to provide a description from an selected issue and want to parse the description field to pick strings in a specified pattern starting with 'SRC_' and summary written by users. For example, I want to remove the below strings and need to select a part of description after {color} tag. {panel:bgColor=#deebff} h1. *Summary* {panel} h1. {color:#0747a6}*Short Description*{color} The string after parsing can be vary but it is an example: Created tables ... # Source_file_name_1 # Source_file_name_2 " How can I make the customized text that will show to users? -
Django/Python Web Scraping - the targeted tag isn't being found to pull the information I need
I am working on a Django web application for sports cards. Each card has their own page that displays the card name at the top, and underneath it should display the current lowest price of that card. The lowest price value is pulled from https://cardboard.market/. In my views.py I want a function that gets this lowest price. Here is where I am at currently: views.py: def get_lowest_card_price(card_name): base_url = "https://cardboard.market/" search_url = f"{base_url}search?q={card_name}" try: # Send a GET request to the website response = requests.get(search_url) response.raise_for_status() # Raise an exception for bad responses (4xx or 5xx) # Parse the HTML content of the page soup = BeautifulSoup(response.text, 'html.parser') # Find the element with the specified class target_div = soup.find('div', class_='bubble-element Text cmgaCs') # Extract the text content if target_div: price_text = target_div.text.strip() return price_text else: print(f"Could not find the specified div element for card '{card_name}'.") except requests.RequestException as e: print(f"Error during request: {e}") return None def ProSet1990_1(request): # Hardcoded card details for demonstration purposes card_name = "David Seaman" card_set = "1990 Pro Set" # Use the web scraping bot to get the lowest card price lowest_price = get_lowest_card_price(f'{card_set} {card_name}') # Pass the data to the template context = { 'card_name': … -
How to partially match URLs when searching with Django Full Text Search
I have a Django model representing a website, and I use the Postgres Full Text Search to search the Website objects. However, if you search for only part of a website's url, it doesn't return matching Websites. e.g. if a Website has a url of "https://www.example.com/foo/" and you search for "example" or "foo", then that Website isn't returned in results. I could create a new field, that's populated on save, which contains the url, but with parts separated by spaces. e.g. "www example com foo". And then index that. But then this wouldn't work if the user searched for "example.com". Is there some way I can use Full Text Search to search for partial matches on the url field, as well as still searching title and description? My model: from django.contrib.postgres.indexes import GinIndex from django.contrib.postgres.search import SearchVectorField from django.db import models class Website(models.Model): title = models.CharField(blank=True, null=False, max_length=255) url = models.URLField(blank=False, null=False, max_length=255) description = models.CharField(blank=True, null=False, max_length=1000) search_document = SearchVectorField(null=True) class Meta: indexes = [GinIndex(fields=["search_document"])] def index_components(self): return ( (self.title, "A"), (self.url, "B"), (self.description, "C"), ) Not sure this is relevant, but for completeness, there's a post save signal that updates the index, something like this from here: from … -
I am not able to implement Manty to One relationship in developing a search in multiple attributes across multiple models. One to Many works
model.py view.py search_form.html search_reslut.html form.py ######################################################### I am doing a search app, that allows users to search books with their properties and authors. So it is " Multiple properties across multiple models". The problem is I can't bring the One-to-Many relationship search. The Many-to-one works. I want to retrieve books written by the one author. When I search book, It shows, the author, isbn, pages. But when I search author, cant get books. -
how to solve the psycopg2 and pillow installation problem on cpanel (
for hours I have been trying to deploy my django project on cpanel of lws, I created a python application and activated the virtual environment but as soon as I try to install the dependencies I receive an error error: subprocess-exited-with-error × Building wheel for Pillow (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [143 lines of output] running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-cpython-39 creating build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/BlpImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/ImageFilter.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/SpiderImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/ImageGrab.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/GimpPaletteFile.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/FpxImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/DdsImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL copying src/PIL/XpmImagePlugin.py -> build/lib.linux-x86_64-cpython-39/PIL running egg_info writing src/Pillow.egg-info/PKG-INFO writing dependency_links to src/Pillow.egg-info/dependency_links.txt writing requirements to src/Pillow.egg-info/requires.txt writing top-level names to src/Pillow.egg-info/top_level.txt reading manifest file 'src/Pillow.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.c' warning: no files found matching '*.h' warning: no files found matching '*.sh' writing manifest file 'src/Pillow.egg-info/SOURCES.txt' running build_ext building 'PIL._imaging' extension creating build/temp.linux-x86_64-cpython-39/src/Tk declaration -fPIC -DHAVE_LIBJPEG -DHAVE_LIBZ -DHAVE_LIBTIFF-DHAVE_XCB -DPILLOW_VERSION=\"10.0.1\" -I/usr/include/freetype2 -I/usr/include -I/home/uloyxtlb/virtualenv/core/Ulc_loyola_core/3.9/include -I/opt/alt/python39/include/python3.9 -c src/_imaging.c -o build/temp.linux-x86_64-cpython-39/src/_imaging.o error: command '/usr/bin/gcc' failed: Permission denied [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel … -
Two objects are created after registering with Django
After registration, two objects are entered in the database, one with only the user, the other with the user and first and last name. This is because I save twice, but when saved once will fail u = UserProfile(user=user, name=user_name, last_name=last_name) u.save() views.py def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user_name = form.cleaned_data['username'] last_name = form.cleaned_data['last_name'] if UserProfile.objects.filter(user__username=user_name).exists(): messages.error(request, 'This username is already taken. Please choose a different one.') else: user.save() u = UserProfile(user=user, name=user_name, last_name=last_name) u.save() login(request, user) messages.success(request, 'Successful registration') return redirect('home') else: messages.error(request, 'Registration error') else: form = UserRegisterForm() return render(request, 'service/register.html', {'form': form}) models.py class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=150, verbose_name='Name') last_name = models.CharField(max_length=150, verbose_name='Last name') def __str__(self): return f'User: {self.user}' forms.py class UserRegisterForm(UserCreationForm): username = forms.CharField(label='Name', widget=forms.TextInput( attrs={'class': 'form-control', 'autocomplete': 'off'})) last_name = forms.CharField(label='Last name', widget=forms.TextInput( attrs={'class': 'form-control', 'autocomplete': 'off'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput( attrs={'class': 'form-control'})) password2 = forms.CharField(label='Again password', widget=forms.PasswordInput( attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'last_name', 'password1', 'password2') I tried to save with one save, but it saves without a first and last name or an error pops up save() prohibited to prevent data loss due to unsaved related … -
Problem starting Django container in production (Whitenoise?)
I have suddenly started having trouble starting up my website in production after I moved to a new VPS hosting service. I was using Vultr and moved to Digitalocean because response time was way faster when using Ansible (for the same machine configuration). In both cases I was using Ubuntu 23.10 as a host. I also tried to do "compose up" with production.yml in my dev machine and the error is the same, so I guess it has nothing to do with the change of hosting service. Here's an extract of Docker's output: cymentcom-django-1 | PostgreSQL is available cymentcom-django-1 | Post-processing 'vendor/purecounter/purecounter_vanilla.js' failed! cymentcom-django-1 | cymentcom-django-1 | Traceback (most recent call last): cymentcom-django-1 | File "/app/manage.py", line 39, in <module> cymentcom-django-1 | execute_from_command_line(sys.argv) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line cymentcom-django-1 | utility.execute() cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute cymentcom-django-1 | self.fetch_command(subcommand).run_from_argv(self.argv) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv cymentcom-django-1 | self.execute(*args, **cmd_options) cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute cymentcom-django-1 | output = self.handle(*args, **options) cymentcom-django-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle cymentcom-django-1 | collected = self.collect() cymentcom-django-1 | ^^^^^^^^^^^^^^ cymentcom-django-1 | File "/usr/local/lib/python3.11/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 154, in collect cymentcom-django-1 | … -
Wagtail page edit, 'NoneType' object has no attribute 'get_actions'
I got a strange error, when trying to view page in wagtail admin 'NoneType' object has no attribute 'get_actions' at wagtail/admin/views/pages/edit.py in workflow_action_is_valid at line 469 Not sure, how this can happen? And what is the possible solution to fix that? -
django userprofile nested relationship is empty in django REST
Hello I have an UserProfile model in django, and I want to serialize my User model with its UserProfile nested to receive it via ajax in my template but it cames empty. Model UserProfile class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.DO_NOTHING) departamento = models.ForeignKey(Departamento,on_delete=models.PROTECT,related_name="pertenece_a") class Meta: db_table = 'UserProfile' def user_profile(sender, instance, signal, *args, **kwargs): Userprofile, new = UserProfile.objects.get_or_create(user=instance) signals.post_save.connect(user_profile, sender=User) Serializers class ProfileSerializer(serializers.Serializer): class Meta: model = UserProfile fields = ["departamento"] class GestionUsuarioSerializer(serializers.ModelSerializer): profile = ProfileSerializer(many=True,read_only=True) class Meta: model = User fields = ["id","username","email","first_name","last_name","profile"] Result -
Please help django
I want the results from the columns on the left to be in one main column on the right, to be distributed according to categories and subcategories. results from the columns on the left to be in one main column on the right, to be distributed according to categories and subcategories. -
Make inner joins by using Q objects in Django
I'm customizing a model's Admin change list page in my project. This model contains a Many to Many field and I want to allow multi-selection filtering. I've used the Django Admin Multi Select Filter package to do this but I noticed that the default behaviour in Django's __in lookup is to be inclusive and not exclusive. Imagine I have an object A associated with M2M objects 1 and 2 and object B associated with M2M objects 2 and 3. If I make the following query Model.objects.filter(m2m_model__in=[1,2]) I will have both objects A and B being retrieved, since the search will use the following condition: Index Cond: (models_model_m2mfield.model_id = ANY ('{1,2}'::bigint[])) I was able to customize the behaviour of the search by doing the following: for choice in choices: queryset = queryset.filter(**{self.lookup_kwarg: choice}) This generates inner joins and returns the value I'm waiting for (only objects matching every option). INNER JOIN "models_model_m2mfield" ON ("models_m2mmodel"."id" = "models_model_m2mfield"."m2mfield_id") INNER JOIN "models_model_m2mfield" T4 ON ("models_m2mmodel"."id" = T4."m2mfield_id") WHERE ("models_model_m2mfield"."model_id" = 4 AND T4."model_id" = 5) I've tried using Q objects to get the same result, but I couldn't make it work. Is it possible to achieve the same behaviour using the Q class? -
why commands in command line starting with python is not working and giving output "Python"?
When I'm running a command starting with python in Windows PowerShell I always have just output "Python" Example: PS C:\Users\----\Django\jobapp> python -m venv env Python Example 2: PS C:\Users\----\Django\jobapp> python manage.py runserver Python I had a python version 3.9 and then I tried to reinstall python for a new version(3.12), but nothing have changed -
"commands out of sync; you can't run this command now" on first use of cursor
I am using MySQL in Django (Python). The draft version of this code worked and was stable, but it created cursors without closing them, and I just rewrote it to manage the cursor with enter/exit. Now it is unstable. class Cursor: def __init__ (self, db): self.db = db self.cursor = db.DB_connection.cursor () def __enter__ (self): return self def __exit__ (self, ex_type, ex_value, ex_traceback): if ex_value is not None: # log stuff self.cursor.close () self.cursor = None def __del__ (self): if self.cursor is not None: # log stuff self.cursor.close () def one (self, query, args): self.cursor.execute (query, args) return self.cursor.fetchone () class DB: def __init__ (self, my_stuff): self.DB_connection = connect (...) def get (self): return Cursor (self) and in the application: with DB_connection.get() as db: result = db.one ("SELECT ...", ...) Sometimes this works as before, but sometimes randomly it will fail calling db.one() _mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now this exception is seen in Cursor's __exit__ Googling this error tells me that this means an earlier SELECT on that cursor still has un-fetched results. But this is nonsense since with DB_connection.get() as db creates a new cursor. Also sometimes the process simply exists without printing … -
Django Autocomplete Light: ModelSelect2Multiple height not expanding
I have a forms.models.ModelMultipleChoiceField using an autocomplete.ModelSelect2Multiple widget. This is working well, except that when I add many entries and it spans multiple lines, the box does not expand to accommodate them (see image below). Can anyone please suggest the best way to make the box expand? -
Handling formsets in Django
In my django project, I want to use formsets, but I have a problem with handling the POST requests. I defined my formset this way: strategy_settings = formset_factory(StrategySettings) strategy_formset = strategy_settings(request.POST) Then I tried to loop through all of the forms in a formset if the forms are valid: if strategy_formset.is_valid(): for form in strategy_formset: data = form.cleaned_data["data"] But the thing is, although I fill the forms with proper data, the forms are not valid, I checked this by printing statements in the console. No error appears, when I submit the forms, formset just disappears from a page. Here is my full view: def input_view(request): if request.method =="POST": simulation_form = SimulationSettings(request.POST) # Regular form strategy_settings = formset_factory(StrategySettings) # Formset strategy_formset = strategy_settings(request.POST) # Formset if simulation_form.is_valid() and strategy_formset.is_valid(): print("valid") initial_amount = simulation_form.cleaned_data['initial_amount'] number_of_simulations = simulation_form.cleaned_data['number_of_simulations'] number_of_trades = simulation_form.cleaned_data['number_of_trades'] values_from_all_forms = [] for form in strategy_formset: accuracy = form.cleaned_data['accuracy']/100 take_profit = form.cleaned_data['take_profit'] / 100 stop_loss = form.cleaned_data['stop_loss'] / 100 max_dd_list = [] for simulation in range(0, number_of_simulations): trades = (["W"] * int(number_of_trades*accuracy)) + (["L"] * int(number_of_trades * (1-accuracy))) random.shuffle(trades) current_amount = initial_amount current_amount_list = [] profit_list = [] for trade in trades: if trade == "W": current_amount = current_amount + current_amount*take_profit … -
Issue with Database Queries in Authenticated Django API Calls Despite JWT Verification
Each time an authorized API call is made using a bearer token (specifically a simple JWT), a database query is executed to retrieve user details, even though JWT Authentication is supposed to eliminate the need for database validation. Could someone help me understand the reason behind these database queries and suggest a solution to avoid them while still ensuring proper authentication through JWT? Your insights would be greatly appreciated! When making a request to a Django API with a JWT bearer token, an extra database call is initiated to retrieve user details associated with the user ID specified in the token payload. SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 2 LIMIT 21; args=(2,); alias=default . The execution of this database query is unexpected, and I am unsure about the reason for its occurrence. Can anyone assist me in determining the cause of this DB Query? -
"500 Internal Server Error During Sign-Up"
I am getting error when i tried to signup in my django project, error is given below, enter image description here urls.py views.py templates and all the related files and code are provided below, may you please check it and tell me why i am getting this error? urls.py from django.urls import path from . import views app_name = "users" urlpatterns = [ path('', views.AccountView.as_view(), name="account"), path('profile/', views.profile_view, name="profile"), path('sign-up', views.SignUpView.as_view(), name="sign-up"), path('sign-in', views.SignInView.as_view(), name="sign-in"), path('sign-out', views.sign_out, name="sign-out"), ] views.py from django.shortcuts import render, redirect, reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.conf import settings from django.http import JsonResponse from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.utils.decorators import method_decorator from django_google_api.mixins import( AjaxFormMixin, reCAPTCHAValidation, FormErrors, RedirectParams, ) from .forms import ( UserForm, UserProfileForm, AuthForm, ) result = "Error" message = "There was an error, please try again" class AccountView(TemplateView): ''' Generic FormView with our mixin to display user account page ''' template_name = "users/account.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance = up) if request.is_ajax(): form … -
After Django update to 4.2.6: The requested resource was not found on this server
I have a funny situation: My site tells me Not Found: The requested resource was not found on this server.. In the logs I see nothing. But: I also have a running django-huey worker (multiple actually) and they run just fine. Even funnier: admin section works without problems. -
using django smart_selectors with django_cities_light not working
I am using django cities_light, but what I want is: Region drop down to be depend on Country and city drop down on region. for achieving this I installed smart_selectors to flirter them using ChainedForeignKey and The Strange thing is, it worked for the first time but when I checked it other day it wont wrok anymore. this is the code I am using from smart_selects.db_fields import ChainedForeignKey from cities_light.models import Country, City, Region Class Address(Models.Model): #i tried this before did not work #country = models.ForeignKey('cities_light.Country', #on_delete=models.SET_NULL, null=True, #blank=True) # Country, City and State country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True) region = ChainedForeignKey( Region, chained_field="country", chained_model_field="country", show_all=False, auto_choose=True, null=True ) city = ChainedForeignKey( City, chained_field="state", chained_model_field="region", show_all=False, auto_choose=True, null=True ) I am attaching screenshot and they dont get chained somehow I dont know what I am doing wrong I was expeting them to chained and fliter regions and then cities xD -
I Want To Add Creat Super user By Using Custom User Model
enter image description here My Models Here I Use AbstractUser in My Class class CustomMyUserModel(AbstractUser): username = None phone_number = models.CharField(max_length=100, unique=True) email = models.EmailField(unique=True) user_bio = models.CharField(max_length=50) user_profile_image = models.ImageField(upload_to='upload') USERNAME_FIELD = 'phone_number' REQUIRED_FIELD = [] This Is Code Of Migrations.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, phone_number, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number Is required:') extra_fields['email'] = self.normalize_email(extra_fields['email']) user = self.model(phone_number = phone_number, **extra_fields) user.set_password(password) user.save(using = self.db) return user def create_superuser(self, phone_number, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(phone_number, password, **extra_fields) ^C(overrideuser) hamza@hamza-HP-EliteBook-840-G1:~/PycharmProjects/pythonProject2/OverrideUser$ python manage.py createsuperuser Phone number: 030476701645 Email: hamzabiall@gmail.com Password: Password (again): Traceback (most recent call last): File "/home/hamza/PycharmProjects/pythonProject2/OverrideUser/manage.py", line 22, in main() File "/home/hamza/PycharmProjects/pythonProject2/OverrideUser/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 88, in execute return super().execute(*args, **options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/hamza/PycharmProjects/pythonProject2/overrideuser/lib/python3.10/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 233, in handle self.UserModel._default_manager.db_manager(database).create_superuser( TypeError: UserManager.create_superuser() missing 1 required positional argument: 'username' -
django error - InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency userauth.0001_initial
hello i get this error when i run the command below: python manage.py migrate what should I do? I comment the 'django.contrib.admin', but I get another error =) : RuntimeError: Model class django.contrib.admin.models.LogEntry doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. what should I do with this issue? -
Django REST API Error: FOREIGN KEY constraint failed
In my django api, am able to successfully create admin users as well as normal users. This is the code for my models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None, **extra_fields): if not phone: raise ValueError('The phone field must be set') user = self.model(phone=phone, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', 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(phone, password, **extra_fields) class Users(AbstractBaseUser, PermissionsMixin): unique_code = models.TextField() fname = models.TextField() lname = models.TextField() email = models.EmailField(unique=True) phone = models.TextField(unique=True) sex = models.TextField() country = models.TextField() date_of_birth = models.TextField() image = models.TextField(default=None, blank=True, null=True) district = models.TextField() subCounty = models.TextField() village = models.TextField() number_of_dependents = models.TextField() family_information = models.TextField() next_of_kin_name = models.TextField() next_of_kin_has_phone_number = models.IntegerField(default=None, blank=True, null=True) next_of_kin_phone_number = models.TextField(default=None, blank=True, null=True) pwd_type = models.TextField(default=None, blank=True, null=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) REQUIRED_FIELDS = ['unique_code', 'fname', 'lname', 'phone'] USERNAME_FIELD = 'email' objects = CustomUserManager() def __str__(self): return self.phone Am using token authentication and this is my code for auth from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.response import …