Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django override save method problem that create two different ids for the meeting
I had override a save method for my Meeting model which will generate a random id for the meeting_ID whenever user create a meeting. The save method itself is successful but the problem is that somehow the override save() method generate two random ids instead of just one for the created meeting. Meaning that when I click on Save button, it will create two identical meetings with different meeting_ID. I don't know what is the issue as I'm a beginner for Django. Thanks in advance. Model.py class Meeting(models.Model): MEETING_STATUS = ( ('Coming Soon', 'Coming Soon'), ('Live', 'Live'), ('Closed', 'Closed') ) meeting_ID = models.CharField(primary_key=True, max_length=6, validators=[RegexValidator(r'^\d{6,6}$')], null=True) meeting_title = models.CharField(max_length=400, null=True) meeting_date = models.DateField() meeting_time = models.TimeField() meeting_desc = models.CharField(max_length=500, null=True) meeting_status = models.CharField(max_length=200, null=True, choices=MEETING_STATUS) date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return self.meeting_ID def save(self, *args, **kwargs): meetingID = random.randint(100000,999999) if not Meeting.objects.filter(meeting_ID=str(meetingID)).exists(): self.meeting_ID = str(meetingID) print(self.meeting_ID) super(Meeting, self).save(*args,**kwargs) class Resolutions_Meeting(models.Model): reso_ID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) resolution = models.CharField(max_length=400) meeting_id = models.ForeignKey(Meeting, related_name="has_meetings", on_delete=CASCADE, null=False) def __str__(self): return str(self.meeting_id) Views.py class MeetingsCreate(CreateView): model = Meeting template_name = 'meetings/create_meetings.html' # fields = ['meeting_ID', 'meeting_title', 'meeting_date', 'meeting_time', 'meeting_desc', 'meeting_status'] form_class = MeetingForm success_url = None def get_context_data(self, **kwargs): data = super(MeetingsCreate, self).get_context_data(**kwargs) … -
Add date from external API to view response - Django
I'm trying to add some data from an external API to a view response. My view already send data from my database, and I want to add some data from an external API call in the view. Models: class Currency(models.Model): """Store information about a currency asset.""" id = models.IntegerField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Price(models.Model): """Store price about a currency asset.""" currency = models.ForeignKey(Currency, related_name="price", on_delete=models.CASCADE) price = models.FloatField(blank=True, null=True) View: class CurrencyViewSet(viewsets.ModelViewSet): serializer_class = serializers.CurrencySerializer queryset = models.Currency.objects.all() def get_queryset(self): currencies = self.request.user.currencies_set.all() ids = [currency.id for currency in currencies] price = fetch_currency_price(ids) # fetch from external api for currency in currencies: currency.price.set(Price(currency_id=currency.id, price=price.get('id')) return currencies Which doesn't work. I got tons of different errors and I can't figure it out. -
Uncaught TypeError: $(...).modal is not a function with webpack using bootstrap in django application
Scoured stackoverflow and played around with webpack plugin config, but still getting Uncaught TypeError: $(...).modal is not a function even when importing Bootstrap's .modal function through webpack. The imports I have tried in the file to use Bootstrap's .modal function are import 'bootstrap' and import 'bootstrap/js/dist/modal'. These imports were directly in the file that they were being used in. Every other import works except for bootstrap it seems. webpack.config.js module.exports = { mode: 'development', entry: { index: './objectivedeck/static/js/index.js', unauthed: './objectivedeck/static/js/unauthed.js' }, output: { filename: 'main.js', filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), sourceMapFilename: "[name].js.map" }, devtool: "source-map", plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', Popper: ['popper.js', 'default'], Modal: 'exports-loader?Modal!bootstrap/js/dist/modal', }), ] } I have installed exports-loader and everything is compiling and the js is being bundled to the output without any errors. Since I was having trouble with the source map files I had stackoverflow-ed a solution so you'll see I have added a seperate output that may not usually be there (sourceMapFilename: "[name].js.map") but it resolved the source map issue. Sadly it didn't solve the issue with .modal. One thing I have maybe brought it down to was that somehow bootstrap isn't seeing jquery and it's not creating … -
Why do I need to specify HTML file in render()
Why do I need to give html file name in render() - I have already set url in my project file in urls.py in django urls.py url('view-books',views.viewBooks) views.py def viewBooks(request): books=models.Book.objects.all() res=render(request,'BRMapp/view_book.html',{'books':books}) Why can I not give in render view-books? -
Django Queryset - Get counts by model.choices
I have below model, which has all the details about customer Leads. Customer wants to see his Leads followup statuses. class FollowUp(models.Model): CALL_CHOICES = [("0", "Call Unanswered"), ("1", "Call Later"), ("2", "Visit Scheduled"), ("3", "Not Visited"), ("4", "Not reachable"), ("5", "Wrong Number"), ("6", "Not Interested"), ("7", "Deal Closed")] status = models.CharField(_("Call Status"), max_length = 20, choices = CALL_CHOICES, default = '1' ) next_action_on = DateTimeField(_("Next Action"), auto_now_add=False, null=True, blank=True) reminder = models.BooleanField(_("reminder"), default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Lead(models.Model): followups = models.ManyToManyField(FollowUp, verbose_name=_("Follow up"), blank=True) ... How can I get Lead counts of each status choice. such as { 'Call Unanswered': 12 #Leads, 'Call Later': 10 # Leads 'Visit Scheduled': 20, #Leads, ... } -
I am not able to uplaod image in django ekeditor
I want to text editor just like stack over flow have for the images i can edit the image properly as well as text i watch some videos they show that they can do this by configuring the django setting django project url i did the same now i was able to paste image in the text fiels editor but it was only for the superuser for the user in frontent they can upload it shows when i search on google it says this error because ckeditor is develop with default login required for the admin you can read the same documentation here read here so when i fololow the things it say says gives me bigger error now nobody can upload images it says error 404 -
How to save env variable in osX in django
this might occur as a naive question. I am using cookie cutter django template and have to set env variables every time restarts the project. I am doing the following every time I start working on the project export env_var_for_project=some_value What I need to do in order to have these variables stored so that I don't have to export every time I open up my project -
How to know when chained django lifecycle hooks/signals are finished running?
I have an Animal model and a Herd model that looks like this: from django_lifecycle.hooks import AFTER_CREATE class Animal(models.Model): parent = OneToOneField("self", related_name="child") age = IntegerField() class Herd(models.Model): animal = OneToOneField(Animal) total_age = IntegerField() @hook(AFTER_CREATE) def create_animal_child(self): if self.animal.child.exists(): Herd.objects.create(parent=self, animal=self.animal.child) def save_total_age(self): total_age = self.animal.age position = self.animal while position.child.exists(): total_age += position.child.age position = position.child The idea being that you create your Animals. Then you create your Herd for the topmost animal you want. The Herd's AFTER_CREATEwill then create a "chain" of all the Herd objects for the Animal's children, the children's children, and so on. E.g. a1 = Animal.objects.create(age=10) a2 = Animal.objects.create(parent=a1, age=7) a3 = Animal.objects.create(parent=a2, age=3) h1 = Herd.objects.create(animal=a1) # Two Herd objects with an "animal" field pointing to a2 and a3 respectively are automatically created h1.save_total_age() # h1.total_age = 20 # 10 + 7 + 3 Which is all fine. My problem is for my front-end, how can I tell when all the relevant Animal AFTER_CREATE hooks have finished running so I know to call my calculate_total_age method? So say I have the following REST API endpoints: example.com/api/animals/<pk> example.com/api/herds/<pk> example.com/api/herds/<pk>/save_total_age If I do a POST to example.com/api/herds/<pk> to create a Herd, I call save_total_age() as … -
ModuleNotFoundError: No module named 'setuptools_rust' when deploying Django app to AWS Elastic Beanstalk
I have a Django web app that I wish to deploy to elastic beanstalk. I have cryptography package inside requirements.xml. When I do eb deploy it gives ModuleNotFoundError: No module named 'setuptools_rust' error. I created requirements.txt with pip freeze command. What's wrong with setuptools_rust? -
Problem installing mysqlclient for Django project (macOS)
When connecting my Django project to a database hosted on a remote VM, when I run python3 manage.py run server I get the error django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? when I try python3 -m pip install mysqlclient to resolve the dependency, I get the error ERROR: Could not find a version that satisfies the requirement mysqlclient (from versions: 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.3.10, 1.3.11rc1, 1.3.11, 1.3.12, 1.3.13, 1.3.14, 1.4.0rc1, 1.4.0rc2, 1.4.0rc3, 1.4.0, 1.4.1, 1.4.2, 1.4.2.post1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 2.0.0, 2.0.1, 2.0.2, 2.0.3) ERROR: No matching distribution found for mysqlclient I'd like to understand what is causing these issues and how to resolve it. Thanks in advance! -
Django url file is calling the wrong function
I'm trying to call a function to write a file, but my Django url.py seems to be calling the markdown function. When you press the submit button on the form in the HTML, you get an error that throws at the line "if query["q"] in entries:". HTML <h1>New Page</h1> <form action="{% url 'newPage'}" method="POST"> {% csrf_token %} <div class="form-group"> <label for="title">Title</label> <input type="text" class="form-control" id="title" name="t" placeholder="Title"> </div> <div class="form-group"> <label for="content">Content</label> <textarea class="form-control" id="content" rows="10" name="c" placeholder="Markdown content"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> views.py def markdown(request, entry): pathOfFile = "entries/" + entry + ".md" entries = util.list_entries() query = request.POST if request.method == "POST": if query["q"] in entries: return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path("entries/"+query["q"]+".md") }) else: searchResults = [] if query["q"] in entries: for i in entries: if query["q"] in i: searchResults.append(i) return render(request, "encyclopedia/search.html", { "searchResults": searchResults }) else: return render(request, "encyclopedia/error.html") else: if (entry in entries): return render(request, "encyclopedia/entry.html", { "html_markdown": markdown2.markdown_path(pathOfFile) }) else: return render(request, "encyclopedia/error.html") def newPage(request): if request.method == "POST": query = request.POST title = query["t"] content = query["c"] util.save_entry(title, content) else: return render(request, "encyclopedia/newPage.html") urls.py urlpatterns = [ path("", views.index, name="index"), path("error", views.error, name="error"), path("newPage", views.newPage, name="newPage"), path("<str:entry>", views.markdown, name="entry") -
ModuleError: No module named <appname>.url
I have been trying to make a django project, but I can't make an app. python3 manage.py startapp app In settings.py: INSTALLED_APPS = [ 'app', <All other django.things> ] In urls.py: from django.urls import path, include urlpatterns = [ path('app/', include('app.urls')), path('admin/', admin.site.urls), ] Note: These are exerpts But I still get this error: ModuleNotFoundError: No module named 'app.urls' -
Detect When Entire Field is Empty / Has No Inputs - Django - Python
I need a way to detect when all a field in my models has no entries in it at all. I need it to see every submitted entry and detect when a field has been left blank every single time. I know this is possible using {% empty %} in a forloop but that works for the whole forloop. Do I so this is my views.py? views.py def repo1(request): context = {} context['Add_Repo'] = Add_Repo.objects.filter(user=request.user) context['Data_Repo1'] = Data_Repo1.objects.filter(user=request.user) context['Field_Repo1'] = Field_Repo1.objects.filter(user=request.user) return render(request, 'sheets/list_repo/repo1.html', context) Data_Repo1 contains the data that I need to detect if a field is left completely empty and what field that is. HTML {% for post in Data_Repo1 %} <tr> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date1 %}{{ post.date1 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date2 %}{{ post.date2 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> <td><div><a href="{% url 'update_extinguisher' pk=post.pk %}" style="color: black;">{% if post.date3 %}{{ post.date3 }}{%else%}<span style="color: white;">None</span>{%endif%}</a></div></td> </tr> <tr> {% endfor %} I'm really stuck and just don't know if it's possible at this point. Thanks! -
Python Django web design
I am working on a project where the front-end is in Angular, HTML, CSS and the back-end is in Python and Django. Whenever I develop a new feature or do an enhancement or fix a bug, I would like to have a guide of where it would be best to do so i.e. at the front-end or the back-end? If at front-end it would be best as component or as a service. If at back-end as a view, as a new model/model field etc. Hence, I am looking for resources e.g. books, web-sites to read about principles of designing optimally a front-end/back-end and the related API. Also, that would be helpful to support and explain my design choices to my teammates and any stakeholders. What would you suggest? -
Could not resolve URL for hyperlinked relationship using view name "rest:campaign-detail"
A newbie here in the world of Django. I am struggling with creating a hyperlink for a nested route. The error I am getting is: Could not resolve URL for hyperlinked relationship using view name "rest:campaign-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field. Some project setup notes using DRF-extensions to create the routes Using ModelViewSet Expected end points: https://.../accounts/ https://.../accounts/< pk >/ https://.../accounts/< pk >/campaigns/ https://.../accounts/< pk >/campaigns/ https://.../accounts/< pk >/campaigns/adgroup/ https://.../accounts/< pk >/campaigns/adgroup/< pk > Set a namespace of rest in urls.py Using HyperlinkedIdentityField to create the hyperlink. It works if with the parent object i.e url = serializers.HyperlinkedIdentityField(view_name='rest:account-detail') However fails with the nested object i.e. url = serializers.HyperlinkedIdentityField(view_name='rest:account-detail') The model is quiet simple, an Account can have many Campaigns, and a campaign can have many AdGroups. See code below: models.py from django.db import models from django.db.models import Q from model_utils import Choices ORDER_COLUMN_CHOICES = Choices( ('0', 'id'), ('1', 'keyword'), ('2', 'status'), ('3', 'match_type'), ) # Account class Account(models.Model): account_name = models.CharField(max_length=128) def __str__(self): return self.account_name # Campaign class Campaign(models.Model): class Status(models.TextChoices): Enabled = "Enabled" Paused = "Paused" account = models.ForeignKey( to=Account, on_delete=models.CASCADE, related_name='campaigns' ) … -
How to insert wildcard for each word in Django query?
I'm using Django's CharFilter with lookup_expression icontains, but noticed that it's the SQL equivalent to: '%director eng%' when I actually want '%director%eng%' What's the best way to insert wildcard for each word in query? Here's what I have in my filters.py role = django_filters.CharFilter(field_name ='title', lookup_expr='icontains', label="Role:") And here's what I have in my HTML file: <input type="search" name="role" class="form-control" placeholder="Any"> Maybe I need a custom lookup expression? -
Django variable not workign when empty POST
I have the following template in django. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Question</title> </head> <body> <h1>{{ question.question_text }} {{ question.id }}</h1> <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {% if question.choice_set.all %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> {% endfor %} <br> <input type="submit" value="Vote"> {% else %} <p>No choices available.</p> {% endif %} </form> </body> </html> If I select a value for the form, it will work correctly and POST to /polls/1/vote/. However if I leave the form empty and submit, I get an error: NoReverseMatch at /polls/1/vote/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$'] Here is my urls.py: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.DetailView.as_view(), name = 'detail'), path('<int:question_id>/vote/', views.vote, name='vote'), path('<int:question_id>/results/', views.results, name='results'), ] -
How can I use SearchRank in a Django model field?
I have a model Post: class Post(models.Model): post_title = models.CharField(max_length=120) post_subtitle = models.TextField() post_text = models.TextField() vector_column = SearchVectorField(null=True) class Meta: indexes = (GinIndex(fields=['vector_column']),) and I've created a trigger in the database to update the vector_column value: create function core_post_trigger() returns trigger as $$ begin new.vector_column := setweight(to_tsvector('pg_catalog.english', coalesce(new.post_title, '')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.post_subtitle, '')), 'B') || setweight(to_tsvector('pg_catalog.english', coalesce(new.post_text, '')), 'C'); return new; end $$ language plpgsql; create trigger vector_column_trigger before insert or update on core_post for each row execute procedure core_post_trigger(); And I search through this model like this: Post.objects.filter(vector_column=SearchQuery(query, config='english', search_type='websearch') Although I've applied weights in this search, I did not apply ranking (to_tsrank). I know that I can apply rank in Django like this: vector = SearchVector('post_title', weight='A', config='english) + SearchVector('post_subtitle', weight='B', config='english') + SearchVector('post_text', weight='C', config='english') query = SearchQuery(query, search_type="websearch") Post.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank') The question is that I don't know how to use SearchRank with my vector_column column, as this column has a GinIndex. If I use this vector variable created above, I will not use the index, and then this search will be slow. I've tried to write this query in various ways, but I don't know how to do. I tried, for example, this: Post.objects.annotate(SearchRank(vector_column, … -
AWS RDS rename database name
I have a database created with RDS and I want to rename it. But whenever I try to modify it through the AWS console, the option for the database name is gone. And when I try it through the shell, it's showing an error. I just need to rename the DB name from postgrestestdatabase to a new one. -
403 Error "Authentication credentials were not provided" in Safari, but not in Chrome, Edge, Firefox, etc. [Django + Next.js]
Currently i'm having problems running my page in Safari and iOS devices (even with chrome browser). The main problem is that Safari is returning 403 errors in some endpoints, but the token was sent and this is only happening in this browser. For example: get_quantites enpoint with status 200 -
How to filter based on another model in Django ModelViewSet?
I currently have a SiteViewSet using ModelViewSet that can list, retrieve, create, and update sites from the model Site. I want to add a filter to the same SiteViewSet that lists all the site objects where is_active is True - but this condition is based on the AdminConfiguration model. I was not able to find how to implement a filter in ModelViewSet based on conditions of another model. Is the filtered endpoint /v1/site/?is_active=True possible to implement in the same SiteViewSet with ModelViewSet or should I create a separate view via a more flexible APIView? SiteViewSet: class SiteViewSet(viewsets.ModelViewSet): model = Site lookup_field = 'uuid' pagination_class = PageNumberPagination serializer_class = SiteSerializer queryset = Site.objects.all() Site Model: class Site(models.Model): uuid = models.UUIDField( default=uuid.uuid4, unique=True) domain_name = models.CharField(max_length=255, unique=True) AdminConfiguration Model: class AdminConfiguration(models.Model): site = models.OneToOneField( Site, on_delete=models.CASCADE) always_active = models.BooleanField(default=False) subscription_ends = models.DateTimeField( default=set_default_expiration) @property def is_active(self): active_status = self.always_active or self.subscription_ends > timezone.now() return active_status -
When deploying updated Django code on server, the database resets
I have built an app built which uses Django as Rest API (Django rest framework). After having deployed the code on digital ocean using production grade services, everything works well. The database populates itself correctly . There is no reset of the server like on Heroku. Except, if I change a file and push the changes through gitlab which are then picked up by Digital ocean who automatically deploy the updated version of the server), the database resets to its original state. I have removed all migration files before pushing updates, but to no avail. I imagine it has to be something rather trivial but I can't find it. this makes it impossible for me to go into production -
why unable to import a model in django (most likely due to a circular import)?
I am working on a small application for learning purpose, and created a three models CustomUser, UserProfile and PollQuestion. CustomUser and UserProfile having OneToOne field. And UserProfile and PollingQuestion having ForeignKey relation between them, i am also posting and code snippet bellow:- CustomUser And UserProfile models:- from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.signals import post_save from polls.models import PollQuestion # Create your models here. class CustomUser(AbstractUser): email = models.EmailField(max_length=250, null=False) name = models.CharField(max_length=50, null=False) username = models.CharField(max_length=50, null=False, unique=True) password = models.CharField(max_length=15, null=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = [] class UserProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def get_all_polls(self): all_polls = PollQuestion.objects.all().count() return 10 PollingQuestion:- class PollQuestion(models.Model): question = models.TextField(max_length=250) user = models.ForeignKey(UserProfile, null=True, on_delete=models.CASCADE) option_one = models.CharField(max_length=250, null=False) option_two = models.CharField(max_length=250, null=False) option_three = models.CharField(max_length=250, null=False) option_four = models.CharField(max_length=250, null=False) option_one_votes = models.IntegerField(default=0) option_two_votes = models.IntegerField(default=0) option_three_votes = models.IntegerField(default=0) option_four_votes = models.IntegerField(default=0) When i tried to run the command python manage.py makemigrations got following error:- Traceback (most recent call last): File "C:\Users\akcai\OneDrive\Desktop\deep_stuffs\PollingApplication\manage.py", line 22, in <module> main() File "C:\Users\akcai\OneDrive\Desktop\deep_stuffs\PollingApplication\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_li ne utility.execute() File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 395, in execute django.setup() File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\akcai\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", … -
How can I cast a DateField() + TimeField() to local time in a Django QuerySet?
My model as these fields: date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() I would like to annotate the queryset with start_datetime and end_datetime, like so: class SessionQuerySet(models.QuerySet): def with_datetimes(self): return self.annotate( start_datetime=ExpressionWrapper( F('date') + F('start_time'), output_field=models.DateTimeField() ), end_datetime=ExpressionWrapper( F('date') + F('end_time'), output_field=models.DateTimeField() ), ) However, the output field in the query results in a naive datetime: >>> Session.objects.with_datetimes()[0].start_datetime <<< datetime.datetime(2021, 9, 20, 17, 0) I tried wrapping the above expressions in django.db.models.functions.Cast(), with output_field=DateTimeField(), but it casts to UTC and not the local timezone. Essentially what I need is the equivalent of the Postgres at time zone feature to convert a naive time to localtime. Is there a way to do that in Django? -
Django Admin Login --> Redirect on Login to another Page
Good evening, I am currently trying to solve a problem with Django Admin. I want to do this steps: 1.) If I visit localhost:8000/admin --> the Admin Login appears 2.) If I log in with credentials --> it should redirect me to localhost:8000/test_page and not to the localhost:8000/admin page. 3.) If I revisit localhost:8000/admin while I am logged in, it should show me the admin page. I was already looking in /python3.x/dist-packages/django/contrib/admin/sites.py but couldn`t find the code piece to make 2.) and 3.) work. Anyone got an idea or could help me ? Thanks :)