Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to generate hash from a queryset?
My idea is to create a hash of a queryset result. For example, product inventory. Each update of this stock would generate a hash. This use would be intended to only request this queryset in the API, when there is a change (example: a new product in invetory). Example for this use: no change, same hash - no request to get queryset there was change, different hash. Then a request will be made. This would be a feature designed for those who are consuming the data and not for the Django that is serving. Does this make any sense? I saw that in python there is a way to generate a hash from a tuple, in my case it would be to use the frozenset and generate the hash. I don't know if it's a good idea. -
Calculate Sum of aggregated fields in a Subquery
How can I calculate the sum of all aggregated fields in a subquery? For example, I have three models: A, B, C. B has FK to A. C has FK to B. I have a query: A.objects .annotate( total_revenue=Subquery( B.objects.filter(...) .revenue() .values("id") .annotate(b_renevue=Sum("revenue")) ) ) where B.revenue() is a method that sums up all related fields and then multiplies them by one of its fields. The problem is that revenue is aggregated and isn't calculated at the moment when I try to sum it. The original exception is : django.core.exceptions.FieldError: Cannot compute Sum('revenue'): 'revenue' is an aggregate -
How to link a field of a model to another models's field in django?
I want to link first_name and last_name field of my extended user model to the base User of Django so that changing the values of the fields in one model also affects the values in the other model. I have extended the Base User Model to store additional information about the user and I need to enable the users to edit all those values along with first_name and last_name with a single form. class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = "Linked to first_name of base User Model" last_name = "Linked to last_name of base User Model" other fields.... -
extends base html issue
i got main page at index.html , i want to transfer my template to base.html. I used {% extends 'base.html' %} at index.html , but he doesn't see this file with *Unresolved template reference ''base.html'' * folder of base.html: project/templates myproject/app/views.py from django.shortcuts import render def index(request): return render(request, 'mainsite/index.html') project/app/urls.py from django.urls import path from .views import * urlpatterns = [ path('', index, name='home'), ] project/setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainsite.apps.MainsiteConfig', ] project/url.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('mainsite.urls')), ] -
Wagtail Customising User Account Settings Form With One-to-One Model
I have a model in my app called "portal", in portal/models.py: from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save from wagtail.snippets.models import register_snippet from wagtail.admin.edit_handlers import FieldPanel @register_snippet class StaffRoles(models.Model): role = models.CharField(max_length=154, unique=True, help_text="Create new staff roles here, these roles an be assigned to 'staff' users.") panels = [ FieldPanel('role'), ] def __str__(self): return self.role class Meta: verbose_name = "Staff Role" verbose_name_plural = "Staff Roles" @register_snippet class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=1024, blank=True) roles = models.ManyToManyField(StaffRoles, blank=True) def __str__(self): return str(self.user.first_name) + " " + str(self.user.last_name) class Meta: verbose_name = "Staff" verbose_name_plural = "Staff" @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created and instance.is_superuser: Staff.objects.create(user=instance) Any new superuser is automatically given the Staff model. Any existing (non superuser) user can also be added as Staff. I want Staff members to be able to set a bio and a role. Roles can be added through the Snippets page in Wagtail admin. Right now, Staff is registered as a snippet, this means any Staff member can edit another Staff member's Staff attributes. I want to customise the Wagtail User Account Settings by adding a form to each user's respective … -
Understanding the purpose of an .env file with Django
Using Docker to deploy a Django + React application, and I've seen that best practice (or at least, one of the best practices) is to store certain pieces of information in an .env file, specifically database information. I am using this strategy now but I am still having trouble getting postgres to work. I am not sure if I still need to create the database locally on my system, or whether Docker handles it automatically. .env DB_NAME=animemusicsorter DB_PASSWORD=root DB_USER=waifuszn DB_HOST=postgres DB_PORT=5432 DEBUG=1 settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": os.environ.get("DB_NAME", "dbname"), "USER": os.environ.get("DB_USER", "dbuser"), "PASSWORD": os.environ.get("DB_PASSWORD", "dbpassword"), "HOST": os.environ.get("DB_HOST", "postgres"), "PORT": os.environ.get("DB_PORT", "5432"), } } Traceback postgres | 2021-07-12 17:21:19.630 UTC [34] FATAL: password authentication failed for user "waifuszn" postgres | 2021-07-12 17:21:19.630 UTC [34] DETAIL: Role "waifuszn" does not exist. -
Is there a build in login/logout endpoint in django rest?
I want to make a login functionality on my app for this i want a login end point does django rest have a built in end point or view to login (i will only be using it for BasicAuthentication). I found many ways online but they were for TokenAuth I just want BasicAuth -
Testing: TypeError: expected str, bytes or os.PathLike object, not NoneType
I'm testing user's creation but the test haven't reach the failed test because of the error given TypeError: expected str, bytes or os.PathLike object, not NoneType. I have the migrations using pass on using the AbstractUser giving the following on the migrations/0001initial.py file: # Generated by Django 3.1.4 on 2021-07-12 15:00 import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')), ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')), ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')), ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')), ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')), ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')), ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their … -
How to implement a fast temporary buffer for Django backend to make an online game?
I am making a "typing-race" online application with Django backend and ReactJS frontend. I wanna implement an online race-kinda logic where the users will be typing the given statements and their current progress will be shown to all other competitors. How should I implement this? Should I go with an AJAX implementation, where a user's progress is posted to the server periodically and other users' progress is fetched periodically? How can I store a current game's live state on the server? Should I use Django channels and WebSockets, but is that really necessary? -
Django 'context' for function-based and class-based views
Help me understand how to use Django's context--Is the issue related to the use of context in function-based vs class-based views: I have created two views (index and post_list) and respective templates (following the Assessment portion of the Mozilla Django Tutorial). The code for index works, but identical code for post_list doesn't. Why is that? view #1 def index(request): post_list = Post.objects.all() num_posts = Post.objects.all().count() num_comments = Comment.objects.all().count() num_authors = Author.objects.count() num_commenters = Commenter.objects.count() context = { 'num_posts': num_posts, 'num_comments': num_comments, 'num_authors': num_authors, 'num_commenters': num_commenters, 'post_list' : post_list, } return render(request, 'index.html', context=context) template #1 --Works: {% block content %} <h1>Index:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} view #2 class PostListView(generic.ListView): model = Post post_list = Post.objects.all() num_posts = Post.objects.all().count() num_authors = Author.objects.count() template_name = 'blog/post_list.html' context = { 'num_posts': num_posts, #'num_authors': num_authors, # Removed b/c it doesn't work 'post_list' : post_list, } def get_context_data(self, **kwargs): context = super(PostListView, self).get_context_data(**kwargs) context['num_authors'] = Author.objects.count() # But this works! template#2 - not totally working: {% block content %} <h1>All Posts:</h1> This blog has a total of {{num_posts}} posts by {{ num_authors}} authors. {% endblock %} -
Django __range function with date only returning first date
I want to return all Source objects within a date range, and the current query I have is sources = Source.objects.filter(datetime__range=(date(2013, 5, 15), date(2013, 5, 20))). However, the returned sources list only contains items from 2013-5-15. Any idea why this is happening? Sorry for the following code dump. views.py from django.shortcuts import render, redirect import os import json import pandas as pd import numpy as np import geopandas as gpd from .models import Source from datetime import date from .utils import df_to_geojson # Create your views here. def home(request): sources = Source.objects.filter(datetime__range=(date(2013, 5, 15), date(2013, 5, 20))) print('number of points: {}'.format(len(sources))) print(sources) sources_df = pd.DataFrame(list(sources.values())) source_gdf = gpd.GeoDataFrame(sources_df, geometry=gpd.points_from_xy(sources_df['lon'], sources_df['lat'])) points = df_to_geojson(sources_df, ['temp_BB', 'area'], 'lat', 'lon') print(sources_df.head()) defaultLon = -3.1883 defaultLat = 55.9533 return render(request, 'geoApp/home.html', { 'points': points, 'lon': defaultLon, 'lat': defaultLat, }) models.py from django.contrib.gis.db import models from django.contrib.gis.geos import Point from django.conf import settings import os import csv import pytz from decimal import Decimal # Create your models here. class Source(models.Model): id_key = models.CharField(blank=False, max_length=40, unique=True, null=True) lon = models.DecimalField(max_digits=14, decimal_places=6, default=999999) lat = models.DecimalField(max_digits=14, decimal_places=6, default=999999) temp_BB = models.IntegerField() area = models.DecimalField(max_digits=14, decimal_places=6, default=999999) datetime = models.DateTimeField(null=True) radiant_heat_intensity = models.DecimalField(max_digits=14, decimal_places=6, default=999999) radiant_heat = models.DecimalField(max_digits=14, … -
403 error when query param contains 2 byte character?
I am testing an API constucted via django views.py/urls.py format: where HttpResponse in views.py just returns filter_param, which is captured by some regex pattern defined in urls.py. I input some UTF-8 encoded char to test what is being captured by API, and receive an error in cases where the char requires more than one byte to encode. ex v1/.../filter/'%C2%A9'/ Returns: 403 Forbidden, expected copyright char But v1/.../filter/'%7E%7E'/ Returns: ~~ Therefore I know that this is not an issue of improperly formed regex. I am on python 2.x, and I read that python v2 only understands UTF-16. I tried this (%00%A9) query instead and received a not found error. Server is running Apache. I am new to django and unfamiliar with URI encoding standards, so any knowledge about the origin of this error would be helpful. -
Fetch API headers are not correctly received after GET request
I am using the Fetch API to download a file and the code to do that looks as follows: const response = fetch(`{% url 'export_xls' %}?${urlParams}`,{ method: 'GET', mode: 'cors', headers: { "X-CSRFToken": '{{ csrf_token }}', } }) .then(res => res.blob()) .then(blob => { let file = window.URL.createObjectURL(blob); window.location.assign(file); }) This does result in a downloaded file, however, the name of the file is randomized, instead of using the filename given in the Content-Disposition header. The headers, which I could see in the chrome dev tools are only the Content-Length and Content-Type, however, when I console log the headers of the response, the Content-Disposition header is there. The django view, which is being called with the fetch API sets the header, so I do not understand why the filename is not correct: response = FileResponse(buffer, as_attachment=True, filename="foo.xlsx") response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' response['Content-Disposition'] = 'attachment; filename="foo.xlsx' response['Access-Control-Expose-Headers'] = 'Content-Disposition' # I read it could be a CORS problem and this could solve it, however, no luck return response After some googling, I found multiple threads where people recommend using an a tag element and setting the download attribute, however, as the Content-Disposition header is set correctly, I would expect to have the … -
This is my html code can you help me how i convert my code into jquery
This is my html code: In this code i am displaying my blogs without ajax. In ajax, If i display my blogs without refresh page this code will mandatory in ajax calls so please help me how i write this code in jquery {% for blogs in blog %} <div class="card" id="card" style="width: 18rem;"> {% if ".jpg" in blogs.image.url or ".jpeg" in blogs.image.url or ".png" in blogs.image.url %} <img src="{{blogs.image.url}}" class="card-img-top" height="280" width="280" alt="..."> {% endif %} {% if '.mp3' in blogs.image.url %} <audio controls width="320" height="240"> <source src="{{blogs.image.url}}" type="audio/ogg"> </audio> {% endif %} {% if '.mp4' in blogs.image.url or '.mkv' in blogs.image.url or '.HDV*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} {% if '.3gp' in blogs.image.url or '.AVI*' in blogs.image.url %} <video width='400' controls> <source src="{{blogs.image.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} <div class="card-body"> <h5 class="card-title">{{blogs.title}} Written by {{blogs.author}} </h5> <h5 class="card-title">{{blogs.date}} | {{ blogs.time|time:"H:i" }}</h5> <p class="card-text">{{blogs.description}}</p> <div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups"> <div class="btn-group me-2" role="group" aria-label="First group"> <button type="button" data-sid="{{blogs.id}}" class="btn btn-success">Update</button> </div> <div class="btn-group me-2" role="group" aria-label="Second group"> <input type="button" data-sid="{{blogs.id}}" class="btn btn-danger" … -
Python recursion function to change the elements value
Example data = OrderedDict([('VaryasyonID', '22369'), ('StokKodu', '01277NUC'), ('Barkod', 'MG100009441'), ('StokAdedi', '1'), ('AlisFiyati', '272,00'), ('SatisFiyati', '272,00'), ('IndirimliFiyat', '126,00'), ('KDVDahil', 'true'), ('KdvOrani', '8'), ('ParaBirimi', 'TL'), ('ParaBirimiKodu', 'TRY'), ('Desi', '1'), ('EkSecenekOzellik', OrderedDict([('Ozellik', [OrderedDict([('@Tanim', 'Renk'), ('@Deger', 'Ten'), ('#text', 'Ten')]), OrderedDict([('@Tanim', 'Numara'), ('@Deger', '41'), ('#text', '41')])])]))]) It is an XML value if '#text' is inside the dict, it means the other tuples are attributes of the element. I have to insert data to db in this format. [{'@_value': 'Haki', '@_attributes': {'@Tanim': 'Renk', '@Deger': 'Haki'}}] I basically get the #text put in '@_value' key and other tuples inside the '@_attributes' dict. If dict doesn't contain '#text' then I save it as it is. Now if I do it with this function it works. def get_attrs_to_element(value): ## value type should be dict text_value = '' res = [] #check for attributes for key, val in value.items(): if '#text' in key: text_value = value['#text'] del value['#text'] attr_obj = { "@_value": text_value, "@_attributes": dict(value) } res.append(attr_obj) return res return value And I call this function where I am iterating over the whole XML as they are key value tuples. if isinstance(value, dict): whole_dict[key] = get_attrs_to_element(value) Now this works. But I also need this function to work when there is … -
How do i display the objects related to a foreign key in django
my models: class Company(models.Model): name = models.CharField(max_length=250) def __str__(self): return str(self.name) class Products(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="display") engine = models.CharField(max_length=250, blank=True) cyl = models.CharField(max_length=250, blank=True) bore = models.CharField(max_length=250, blank=True) def __str__(self): return str(self.engine) + " (ref:" + str(self.ref) + ")" my views.py: def Companies(request): context = { 'categories': Company.objects.all() } return render(request, 'product_list.html', context) HTML : {% for category in categories %} <h2>{{ category.name }}</h2> {% for item in category.item_set.all %} {{ item_engine }} {% endfor %} {% endfor %} how do i display every objects of Products(engine,cyl,bore) following its name -
Django dynamic form with many to many field
I'm looking for advice and maybe a little help with my problem. I'm trying to save m2m field but in a "user-friendly" way, it's mean instead of using multiple select fields I want to use something different. I have simple classes # here I store all subnet mask for IPv4 addresses class SubnetMask(models.Model): mask = models.CharField(max_length=15) mask_length = models.CharField(max_length=3) class IPv4Address(models.Model): ip = models.CharField(max_length=15) subnet_mask = models.ForeignKey(SubnetMask, on_delete=models.SET('')) class Computer(models.Model): OS_type = models.ForeignKey(OS, on_delete=models.SET('')) computer_name = models.CharField(max_length=100) ip_address = models.ManyToManyField(IPv4Address) description = models.CharField(max_length=1000, blank=True) Now I'm assuming that one PC can have more than one IP. When in DB have will be many IPs, listing and adding the IP address will be frustrating, so I thought I can use multiple-select field with a searching field but I can not find any good solution to use in adding form (I tried to use searchableselect but it only works in admin site). I tried also to prepare my own form using JS, now, I got something like this https://imgur.com/a/zyhZ5kE, but the first element has two fields one is a text field where the user enters the IP, second, the user can select subnet mask (this is code in HTML). The second element … -
Django's Syntax is not translated in the CSS Files in the Statics Folder
In my django project everything is working fine ,my css file is loaded just fine, but in my css file i assigned a background image body:before{background-image: url({% static 'images/bg/bg3.jpg' %}); but it won't load as django's {% static '' %} thing is not translated by django into that image's url, and it also gives me a warning, so what should i do to make django translate that css file or what other ways should make that line work. the css file is succesfully recived by the client browser but that line is still as it is and not translated by dbjango into the image's url which creates that error. Note: I have tried to type that line in the <head> tag in the html file and it worked but it gives me error in the code editor, there must be a better way to do that! -
How to fetch data with no record of the foreign key after a specific date?
This model is completely unrealistic. Please don't ask me this question "why you did this". I just want to present to you the purpose that I want to learn. Think of a student and that student is saving the books he reads in the system. After a long time, the data accumulated, we had to make a query. Sturent.objects.filter(book__isnull=True) In this way, I can fetch students who have no book record. But I want to attract students who are not registered after a current date. In the example above you see student 1 and student 2. Both have book records. Imagine hundreds of students this way. I want to get a list as a queryset of students who are not registered after a current date. Thanks in advance if anyone knows how to do this. -
On creating and activating the virtual environment using pipenv shell
In the book the following picture was said to appear when you code: However when ran pipenv shell, I'm now getting the name of virtual env in the brackets: PS C:\Users\name\Desktop\env> pipenv shell Launching subshell in virtual environment... Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\Users\name\Desktop\env> What is the reason for this? -
Django - AWS S3 is serving empty static files
I created a S3 bucket and set up the Django static storage with Boto3. The settings are the following DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'imoveis-django' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.sa-east-1.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' I ran collectstatic and the static files were uploaded to the bucket. However, when they are served, they are empty, as you can see in the picture below. I checked in the bucket and the files are not empty there. -
You are authenticated as allaye, but are not authorized to access this page. Would you like to login to a different account?
so i am trying to update my user profile, the login and registration works well, but when i try to update the user profile it does not work and i dont receive any error. after updating when i try to access the django admin page i get the about error message. let say i login into the admin page as boss which is a super user, and into my app as gate, after updating gate details when i try to access the admin page with had already been loged in by boss, i get the about error message. below are my code. /views.py def signin(request): form = UserLogin(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user: login(request, user) return redirect('index') else: return redirect('signin') return render(request, 'login.html', {'form': form}) @login_required() def profile(request): print(request.user) if request.method == 'POST': # current_user = UserProfile.objects.get(username=request.user) form = UserDetailsUpdate(request.POST, instance=request.user) if form.is_valid(): form.save(commit=True) return redirect('profile') form = UserDetailsUpdate(instance=request.user) return render(request, 'profile.html', {'form': form}) /models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) sex = models.CharField(max_length=20, blank=True) website = models.URLField(blank=True) image = models.ImageField(blank=True) def __str__(self): return self.user.username /forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) sex = forms.CharField() class Meta: model = User fields = … -
I want to keep the changed text color even when the link is clicked
I am a student learning Django. I changed the text color when I clicked the Nav-link, and it disappears the moment I go to the link by clicking the link button. It remains the moment you put the mouse on it, but the text color disappears the moment you release the mouse. How do I get a link to remain after visiting? Code : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css2?family=Comfortaa:wght@300&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <style> .menu-wrap li{ display: inline-block; padding: 10px; } .menu-wrap a[selected]{ color:#637B46; font-weight: 600; } </style> </head> <body> {% load static %} <link rel="stylesheet" href="{% static 'main.css' %}"> <div class="text-center navbar navbar-expand-md navbar-light"> <a class="navbar-brand" href="/" style="margin-top:30px;">ZERONINE</a> <button class="navbar-toggler" style="margin-top:30px;" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> <nav class="navbar navbar-expand-lg"> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="menu-wrap" style="margin: auto;"> <li class="nav-link"><a class="nav-link" href="/" class="nav-link">전체상품</a></li> {% for c in categories %} <li class="nav-link"><a href="{{c.get_absolute_url}}" class="nav-link {% if current_category.slug == c.slug %}active{% endif %}" >{{c.name}}</a></li> {% endfor %} <li class="nav-link"><a href="{% url 'zeronine:post' %}" class="nav-link">자유게시판</a></li> {% csrf_token %} {% if user.is_authenticated %} <li class="nav-link"><a href="{% url 'zeronine:logout' %}" class="nav-link"><b>{{ … -
django-admin-autcomplete-filter not working
Resource https://pypi.org/project/django-admin-autocomplete-filter/ I have used the pip command to install this, but when I add to my installed_apps list, I get an error and cannot run my dev environment. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', 'admin-auto-filters', ] Am I doing something wrong? -
request.user in django is None for anonymous user
using python 3.6.8 django 2.2 I have started seeing a weird thing in server logs where anonymous users in django are not being added to the request, I am using the django.contrib.auth.context_processors.auth as my first context-processor. suddenly I am seeing 'NoneType' object has no attribute 'is_anonymous' This comes from a custom context-processor that is added after the auth processor This has gotten me really stumped