Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authentication server for Django projects
I need to write an authentication service (id.domain.com) for several sites (site1.domain.com, site2.domain.com etc., one of the sites is already running in production). I read about OpenID, SSO, jwt, but I still do not have a complete picture. Therefore, I seek advice. If user has account in id.domain.com, he can login to all sites (site1.domain.com, site2.domain.com etc.), once agreeing to share user data for each site. I would like to use ready-made libraries (maybe django-oidc-provider) to speed up the process. In which direction should I move and what should I learn? Thank you for your time and help. -
TemplateDoesNotExist | django 3.0.1 ,python 3.6
I am new to Django , I'm working on system Windows 10 , Django version 3.0.1 ,python 3.6 I tried to use all the relevant solutions provided for this problem , but unfortunately none of those resolve my problem . I made a folder named templates in myproject and "index.html" inside it, I write some lines of code in my views.py file as from django.shortcuts import render from django.http import HttpResponse from django.template import loader def index(request): template = loader.get_template('index.html') return HttpResponse(template.render()) here is my settings.py BASE_DIR = (os.path.dirname(os.path.abspath(__file__)) 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', ], }, }, ] **Traceback error ** Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: E:\djangoLearning\myproject\myapp\templates\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: E:\djangoLearning\djangoenv\lib\site-packages\django\contrib\admin\templates\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: E:\djangoLearning\djangoenv\lib\site-packages\django\contrib\auth\templates\index.html (Source does not exist) * django.template.loaders.app_directories.Loader: E:\djangoLearning\myproject\myapp\templates\index.html (Source does not exist) Traceback (most recent call last): File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\djangoLearning\djangoenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\djangoLearning\myproject\myapp\views.py", line 9, in index template = … -
How to add a keyword argument to a class based view success_url
I have a class based UpdateView which returns the user to the url_name for company_list after the form is valid: class CompanyUpdate(UpdateView): model = Company template_name = 'companies/company_update.html' fields = '__all__' success_url = str(reverse_lazy('company_list')) How can I change this to return the user to a detail view that requires a keyword argument? E.g. success_url = reverse_lazy('company_detail', kwargs={'pk': self.object.pk}) ... throws an error because self is not defined. I know I can probably do this via sub-classing def get_success_url but is there a better way to keep it DRY? -
why ajax reload page
I'm creating an ajax call in my django app. The main problem I run this code ajax works and data in db change but then the page reloads. I don't know why it works in this way. Here is my code: JS: $(function() { $( "#button" ).submit(function() { $( this ).addClass( "onclic"); $.ajax({ dataType: 'json', async: false, data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), action: 'post' }, done: function (e, data) { if (data.result.is_valid) { setTimeout(function() { $( "#button" ).removeClass( "onclic" ); $( '#button ').addClass( "validate"); }, 3500 ); }}});});}); views.py: def projects(request, pk): projects_data = Project.objects.get(id=pk) courses = Course.objects.filter(project=pk) context = { 'project': projects_data, 'courses': courses, } if request.POST.get('action') == 'post': project = Project.objects.get(pk=pk) obj = Profile.objects.get(user=request.user) obj.projects.add(project.id) obj.save() data = {'is_valid': True, 'project': str(project)} return JsonResponse(data) return render(request, 'projects/project.html', context) -
Django 3 project structure
Django3 project structure Guys I have a strange problem, I used this structure in the version of django 2.0 and it worked, I did not understand the reason for the error in django 3. Following error image and project structure My AUTH_USER_MODEL : AUTH_USER_MODEL = 'accounts.User' Already tried to put ‘apps.accounts.User’ and it doesn't work, the following error appears: ValueError: Invalid model reference 'apps.accounts.User'. String model references must be of the form 'app_label.ModelName' This is the content of apps/accounts/apps.py: from django.apps import AppConfig class AccountsConfig(AppConfig): name = 'accounts' -
How to call model verbose_name in class based view
I have a UpdateView class based view: class CompanyUpdate(UpdateView): model = Company template_name = 'companies/company_update.html' fields = '__all__' def form_valid(self, form): self.object = form.save() title = str(self.object) messages.info(self.request, 'Company ' + title + ' updated') return super().form_valid(form) My model has a Meta verbose_name defined: class Company(models.Model): company_name = models.CharField(max_length=255) class Meta: verbose_name = 'Company' verbose_name_plural = 'Companies' Is there a way to display the model's verbose_name in the form_valid function so I am not writing messages.info(self.request, 'Company ' + title + ' updated' ) but instead something like: messages.info(self.request, self.request.META['verbose_name'] + title + ' updated' ) ? -
How to use Django star-ratings?
I'm building a rating system for my website that is currently working with numbers. What I want is really simple : 1) In a template, displaying a mean rating as stars instead of as a number (I need to have partials stars, for example 4.3/5 would be rendered as 4 stars and a 1/3 star). 2) In a form, being able to click on stars to record a rating instead of entering a number. For that purpose, I have installed django star-ratings. The problem is that there are no documentation available about how to actually use these app. I only want to be able to modify my templates to display numbers as stars and to record stars as numbers but I can't figure out how to do that. That seems so simple but I found nothing on the official documentation nor on internet. Can someone familiar with this app help me ? Thanks in advance ! -
How StreamingHttpResponse Works in django
A full explanation of how StreamingHttpResponse works in Django and what happens after a StreamingHttpResponse request is answered I have used the code in this link but did not understand exactly how it works response a big file with to be resume I read the following link again I didn't notice it How Does Django’s StreamingHttpResponse Work, Exactly? -
File not uploading django drf
i am trying to upload image from react frontend with drf this is error i'm getting: ValueError: Cannot assign "1": "ProjectImage.category" must be a "ProjectCategory" instance. models.py: class ProjectCategory(MPTTModel): name = models.CharField(max_length = 100) slug = models.SlugField() parent = TreeForeignKey('self',blank=True, null=True, related_name='children', on_delete=models.CASCADE, db_index = True) class MPTTMeta: verbose_name_plural = "Projectcategories" order_insertion_by = ['name'] def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) class ProjectImage(models.Model): title = models.CharField(max_length = 100) image = models.ImageField(upload_to = 'media' , default = 'home/tboss/Desktop/image/logo.png') category = models.ForeignKey('ProjectCategory', null=True, blank=True, on_delete=models.CASCADE,) description = models.TextField(max_length=1000) def __str__(self): return self.title views.py: class ProjectImageUploadView(APIView): authentication_classes = [] permission_classes = [] def post(self, request,category): file = request.data['file'] data={ 'image':file, 'category':category } ProjectImage.objects.create(**data) return JsonResponse(json.dumps({'message': "Uploaded"}), status=200, safe=False) def __str__(self): return self.title urls.py: path('projectuploadimage/<int:category>/', views.ProjectImageUploadView.as_view()), i want to upload multiple image once in category................................................ -
get json response based on django orm
I want details in a nested json response on the above tables where one challan can have multiple items and one item can have multiple item quantity. enter image description here picture -
Populate OneToOneField after submitting form Django
I wrote the following code which creates a new user and tries to create a profile for that user: class RegisterForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') @login_required(login_url="/login") def index(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): profile = Profile().save() user = form user.profile = profile user.save() return redirect('users') else: print(form.errors) else: form = RegisterForm() user_model = get_user_model() users = user_model.objects.all() paginator = Paginator(users, 15) page = request.GET.get('page') users = paginator.get_page(page) return render(request, 'users/index.html', {'users': users, 'form': form}) class Profile(models.Model): has_premium_until = models.DateTimeField(null=True, blank=True) has_premium = models.BooleanField(default=False) has_telegram_premium_until = models.DateTimeField(null=True, blank=True) has_telegram_premium = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class CustomUser(AbstractUser): email = models.EmailField(max_length=255, unique=True) profile = models.OneToOneField(Profile, on_delete=models.CASCADE, null=True) When I'm submitting the form the user as well as the profile is created but the profile is not stored in the user (the profile_id stays null). Anyone who can help me out? -
Bookmarks in django object got simplelazyobject when adding user instance Why
Have wasted alot of time researching and trying to figure out how to implement bookmarks in django. I tried CBV but i gave up. I tried fbv but I keep on getting this errors TypeError at ... 'Bookmark' instance expected, got > Here is my View @login_required def company_bookmark(request, slug): user = request.user model = get_object_or_404(Company, slug=slug) if user.is_authenticated: if model.bookmark.filter(id=user.id).exists(): model.bookmark.remove(request.user) else: model.bookmark.add(request.user) return HttpResponseRedirect(model.get_absolute_url()) else: messages.warning(request, 'you must be authenticated first') I wrap it in condition statement and still got same error, I added the condition in html to no avail {% if request.user.is_authenticated %} <a href="{% url 'company:bookmark' slug=company.slug %}" value="{{ company.slug }}" type="submit" class="btn_1 full-width outline wishlist"> <i class="icon_heart"></i> Add to Favourite </a> {% endif %} I even tried to add id to view like this model.bookmark.remove(request.user.id) it bring another error: AttributeError at 'int' object has no attribute '_state' If I can get help I would be much grateful. Thanks in advance. -
Template does not exist error when template exists
Getting the error message template does not exist even though the template is in the referenced folder Here is part of the structure of my project classroom -->templates ---->classroom ------>teachers app-instructor-profile.html app-instructor-dashboard.html This is what I have on urls.py urlpatterns = [ ... path('teachers/', include(([ path('', teachers.QuizListView.as_view(), name='app-instructor-dashboard'), path('logout', teachers.logout_request, name="logout"), path('edit_user', teachers.edit_user, name='edit_user'), ], 'classroom'), namespace='teachers')), home.html (app-instructor-dashboard) <li><a href={% url 'teachers:edit_user' %}>Edit Profile</a></li> teachers.py (views.py) def edit_user(request): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('teachers:app-instructor-dashboard') else: form =UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'teachers:app-instructor-profile', args) However, when I click the link which should redirect me to the edit-profile view I get the error message: TemplateDoesNotExist at /teachers/edit_user teachers:app-instructor-profile -
How to return django queryset from model method to template?
i would like to get all children recursively from concrete object, until now i have this.. models.py: class CustomModel(models.Model): ... parent = models.ForeignKey('self', related_name='child', blank=True, null=True, on_delete=models.SET_NULL) def get_child(self, childs=[]): child = Budget.objects.filter(parent_id=self.id).first() if childs is None: childs = [] if child is not None: childs.append(child.id) child.get_child(childs) else: result = CustomModel.objects.filter(id__in=childs) print(result) return result file.html: {{ element.childs }} or {% for child in element.get_child %} On print debug point i can see all children objects but in template appears as none Anybody could help me please ? Happy new year everyone. -
How to build a ready-made Django project with a standard Sqlite database on Docker?
Created a small server on django and sqlite. In Dockerfile, I specified only the server folder. Dockerfile: FROM python:latest ENV PYTHONUNBUFFERED 1 ADD requirements.txt /cars/ WORKDIR /cars/ RUN pip install -r requirements.txt Requirements.txt: Django>=2.0,<3.0 djangorestframework docker-compose.yml: version: '3' services: db: image: spartakode/sqlite3:latest volumes: - .db/database.db:/db/db.db web: build: cars/ command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/cars ports: - "8000:8000" depends_on: - db However, I did not add anything to the db folder. I understand that something needs to be added there, but I don’t understand what exactly because db.slite3 is located in the cars folder. If I take my django project separately, then everything works fine. I did migration and so on. When I transfer the project folder and run it on another computer python manage.py runserver on , everything works flawlessly. Structure: When docker-compose up starts, it displays the following: Questions: 1) What should I do in my case for the Django project to work with the standard database (Sqlite) on Docker? 2) How to assemble a ready Django project on Docker? Maybe it can be done somehow different? -
Updated model instance field doesn't reflect everytime in django admin
I have this issue where by when I update a model instance's field the updated value doesn't always reflect in django admin although sometimes it does. To try and debug it further I setup a post save signal on the model to see if the value is actually modified and I do get the updated value in my post save signal, however it doesn't always update the value in the django admin. And further more when I make another request it picks up the value in the django admin which is sometimes the not updated value or updated value depending on whether the django admin was able to pick up the value the previous time. An example of how I'm updating. It might help to know that the field causing me problems is a PositiveIntegerField Say I have a model instance called post and I want to update the version of the post. post.version = int(new_version) post.save() Any help will be much appreciated thank you. -
How to caching log files in Django celery task for processing
I am processing some log files csv files that are downloaded every time there is a new one. But the problem is when a new log file is added to log list the process starts from scratch processing. I want to maintain the processing position. How can I do that? @only_one(ikey='process-pmta-logs') @shared_task(soft_time_limit=60*60, time_limit=60*60+30) def process_pmta_logs(): """ Get 5 oldest log files from the storage and process them. Those files are located in docker volume - so should be available for all workers and web part as well. """ log_files = list(filter(os.path.isfile, glob.glob(f'{settings.PMTA_LOGS_FILE_PATH}/*.csv'))) log_files.sort(key=lambda f: os.path.getmtime(f)) emails = set() for log_file_path in log_files[-5:]: with open(log_file_path, 'rt') as log_file: log_file_reader = reader(log_file) headers = next(log_file_reader, None) ... -
"UNIQUE constraint failed" when migrate
Error message: Operations to perform: Apply all migrations: admin, auth, contenttypes, contest1, dashboard, sessions, tiaozhancup Running migrations: Applying dashboard.0012_auto_20200104_1633...Traceback (most recent call last): File "C:\Users\acer\Desktop\来了喔\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\acer\Desktop\来了喔\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: UNIQUE constraint failed: new__dashboard_teacher.TID models.py class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.CharField(max_length=50, blank=True, null=True) #这个是为了能在admin能用,就当他是真实姓名吧,管它呢 email = models.EmailField(max_length=254, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) SID = models.CharField(max_length=50, blank=True, null=True, unique=True,) gender = models.CharField(max_length=50, blank=True, null=True) school = models.CharField(max_length=50, blank=True, null=True) contest = models.CharField(max_length=500, blank=True, null=True, default='[]') class Teacher(models.Model): really_a_teacher = models.BooleanField('真的是老师吗 ?', default=False) user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) username = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(max_length=254, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) TID = models.CharField(max_length=50, blank=True, null=True, unique=True,) gender = models.CharField(max_length=50, blank=True, null=True) department = models.CharField(max_length=50, blank=True, null=True) authorization_for_contest = models.CharField(max_length=500, blank=True, null=True, default='[]') I add 'unique=True' to SID and TID respectly, somehow only TID part get error when I migrate. -
AttributeError: module 'users.models' has no attribute 'User'
i have done this : users/models.py from django.contrib.auth.models import AbstractUser from django.db import models from friends import models as friends_models class User(AbstractUser): """User Model Definition""" LANGUAGE_KOREAN = 'kr' LANGUAGE_ENGLISH = 'en' LANGUAGE_CHOICES = ((LANGUAGE_KOREAN, "한국어"), (LANGUAGE_ENGLISH, "영어")) CURRENCY_USA = "en" CURRENCY_KOREA = "kr" CURRENCY_EUROPE = "eu" CURRENCY_CHOICES = ((CURRENCY_KOREA, "KRW"), (CURRENCY_USA, "USD"), (CURRENCY_EUROPE, "EUR")) friends = models.ManyToManyField(friends_models.Friends, blank=True) # optional information language = models.CharField( choices=LANGUAGE_CHOICES, max_length=2, blank=True, default=LANGUAGE_KOREAN) currency = models.CharField( choices=CURRENCY_CHOICES, max_length=2, blank=True, default=CURRENCY_KOREA) birthdate = models.DateField(blank=True, null=True) friends/models.py from django.db import models from cores import models as core_models from users import models as user_models class RequestFriends(core_models.TimeStampedModel): id = models.AutoField(primary_key=True, editable=False) user_from = models.ForeignKey(user_models.User, on_delete=models.CASCADE) user_to = models.ForeignKey(user_models.User, on_delete=models.CASCADE) class Friends(core_models.TimeStampedModel): id = models.AutoField(primary_key=True, editable=False) friends = models.ForeignKey( user_models.User, on_delete=models.CASCADE) when i try to makemigrations or migrate, error appear like File "/Users/kimdoehoon/Project/web_dev/divideN/friends/models.py", line 8, in RequestFriends user_from = models.ForeignKey(user_models.User, on_delete=models.CASCADE) AttributeError: module 'users.models' has no attribute 'User' I already have User model, but why users.models has no attribute User? What it means? -
AttributeError: module 'django.db.models' has no attribute 'RichTextField'
I'm trying to add a rich text field in my Django application and for that, I am using "Ckeditor". But when I am trying to add the CKEditor rich text field in my models.py it is showing an error. AttributeError: module 'django.db.models' has no attribute 'RichTextField' models.py from django.db import models from ckeditor.fields import RichTextField class Post(models.Model): # id = models.AutoField(blank = False ,null = False) name = models.CharField(max_length=100, default=None ,blank = False ,null = False) category = models.CharField(max_length=40, default=None ,blank = False ,null = False) author = models.CharField(max_length=40, default=None ,blank = False ,null = False) content = models.RichTextField(blank = True ,null = True) date = models.DateField(null=True, blank=True) def __str__(self): return self.name -
Reverse not found Django
I would like to redirect users to another page after they click a link. I know that I need to register the redirect on urls.py and have the view on views.py I have done all of this to my understanding, but still getting this error specifically for one redirect. Here is my html <li><a href={% url 'edit_user' %}>Edit Profile</a></li> urls.py urlpatterns = [ path('teachers/', include(([ path('', teachers.QuizListView.as_view(), name='app-instructor-dashboard'), path('logout', teachers.logout_request, name="logout"), path('edit_user', teachers.edit_user, name='edit_user'), ], 'classroom'), namespace='teachers')), and views.py(teachers.py) def edit_user(request,pk): if request.method == 'POST': form = UserChangeForm(request.POST, instance=request.user) if form.is_valid(): form.save() return redirect('teachers:app-instructor-dashboard') else: form =UserChangeForm(instance=request.user) args = {'form':form} return render(request, 'teachers:app-instructor-profile', args) This is the error message I am getting NoReverseMatch at /teachers/ Reverse for 'edit_user' not found. 'edit_user' is not a valid view function or pattern name. -
Add jQuery to Django Admin Page for Dropdown Selection to Enable/ disable it
I have a model in Django which contains dropdowns and they are dependent. If I select "Yes" in a, the dropdowns associated with it i.e. b and c should be enabled and if "No", they should be disabled. Note that I want this to work on admin page. models.py class foo(models.Model): a = models.CharField(max_length=3,choices=(('No','No'),('Yes','Yes')) b = models.ForeignKey(SomeModel_1,,on_delete=models.CASCADE,null=True,blank=True) c = models.ForeignKey(SomeModel_2,,on_delete=models.CASCADE,null=True,blank=True) jQuery $(function() { $("#id_a").change(function() { if ($(this).val() == "Yes") { $("#id_b").prop("disabled", false); $("#id_c").prop("disabled", false); } else { $("#id_b").prop("disabled", true); $("#id_c").prop("disabled", true); } }); })(django.jQuery); And I have also added Media class admin.py class fooAdmin(admin.ModelAdmin): class Media: js = ('https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js', 'js/myScript.js',) admin.site.register(foo,fooAdmin) Now, the dropdown b and c are available regardless of choice selected in a. How can I make this work? If I need forms.py then please explain how can I do that. Thank you. -
how to change models field value from views in django
I want to set the value of is_delete field True when i click delete button from list page. This is my views.py file def delete_faculty(request, faculty_id): faculty = Faculty.objects.get(id=faculty_id) faculty.is_delete = True return redirect('faculty-list') This is models.py class Faculty(models.Model): name = models.CharField(max_length=255, unique=True) established = models.DateField() about = models.TextField() status_choice = ( ('active', 'Active'), ('disabled', 'Disabled'), ('paused', 'Paused') ) status = models.CharField(choices=status_choice, max_length=15) is_delete = models.BooleanField(default=False) def __str__(self): return self.name This code can not set the value of True in is_delete field . How can i solve this? -
Search result from two different model related by foreign-key
I've two models. One is class Pin(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title another is class Content(models.Model): pin = models.ForeignKey(Pin, on_delete = models.CASCADE) content_type = models.CharField(max_length=2) content = models.TextField() I want show the list of Pin's if the Pin's title or Content's content contains the search query. For a single Pin there can be multiple Content, and I want to show the list of Pins if the title of Pin or the content of a Content match. I can generate result if the Pin's title contains the query. Anyone can help me? -
django.contrib.auth.decorators login_required with django-rest-framework
I am implementing login functions in my web app, but this error occurred. File ".../venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 20, in _wrapped_view if test_func(request.user): AttributeError: 'QuestionListView' object has no attribute 'user' Below is views.py, where the user is logged in using django.contrib.auth's user login function. class QuestionListView(APIView): @login_required def get(self, request, format=None): return Response({'message': 'try', 'status': 1}) class UserLoginView(APIView): def post(self, request, format=None): data = request.data user = authenticate( username=data['username'], password=data['password']) if user is not None: login(request, user) return Response({'message': 'Login successful', 'status': 1}) else: return Response({'message': 'Wrong password', 'status': 0}) url.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^accounts/login/$', views.UserLoginView.as_view()), url(r'^questions/$', views.QuestionListView.as_view()), ] Since I am using React JS, I redirect the page using window.location.href = '/'; after the login button is clicked. (I am also not sure whether this is an appropriate way to redirect the page) With reference to class has no attributed user, I tried changing @login_required to @method_decorator(login_required). No error occurred, but instead it triggered GET another method "GET /accounts/login/?next=/questions/ HTTP/1.1" 200 17 Can anyone explain how to fix this problem or to properly use @login_required?