Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: Update dabatase table with a formset
I am confused about formsets. I built a form and a view to insert one database table row that working just fine, and I just built a formset in a view to be able to insert several rows at once. My issue is that the formset does not seem to work. Nothing gets changed in the DB. Here is what my form look like: class ProcurementOperationRecordForm(forms.ModelForm): class Meta: model = replenishment fields = ('Id', 'Quantity', 'NetAmount', 'Supplier', 'SellPrice') and here is what my former view looked like: #def New_Purchase(request): #if request.method == 'POST': #form = ProcurementOperationRecordForm(request.POST) #if form.is_valid(): #form.save() #quantity = form.cleaned_data.get('Quantity') #id = form.cleaned_data.get('Id') #update = replenishment.objects.filter(Id = id).update(StockOnOrder =+ quantity) #update2 = Item2.objects.filter(reference = id).update(en_cours_de_reception =+ quantity) #quantity = form.cleaned_data.get('Quantity') #id = form.cleaned_data.get('Id') #update = replenishment.objects.filter(Id = id).update(StockOnOrder = (StockOnOrder + quantity)) #return redirect('/dash2.html') #else: #form = ProcurementOperationRecordForm() #context = {'form': form,} #return render(request, 'new_purchase.html', context) and here is what my formset view looks like: def New_Purchase(request): context = {} form = formset_factory(ProcurementOperationRecordForm, extra = 3) formset = form() context['formset'] = formset return render(request, 'new_purchase.html', context) I don't know what to do to make this formset works, would someone have a clue that could unblock the situation? -
Django internationalization doesn't work on my system
It has been several hours I am going through answers in Stackoverflow and looking documentation to solve this. I recently asked this question explaining why Django internationalization doesn't work in my project. I downloaded gettext versions from here. I am asking this question because I restarted a new project from scratch set up everything for Django translation, but still this new project doesn't work as well. What is happening? any hint or clue please. It sounds it is something outside Django in my installation or computer or what I don't know? Thank you -
Changing render context data if Post request
I would like to change my variable data according to what i get from my post request. Print(data) return correct values in my console but data in my template is still equal to Post.objects.all() even if my inp = "radio-two" or "radio-three". views.py @csrf_exempt def update_radio(request): post = Post.objects.all() tag = Tag.objects.all() editor = EditorProfile.objects.all() data = Post.objects.all() if request.method == 'POST': print("get input") print("update radio post request") inp = request.POST.get('input',None) if(inp == "radio-two"): data = post elif(inp == "radio-three"): data= editor else: data = tag print(data) return render(request, 'blogapp/radio2.html',{'data':data}) -
My Django project can't import shortcuts (Pylint Import Error)
Unable to import 'django.shortcuts'pylint(import-error) how can i solve this error -
Django ORM query two ManyToMany relationships, via a ForeignKey relationship
class ThingDefinition(models.Model): ... class Thing(models.Model): definition = ForeignKey(ThingDefinition) class FooGroup(models.Model): thing_definitions = ManyToManyField(ThingDefinition, blank=True) class Bucket(models.Model): contents = ManyToManyField(Thing, blank=True) foo_group = ForeignKey(FooGroup) @property def prop(self): expected_contents = {self.foo_group.thing_definitions} actual_contents = {x.thing_definition for x in self.contents} return bool(expected_contents.difference(actual_contents)) I am trying to write a django ORM query tog get the value of prop. I have written some python which gives the right answer; it is too slow to use, but it should make it clear what I am trying to achieve. To summarise in English: For each Thing in the many to many field self.contents, get the value of the foreign key to ThingDefinition Follow the foreign key relationship self.foo_group, and get the values of the ManyToManyField thing_definitions. Compare these two querysets, and return True if the latter contains things not contained in the former. -
Have Django templates render registration/login form and React rest of the application
Is it a good approach to have Django built-in templates to handle login/registration views, which on successfull login would redirect to a login required view with html template that has the React application embeded in it? Rest of the communication would be a django-rest-framework and React-query or redux-saga on the frontend. Obviously no request without the user authorized will be allowed. -
Using Factory Boy inside a dict for a data model factory in Django? Alternatively, getting FactoryBoy to evaluate subfactory on demand?
I have the following ModelFactory: class ProjectDataModelFactory(DjangoModelFactory): project = factory.SubFactory("projects.factories.ProjectModelFactory") version = "1" content = { "id": {"value": fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(), "type": "string"}, "win_probability": {"value": fuzzy.FuzzyInteger(0, 100).fuzz(), "type": "number"}, "bid_value": { "value": fuzzy.FuzzyInteger(0, 10000000).fuzz(), "type": "number", }, "status": {"value": random.choice(["Won", "Lost"]), "type": "string"}, "sector": { "value": random.choice( ["Construction", "Technology", "Finance", "Consulting", "Agriculture", "Engineering"] ), "type": "string", }, } In content["id"], I would like to have value be project.external_id instead of fuzzy.FuzzyText(length=7, chars=string.ascii_letters).fuzz().upper(). external_idis part of the ProjectModel. But when I put project.external_id in the place of the fuzzer, I get this error: AttributeError: 'SubFactory' object has no attribute 'external_id This only seems to be a problem with dicts. We have not had issues using it in other contexts. I do not have a lot of experience using FactoryBoy, so it could easily be something trivial. Any ideas? -
No modules named _sqlite3 when starting Django project on a shared hosting site
I am using a shared hosting site (centOS) to host my Django site. I can get python 3.8.5 running and Django installed, but if I run python manage.py shell, I get the following error output Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home4/bendempe/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home4/bendempe/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home4/bendempe/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home4/bendempe/python/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home4/bendempe/python/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home4/bendempe/python/Python-3.8.5/Lib/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home4/bendempe/python/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home4/bendempe/python/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/base.py", line 122, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/base.py", line 326, in add_to_class value.contribute_to_class(cls, name) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/models/options.py", line 206, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home4/bendempe/python/lib/python3.8/site-packages/django/db/utils.py", … -
get value form and if it is null, leave the field empty for input
hi I have automated my field but if the value to be retrieved is null it puts error undefined method for nil: NilClass how I solve this problem in the view with get value Controller def show @ref_entraineur = CarriereDocumentFootballeur.where(id: params[:id]) end in views <%= f.text_field :num_entraineur , label: "Numéro Entraineur " , value: @ref_employeur.last.num_entraineur %> -
How to solve round() bug in python? [duplicate]
I recently found out that round function gives wrong output sometimes.Can anyone plz solve this? print(round(60256.5)) And the expected output was 60257. But instead it was 60256 -
Django Celery Scheduled Task Crashing
Im trying to run a scheduled task on my Django project that is hosted on Heroku, however my task keeps crashing and I dont know how to fix this. Here is the error message bellow I'm getting in the error logs. I have in my settings.py my timezone set to 'America/New_York' and I even tried added the time zone as well in the celery.py to be the same to try to troubleshoot it but has no affect on it. I appreciate the help. Thanks Full Traceback 2020-09-29T14:42:42.978802+00:00 app[beat.1]: [2020-09-29 10:42:42,978: INFO/MainProcess] DatabaseScheduler: Schedule changed. 2020-09-29T14:42:42.978947+00:00 app[beat.1]: [2020-09-29 10:42:42,978: INFO/MainProcess] Writing entries... 2020-09-29T14:42:43.007143+00:00 app[beat.1]: [2020-09-29 10:42:43,006: INFO/MainProcess] Writing entries... 2020-09-29T14:42:43.009099+00:00 app[beat.1]: [2020-09-29 10:42:43,007: CRITICAL/MainProcess] beat raised exception <class 'TypeError'>: TypeError("can't compare offset-naive and offset-aware datetimes",) 2020-09-29T14:42:43.009100+00:00 app[beat.1]: Traceback (most recent call last): 2020-09-29T14:42:43.009101+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/apps/beat.py", line 109, in start_scheduler 2020-09-29T14:42:43.009102+00:00 app[beat.1]: service.start() 2020-09-29T14:42:43.009103+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 631, in start 2020-09-29T14:42:43.009103+00:00 app[beat.1]: interval = self.scheduler.tick() 2020-09-29T14:42:43.009104+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 329, in tick 2020-09-29T14:42:43.009104+00:00 app[beat.1]: self.populate_heap() 2020-09-29T14:42:43.009105+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/celery/beat.py", line 303, in populate_heap 2020-09-29T14:42:43.009105+00:00 app[beat.1]: is_due, next_call_delay = entry.is_due() 2020-09-29T14:42:43.009106+00:00 app[beat.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django_celery_beat/schedulers.py", line 116, in is_due 2020-09-29T14:42:43.009106+00:00 app[beat.1]: if now < self.model.start_time: 2020-09-29T14:42:43.009238+00:00 app[beat.1]: TypeError: can't compare offset-naive … -
Django views opens different content
I am new to Django. I have created 2 seperate views and URLs, however, when I load my development server and click on slides to open slides_detail.html, it opens sub_detail.html, at this point I have no clue what could cause that as there are no similar names which would lead to opening completely different detail page. Both slides and subcontent sits in the same HTML document, same with URLs and views. There are no errors, to show. Thanks in advance: URLS: path('<int:sub_id>/', views.sub_detail, name='sub_detail'), path('<int:slides_id>/', views.slides_detail, name='slides_detail'), Views: # Will show specific sub content details def sub_detail(request, sub_id): subcontent = get_object_or_404(SubContent, pk=sub_id) context = { 'subcontent': subcontent, } return render(request, 'home/sub_detail.html', context) # Will show specific slides content details def slides_detail(request, slides_id): slides = Slides.objects.get(pk=slides_id) context = { 'slides': slides, } return render(request, 'home/slides_detail.html', context) HTML for slides: {% for slides in slides %} <div class="swiper-slide"> <div class="card"> <a href="{% url 'slides_detail' slides.id %}"> <img src="{{ slides.image.url }}" class="card-img-top img-height" alt="..."></a> <div class="card-body bg-dark"> <h5 class="card-title text-light font-weight-bold text-center">{{ slides.title }}</h5> </div> </div> </div> {% endfor %} HTML for subcontent: {% for sub in subcontent %} {% if forloop.counter|divisibleby:2 %} <div class="row"> {% if sub.image %} <div class="col-md-6 section-index-img"> <img … -
local variable 'intent' referenced before assignment
Can anyone please help me to fix this problem local variable 'intent' referenced before assignment i could not find out why client_secret in the context is triggered. to my knowledge if the code in if statement fails then else block will be executed but i have set a print statement and it does not appear in the teminal either. if someone can please help me in solving this issue. from django.shortcuts import render, redirect, reverse from django.contrib import messages from django.conf import settings from .forms import OrderForm from .models import Order, OrderLineItem, ProductLineItem, ExerciseLineItem, NutritionLineItem from merchandise.models import Product from exercise.models import ExercisePlans from nutrition.models import NutritionPlans from cart.contexts import cart_contents import stripe def checkout(request): stripe_public_key = settings.STRIPE_PUBLIC_KEY stripe_secret_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': cart = request.session.get('cart', { 'merchandise_dic': {}, 'excercise_plans_dic': {}, 'nutrition_plans_dic': {}, }) form_data = { 'full_name': request.POST['full_name'], 'email': request.POST['email'], 'phone_number': request.POST['phone_number'], 'country': request.POST['country'], 'postcode': request.POST['postcode'], 'town_or_city': request.POST['town_or_city'], 'street_address1': request.POST['street_address1'], 'street_address2': request.POST['street_address2'], 'county': request.POST['county'], } order_form = OrderForm(form_data) if order_form.is_valid(): print("Order form is valid") order = order_form.save() for product_type, dic in cart.items(): if product_type == 'merchandise_dic': for item_id, quantity in dic.items(): print(f"This is item id of merchandise: {item_id}") print(f"This is quantity of merchandise: {quantity}") product = Product.objects.get(id=item_id) … -
Designing search API endpoint with filter and query
I have been looking into designing a RESTful search endpoint and I think most people would agree that using GET method as the best approach to do it. Lets say I am currently designing a website to sell used car and a search endpoint required to search available cars. How do we handle a search endpoint that allows different query params to be added and how we write the url pattern in django? For example /cars?color=red&year=2010&keyword=audi I guess the url pattern would be re_path(/cars/, views.car) and we get the color, year and keyword using request.GET? What about if we to use the /cars/ endpoint to have more specific search? For example further expand the url to include other parameters /cars/toyota and /cars/california/toyota Does that means I will need to include more url patterns for each param added and possible different view for it? urlpatterns = [ re_path(/cars/?P<brand>[\w]+/, views.car_brand_search), re_path(/cars/?P<state>[\w]+/<?P<brand>[\w]+/, views_car_state_brand_search) ] -
docker-compose: site running but css not applying
I am trying to run my Django app (V 1.8.6) in a docker container using docker-compose. This is my setting.py: MEDIA_ROOT = "/srv/media/" MEDIA_URL = "/media/" STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static") This is my docker compose: version: "3" services: # # Nettle API server # nettle: image: mcvitty_img command: python manage.py runserver 0.0.0.0:8000 --settings=sites.production.settings ports: - "80:8000" volumes: bluebell: {} postgres-data: {} rabbitmq-data: {} I am successfully running the collect static in my Dockerfile: RUN python manage.py migrate --settings=sites.production.settings --fake-initial RUN python manage.py sitetree_resync_apps --settings=sites.production.settings RUN python manage.py collectstatic --settings=sites.production.settings --noinput But sadly this is the result: This are the logs I get: nettle_1 | [29/Sep/2020 15:08:19] "GET /static/css/all.min.css HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/js/all.min.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/autocomplete.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/style.css HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/remote.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/text_widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/autocomplete.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/addanother.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET /static/autocomplete_light/widget.js HTTP/1.1" 404 4463 nettle_1 | [29/Sep/2020 15:08:19] "GET … -
TypeError: argument of type 'PosixPath' is not iterabl
please help i get this error from python manage.py makemigrations Migrations for 'post': post/migrations/0022_auto_20200929_1749.py - Remove field category from post - Remove field tag from post Traceback (most recent call last): File "manage.py", line 22, in main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python3.8/site-packages/django/core/management/base.py", line 336, in run_from_argv connections.close_all() File "/usr/lib/python3.8/site-packages/django/db/utils.py", line 224, in close_all connection.close() File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 248, in close if not self.is_in_memory_db(): File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 367, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/lib/python3.8/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterabl -
Where should I add more parameters to create a user?
I have followed a tutorial to create an application that only has 1 type of user. In my own app, I'm trying to have multiple types of user, and show different pages according to what type of user they are. I find the teacher in the tutorial isn't very clear and I'm not sure how to differentiate between users. So far, all I need for creating a user is username and password. Also, this article was of help but still made me confused. I want to be able to add more fields but, mainly, differentiate between users (whether they're a Player, Manager or Assistant) during registration. I thought of passing a is_player=true in the POST method for registration but I'm not sure how to add this field to Django registration and then how to create a Player or Manager or Assistant. In my models, I DON'T create a User model, but I create e model for Player, Manager and Assistant # no User model. class Team(models.Model): name = ... ... class Player(models.Model): name = team = models.ManyToManyField(Team) class Manager(models.Model): name = players_responsible_For = models.ManyToManyField(Player) In the serializers file, I DO create a UserSerializer alongside serializers for other models. from django.contrib.auth.models … -
Recommended Editor for Git - Nano or Visual Studio code
I am reading through the Djangogirls.org website and they recommend Nano as the default editor when installing Git. I have also installed Visual Studio Code. I'm want to be efficient if I'm doing django and python in Visual Studio should I just use Visual Studio Code as the default editor? This is the first time I that I'll be using Git or anything similar. It might be that I don't understand it. -
Build passes locally but fails on Travis
I'm going through a Django course right now (recorded online), and we use Travis. I've notices that my builds on Travis fail, even though they pass locally. I've tried to look at different files provided by the instructor an compare it to my code but I can't find any difference. Honestly, this is all very fresh to me so I don't really know even where I should be looking, or what part of the code I should be pasting here for the question. This is the end of the Travis build log: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 5432? The command "docker-compose run app sh -c "python manage.py test && flake8"" exited with 1. Done. Your build exited with 1. And this is my repo: https://github.com/Tsabary/recipe-app-api -
using initial on django MultipleChoiceField on many-to-many relation
In my model, I have: flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT) lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True) in my form, I want these to be selectable, based on available FlowCellLanes. So I pop flowcell to a variable and use it to see which 'Lanes' are there: class DemuxerForm(forms.ModelForm): class Meta: model = Demuxer exclude = ["owner", "pid", "flowcell"] lanes = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): self.flowcell = kwargs.pop('flowcell') super().__init__(*args, **kwargs) self.fields['lanes'].choices = sorted([(lane.pk, str(lane.lane_number)) for lane in self.flowcell.lanes.all()]) Now I would like to have all available checkboxes checked. But I don't know how I could do that. At the spot where initial= could be, 'self' is off course not available... any ideas? -
Get Google oauth2 token of users without having google as login option to Django website
I am using gspread to access sheets on behalf of other users. I need to have tokens of the users to do so. I'm fine with users having to give permission on browser one time but dont want Google as signin option to django website. All the search I have done on Oauth2 libraries, they are about making Google as signin option but I just want Google prompting user once to give permission when needed. -
Django orm returning with timezone 0 while I want time zone with specifications
I moved from not using timezone to using timezone but I have a couple of questions about the handling of it. First of all my settings look like this: TIME_ZONE = "Europe/Amsterdam" USE_TZ = True I now get the correct timezone back from the database but not in the right timezone. I suspect that when I have my TIME_ZONE on Europe/Amsterdam that I get that timezone back. But instead I get: 2020-09-27 23:00:07+00:00 But what I want to receive is: 2020-09-27 22:00:00+02:00 I can do this by using timezone.localtime(date_object) But is there a way to get the timezone back in the right format straight from the orm? I am using Postgres 11 and Django 3.0.1 -
How do I run a XMLHttpRequest that relies on another XMLHttpRequest?
I am setting up a social media website where there are posts and comments on posts. The posts and comments are requested using XMLHttpRequest (with a Django, Python backend) here is my post loading code: const xhr = new XMLHttpRequest() const method = 'GET' const responseType = 'json' const url = '/posts' xhr.responseType = responseType xhr.open(method, url) xhr.onload = function() { const serverResponse = xhr.response onst listItems = serverResponse for(var i = 0; i < listItems.length; i++){ var postObj = listItems[i] var currentItem = formatPostElement(postObj) finalPostStr += currentItem // with additional HTML code } postsElement.innerHTML = finalPostStr } xhr.send() // trigger the request This is my code for loading the comments: const xhr = new XMLHttpRequest() const method = 'GET' const responseType = 'json' const url = '/comments' + post_id xhr.responseType = responseType xhr.open(method, url) var input = '' xhr.load = function() { const serverResponse = xhr.response const commentItems = serverResponse for(var q = 0; q < commentItems.length; q++){ input += commentItems[q].content } commentContainerElement.innerHTML = input console.log(input) } xhr.send() The code for the posts grabs every post available in the database. The code for the comments grabs all the comments that are related for a post with post_id. So how … -
Can't login to django admin after successfully creating a super user with a custom user model
imm trying to login to the django admin panel with a successfully created superuser but cannot get the right username/pw combo right. I want users to just use their email as their username. I've deleted migrations, sycndb, and everything works except logging in to the admin panel. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password= None): if not email: raise ValueError('email required') if not username: raise ValueError('username required') user = self.model( email= self.normalize_email(email), username= username, ) user.set_password(password) user.save(using= self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email= self.normalize_email(email), password= password, username= username, ) user.is_admin= True user.staff= True user.is_superuser= True user.save(using= self._db) return user class Accounts(AbstractBaseUser): email = models.EmailField(verbose_name= 'email', max_length= 60, unique= True) username = models.CharField(max_length= 30, unique= True) date_joined = models.DateTimeField(verbose_name= 'date joined', auto_now_add= True) last_login = models.DateTimeField(verbose_name= 'last login', auto_now= True) is_admin = models.BooleanField(default= False) is_active = models.BooleanField(default= True) is_staff = models.BooleanField(default= False) is_superuser = models.BooleanField(default= False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj= None): return self.is_admin def has_module_perm(self, app_label): return True admin.py from django.contrib import admin from .models import Accounts admin.site.register(Accounts) settings.py INSTALLED_APPS = [ … -
Defining DJANGO_SETTINGS_MODULE
I checked my models.py file for any errors by using the command python models.py check and it returned the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. So I entered the command: export DJANGO_SETTINGS_MODULE=project1.settings where project1 is the folder directory that contains the settings.py file. I've also tried replacing "project1" with the name of my virtual environment "bugstracker". Both attempts returned the following error: ModuleNotFoundError: No module named 'project1' ModuleNotFoundError: No module named 'bugstracker' What am I missing here?