Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to save the html text in django database
I want to save the time(html text) to my django admin and this timer work well enter image description here html_file 00 This 00 part i want to save enter image description here views.py part enter image description here forms.py part enter image description here models.py part -
Import problem in pycharm with django tutorial
Yesterday I started learning django with this tutorial: https://www.youtube.com/watch?v=IMG4r03G6g8 But I am getting an Import Error here: file: django_1/src/dj30/urls.py from django.contrib import admin from django.urls import path from posts.views import post_list_view # ERROR LINE urlpatterns = [ path('admin/', admin.site.urls), path('posts/', post_list_view) ] This is my directory tree: I assume that the Import Error occurs because I am trying to import posts.views.post_list_view from posts/views.py into dj30/urls.py which is in another directory. How does the guy in the tutorial do it? I am positive that I followed the tutorial correctly (I did it twice). Maybe there is a problem with venv because I am using PyCharm (com) and he is not. Here are relevant files that were edited during the tutorial: django/src/dj30/settings.py: """ Django settings for dj30 project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'z=5t$_w+c@k3u+e1c-1tn6xoolrm#*ki*#@kh1u_*=rmwxtk!s' # SECURITY WARNING: don't … -
How do I set my foreign key to the current user in my views
I am developing an app that needs users to login and create posts.The post model has an image and a caption(the user inputs) and a profile foreign key that should to automatically pick the logged in users profile. The app however isnt autopicking the profile.Can someone spot what am doing wrong? I feel like the particular issue is in this line of code in my views form.instance.profile = self.request.Image.profile Someone kindly help models from django.db import models from django.contrib.auth.models import User import PIL.Image from django.urls import reverse # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='images/') caption = models.TextField() profile = models.ForeignKey('Profile', default='1', on_delete=models.CASCADE) likes = models.ManyToManyField(User, blank=True) created_on = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('vinsta-home') class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) photo = models.ImageField(upload_to = 'photos/',default='default.jpg') bio = models.TextField(max_length=500, blank=True, default=f'I love vinstagram!') def __str__(self): return f'{self.user.username}' views from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import (ListView,CreateView,) from .models import Image def home(request): context = { 'posts': Image.objects.all() } return render(request, 'vinsta/home.html', context) class ImageListView(ListView): model = Image template_name = 'vinsta/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-created_on'] class ImageCreateView(LoginRequiredMixin, CreateView): model = Image fields = ['image', 'caption'] def form_valid(self, form): form.instance.profile = self.request.Image.profile … -
create multiple collapse when i use for loop in Django template
How to create multiple collapse when i use for loop in Django template I have created a django template which show lists of lessons and i want to create collapse for each lesson such that on click of it , it shows the video from my url . how i can do this html code : <div id="accordion"> {% for lesson in course_posts.lesson_set.all %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0 text-center"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{lesson.name}} </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> <iframe width="100%" height="400px" src="{{lesson.youtube_url}}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </div> {% endfor %} </div> -
How to remove Byte Order Mark from utf-16 to utf-8 python3?
I going to cast UTF-16 to UTF-8 in django with python3, this is my request to django web app in the "settings.py" with DEFAULT_CHARSET = "utf-16": <QueryDict: {'mykey': ['\ufeff33992FFBDDB5209E523A77DF980FA578']}> We have a Byte Order Mark \ufeff, I was unable to cast to UTF-8, How to remove it? -
Celery task testcase refuses to complete
I have a celery task that iterates through a django queryset. For each iteration, my code interacts with an external api. When i run my testcase to test the task, for some unknown reasons test doesn't complete # celery task @shared_task def iterate_and_compute(): qs = Product.objects.all() for item in qs: iteract_with_external_api() # my testcase from django.test import TestCase from myapp.models import Product from myapp.tasks import iterate_and_compute class TaskTestCase(TestCase): def setUp(self): # do some setup, like creating some products def test_iterate_and_compute_is_successful(): task = iterate_and_compute.delay() res = task.get() self.assertEqual(task.status, 'SUCCESS') celery worker is started like so: celery -A myproject worker -l INFO -P solo my test is run like so: python manage.py test myapp.tests.test_tasks.TaskTestCase.test_iterate_and_compute_is_successful From celery worker i get this response, that task succeeded Task myapp.tasks.iterate_and_compute[71ab0ede-3a58-476b-a5cd-27e56552e9f1] succeeded in 0.07800000000861473s: None This is the response i get from my test console python manage.py test myapp.tests.test_tasks.TaskTestCase.test_iterate_and_compute_is_successful Creating test database for alias 'default'... System check identified no issues (0 silenced). That response remains like so for minutes. Do's & Dont's i'm not chaining / grouping task and no other task is called within iterate_and_compute task within my iterate_and_compute task i use time.sleep(25) which should only last for 25 seconds What i've tried I've tried starting … -
how to make api for comments on a blog detail view. I dont need replies to comments ( ie no children comment)
I want to show comments of a blog post detail. I am new to Django. I have to make an api for this. Here is what I have. class BlogPost(models.Model): CATEGORY_CHOICES = ( ('travel_news', 'Travel News',), ('travel_tips', 'Travel Tips',), ('things_to_do', 'Things to Do',), ('places_to_go', 'Places to Go'), ) image = models.ImageField(blank=True, null=True) categories = models.CharField(max_length=64, choices=CATEGORY_CHOICES, default='travel_news') description = models.CharField(max_length=255) content = RichTextUploadingField() # todo support for tags tags = models.CharField(max_length=255, default='#travel') #todo date_created = models.DateField() @property def html_stripped(self): from django.utils.html import strip_tags return strip_tags(self.content) class Comment(models.Model): blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, default=1) name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('created_at',) This is my serializers class CommentSerializer(serializers.ModelSerializer): blog = serializers.StringRelatedField() class Meta: model = Comment fields = '__all__' class BlogPostSerializer(serializers.ModelSerializer): comments = CommentSerializer(source='comments.content') class Meta: model = BlogPost fields = ['image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' Here is my view. class BlogPostDetailsListAPIView(ListAPIView): serializer_class = BlogPostSerializer def get_queryset(self): return BlogPost.objects.filter(pk=self.kwargs['pk']) Here my view is returning only the BLogpost objects, but not comments.How to return the comments along with the post detail view as well? Can we do without the contenttype? -
Owl Carousel not showing images in Django server
Well, as explained in the title, when I designed the site in plain css and html, it shows the images perfectly, here's the relevant code after calling the necessary files, and result IN PURE FRONTEND: <!-- ================= main slide ================= --> <div class="owl-init slider-main owl-carousel" data-items="1" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide"> <img src="img/banners/CDMX.jpg"> </div> <div class="item-slide"> <img src="img/banners/GDL.jpg"> </div> <div class="item-slide"> <img src="img/banners/MTY.png"> </div> </div> <!-- ============== main slidesow .end // ============= --> </div> <!-- col.// --> and the result: yet, here's the code in index.html after extending the base.html file and making sure all css an js files are correctly called: <!-- ================= ciudades slide ================= --> <div class="owl-init slider-main owl-carousel" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide owl-item"> <img src="{% static 'core/img/banners/MTY.png' %}"> </div> <div class="item-slide owl-item"> <img src="{% static 'core/img/banners/GDL.jpg' %} "> </div> <div class="item-slide owl-item "> <img src="{% static 'core/img/banners/CDMX.jpg' %}"> </div> </div> <!-- ============== main slidesow .end // ============= --> </div> <!-- col.// --> and this result: it shows the following result when analyzing the html result in the browser: <!-- ================= ciudades slide ================= --> <div class="owl-init slider-main owl-carousel" data-margin="1" data-nav="true" data-dots="false"> <div class="item-slide owl-item"> <img src="/static/core/img/banners/MTY.png"> </div> <div class="item-slide owl-item"> <img src="/static/core/img/banners/GDL.jpg "> </div> <div … -
How to solve OperationalError at/category/1
[enter image description here I checked whether the code was fine or not, and the error is happened in Django ]2 Tell me how to solve this issue. And I don't make forum_category in Django, but is it ok? -
Unable to save form using django.views.generic.View
I was able to save before without an issue using django.views.generic.CreateView. However, I can't save the same form using View. Below are my codes: models.py class Project(models.Model): name = models.CharField(max_length=200, verbose_name='Project Name') user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) client = models.ForeignKey(Client, on_delete=models.SET_NULL, blank=True, null=True) deadline = models.DateTimeField(blank=True, null=True) views.py from django.views.generic import View class ProjectCreateView(LoginRequiredMixin, View): form_class = ProjectCreateForm success_url = reverse_lazy('dashboard') template_name = 'translation/project_form.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): project_form = self.form_class(request.POST, instance=request.user) if project_form.is_valid(): project_form.save() return redirect(self.success_url) else: return render(request, self.template_name) html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mt-5 py-2 w-50 bg-dark text-white"> <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success mt-3">Confirm</button> </form> </div> {% endblock content %} urls.py path('project/new', views.ProjectCreateView.as_view(), name='project-add'), When I submit the form in html, it doesn't render any error message. It simply redirects to the self.success_url and the intended object is not saved. Any help or advice will be much appreciated. Thank you! -
Bootstrap 4 elements don't align when added div
So my goal is to try to make my Registration form look like my login form. All I did was added extra fields and then the form went crazy. Can anyone explain? I searched the internet for help but that didn't work and I was just really trying to make this one work because it looks nice. Yes I am working and learning dJango so I just wanted this to look nice even though it is not even needed. I go the extra mile sometimes but hate when I don't understand. This is my index html and login form <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" /> {% load static %} <link rel="stylesheet" href="{% static 'styles.css' %}" /> <title>Albert's Page</title> </head> <body> <section class="Form my-4 mx-5"> <div class="container"> <div class="row no-gutters"> <div class="col-lg-5"> <img src="../static/img/swordandshield.jpg" alt="" class="img-fluid" /> </div> <div class="col-lg-7 px-5 pt-5"> <h1 class="font-weight-bold py3">Welcome to My place</h1> <h4>Sign into your account</h4> <form action="" method="post"> <div class="form-row"> <div class="col-lg-7"> <h4>User Name</h4> <input type="userName" name="userName" class="form-control my-3 p-4" /> </div> </div> <div class="form-row"> <div class="col-lg-7"> <h4>Password</h4> <input type="password" name="pw" … -
Adding an Export Format for files in Django Admin
Helloo, I have added the ImportExportActionModelAdmin function in my Admin for Project, but I can not find the option to choose the format of the file to download and option to export orders. How do I add that option to download features? Here is the admin.py def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('core:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', ....., order_pdf] -
I am trying to install mysql using pip install mysql-python command and getting error
Running setup.py install for mysql-python ... error ERROR: Command errored out with exit status 1: command: 'c:\users\pkhar\pycharmprojects\socialmedia\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\pkhar\\AppData\\Local\\Temp\\pip-install-uzolldq5\\mysql-python\\setup.py'"'"'; file='"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cod e, file, '"'"'exec'"'"'))' install --record 'C:\Users\pkhar\AppData\Local\Temp\pip-record-ani9ddry\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\pkhar\pycharmprojects\socialmedia\ven v\include\site\python3.7\mysql-python' cwd: C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python Complete output (24 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 copying mysql_exceptions.py -> build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\MySQLdb copying MySQLdb_init.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.7\MySQLdb creating build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.7\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.7\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ---------------------------------------- ERROR: Command errored out with exit status 1: 'c:\users\pkhar\pycharmprojects\socialmedia\venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolld q5\mysql-python\setup.py'"'"'; file='"'"'C:\Users\pkhar\AppData\Local\Temp\pip-install-uzolldq5\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n '"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\pkhar\AppData\Local\Temp\pip-record-ani9ddry\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\users\pkhar\pycharmprojects\socialmedia\venv\include\site\python3.7\mysql-python' Check the logs for full command output. Can someone help me in installing mysql client -
Create object automatically after saving another object
I have a car heading towards a series of possible, predefined locations. class locations(models.Model): name = models.CharField(max_length=30, blank=True) coordinates = models.CharField(max_length=30, blank=True) def __str__(self): return self.name In this example, the objects created are New York, Ohio, and Wyoming. Then I have a type of car with the following attributes: class cars(models.Model): type = models.CharField(max_length=30, blank=True) MaxRange = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) Speed = models.DecimalField(null=True, max_digits=20, decimal_places=3, default=Decimal('0.000')) def __str__(self): return self.type When the car departs, that is tracked by another table with values pertaining to when the car could arrive at locations given by the model, locations. class departure(models.Model): car_name = models.ForeignKey(cars, null=True, on_delete=models.CASCADE) location_name = models.CharField(max_length=30, null=True, blank=True) range_or_not = models.CharField(max_length=30, null=True, blank=True) arrival_time = models.CharField(max_length=30, null=True, blank=True) def save(self, *args, **kwargs): for loc in location.objects.all(): self.location_name = #calculation self.range_or_not = #calculation self.arrival_time = #calculation super(departure, self).save(*args, **kwargs) def __str__(self): return self.location_name When the user selects a group and creates a departure, I want to loop through all the locations and generate calculated values pertaining to each of those locations such as: the possible arrival time of a car for all locations inputed in the locations model. I'm not sure how to automatically create a new departure object for … -
Populating a model field based on another model field from a different model
I'm trying to populate "balance" in Transaction model based on "beginning_balance" in the Accounts model, but I'm getting the following error message: save() missing 2 required positional arguments: 'request' and 'pk' What am I doing wrong. Thank you. models.py from django.db import models class Accounts(models.Model): account_nickname = models.CharField(max_length=15, unique=True) beginning_balance = models.DecimalField(max_digits=12, decimal_places=2) def __str__(self): return self.account_nickname class Transaction(models.Model): transaction_date = models.DateField() account_nickname = models.ForeignKey(Accounts, on_delete=models.CASCADE) amount = models.FloatField() balance = models.FloatField(null=True, blank=True, editable=False) def save(self, request, pk): get_beginning_balance = Accounts.objects.get(id=pk) self.balance = get_beginning_balance super().save(request, pk, *args, **kwargs) def __str__(self): return self.account_nickname -
django User update_fields not showing up in signal
i am using django signal to create a user profile automatically when the user is created , and it is work fine , but i want to check also if the user trying to update his "username or email or ..... etc ." i am trying to check these values in signal , but always the 'update_fields' value is None ! 'as you can see in the block of code below ' # create profile automatically when the user is created using (signal) ## def create_profile(sender , **kwargs): if kwargs['created']: Profile.objects.create(PRF_user=kwargs['instance']) if kwargs['update_fields']: print ('some table are updated this is a test') print('all kwargs') print(kwargs) print('end kwargs') #done create profile automatically ## post_save.connect(create_profile , sender=User) enter image description here outprint all kwargs {'signal': <django.db.models.signals.ModelSignal object at 0x00000000037D2780>, 'instance': <User: khder_admin@local.com>, 'created': False, 'update_fields': No ne, 'raw': False, 'using': 'default'} end kwargs how can i tell django to populate 'update_fields' values and send it by signal to my function!? . -
Django modelformset is not validating when trying to update
In my project i am working with modelformsets to create many instances as needed once, when creating those instances modelformsets work like a charm but when i try to update those instances it returns the next error: [{'id': ['Select a valid choice. That choice is not one of the available choices.']}, {'id': ['Select a valid choice. That choice is not one of the available choices.']}, {}] This error appears the same times as the length of the instances i am trying to update. Searching through the documentation i found out that when rendering manually my forms, i needed to render the form id's hidden input, i already did that and did not fixed the problem. I would leave my views and forms below: Views //Add Patient View def add_patient(request): if request.method == 'POST': patient_form = PatientForm(request.POST) allergies_form = AllergiesInformationFormset(request.POST) antecedents_form = AntecedentFormset(request.POST) insurance_form = InsuranceInformationForm(request.POST) if patient_form.is_valid() and allergies_form.is_valid() and antecedents_form.is_valid() and insurance_form.is_valid(): patient = patient_form.save(commit=False) allergies_instances = allergies_form.save(commit=False) antecedents_instances = antecedents_form.save(commit=False) insurance = insurance_form.save(commit=False) patient.created_by = request.user patient.save() for allergy_form in allergies_instances: if allergy_form in allergies_form.deleted_objects: allergy_form.delete() else: allergy_form.patient = patient allergy_form.save() for antecedent_form in antecedents_instances: if antecedent_form in antecedents_form.deleted_objects: antecedent_form.delete() else: antecedent_form.patient = patient antecedent_form.save() insurance.patient = patient … -
How to serialize part of a new model based on the user that is logged in (in Django REST framework)
I'm creating a cloud file manager application targeted towards businesses, the project's github is here. I have a Profile model, which is a simple extension of the User model in django.contrib.auth.models by using a OneToOne field as described here. And my use case is that, as a superuser, I should be able to create a profile and assign it to any existing company. But on the other hand, if I'm not a superuser but I am in the "Company Administrator" Group I should only be able to create and edit profiles that belong to my own company. I learned how to used different serializers based on the request in the ViewSet part of the program: class ProfileViewSet(viewsets.ModelViewSet): serializer_class = ProfileSerializer permission_classes = [IsAdminOrCompanyAdmin] def get_queryset(self): u = self.request.user if u.is_superuser: return Profile.objects.all() return Profile.objects.filter(company=u.profile.company) def get_serializer_class(self): if self.request.user.is_staff: return ProfileSerializer return CompanyAdminProfileSerializer But when it comes to the serializer itself, I have no idea how to make it so my company data gets filled in with the company from the request's user: class CompanyAdminProfileSerializer(ProfileSerializer): class Meta: model = Profile fields = ['url', 'user', 'cpf', 'phone_number'] def create(self, validated_data): validated_data['company'] = # ??? # request.user.profile.company would be nice, but I can't … -
Atrribute Error in Django web application
I have been trying this for some days now with no solution.I am getting this weird error after which I have made several trials all of which hasn't solved my issue, I would be glad to receive a solution. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\views\generic\list.py", line 142, in get self.object_list = self.get_queryset() File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\StaffViews.py", line 364, in get_queryset queryset = self.request.user.quizzes \ File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\utils\functional.py", line 225, in inner return func(self._wrapped, *args) Exception Type: AttributeError at /staff_quiz_home/ Exception Value: 'CustomUser' object has no attribute 'quizzes' MODELS.PY class CustomUser(AbstractUser): user_type_data = ((1, "HOD"), (2, "Staff"), (3, "Student")) user_type = models.CharField(default=1, choices=user_type_data, max_length=10) class Quiz(models.Model): owner = models.ForeignKey(Staffs, on_delete=models.CASCADE, related_name='quizzes') name = models.CharField(max_length=255) subject = models.ForeignKey(Subjects, on_delete=models.CASCADE, related_name='quizzes') class student(models.Model): name = models.CharField(max_length=255) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) gender = models.CharField(max_length=50) quizzes = models.ManyToManyField(Quiz, through='TakenQuiz') class Staffs(models.Model): name = models.CharField(max_length=255) admin = models.OneToOneField(CustomUser, on_delete = models.CASCADE) address = models.TextField() … -
How to link CSS file to pdf.html file for Django
My PDF.html is not linking to any CSS file, I have tried the following: Template PDF.HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet"> <!-- Material Design Bootstrap --> <link href='{% static "css/mdb.min.css" %}' rel="stylesheet"> <!-- Your custom styles (optional) --> <link href='{% static "css/style.min.css" %}' rel="stylesheet"> I am using the same CSS files for other templates as base.html which is working fine and linking to them but for this particular HTML it is not linking, so I am trying to find the reason for this issue Here is the base.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> ----------------------------------------------------- <link href='{% static "css/bootstrap.min.css" %}' rel="stylesheet"> <!-- Material Design Bootstrap --> <link href='{% static "css/mdb.min.css" %}' rel="stylesheet"> <!-- Your custom styles (optional) --> <link href='{% static "css/style.min.css" %}' rel="stylesheet"> -
How to connect Azure Redis Service in Django using django-redis Packages?
I wanted to config Redis with Django in Azure using azure redis one and as I learned through django-redis. we configure like this. CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "PASSWORD": "mysecret" } } } What about configuring credentials for azure redis one? -
Can’t open file manage.py
enter image description here I’m trying to deploy my first django project on heroku, and the final step doesn’t work - can’t open manage.py. But there is manage.py in the directory I copied my project on the desktop, and with the original project manage.py worked fine. So in what may be a problem - the copy or heroku? -
Django REST Generic Class based Views
Can a generic like class based views be created that only needs a serializer object with CRUD functions of any models type be passed to it that can perform all the method handlers needed for an API to work? -
I get UnboundLocalError in Django website [duplicate]
I have been trying to debug this after some few days with no solutions yet, I would be glad if I could get a solution or suggestion. Thanks I get the UnboundLocalError, things were working perfectly but when I made some changes to my models.py to fix some other bug which got resolved, this came about. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\HodViews.py", line 15, in admin_home all_student_count = student.objects.all().count() Exception Type: UnboundLocalError at /admin_home/ Exception Value: local variable 'student' referenced before assignment View.py def admin_home(request): all_student_count = student.objects.all().count() subject_count = Subjects.objects.all().count() course_count = Courses.objects.all().count() staff_count = Staffs.objects.all().count() # Total Subjects and students in Each Course course_all = Courses.objects.all() course_name_list = [] subject_count_list = [] student_count_list_in_course = [] for course in course_all: subjects = Subjects.objects.filter(course_id=course.id).count() students = student.objects.filter(course_id=course.id).count() course_name_list.append(course.course_name) subject_count_list.append(subjects) student_count_list_in_course.append(students) subject_all = Subjects.objects.all() subject_list = [] student_count_list_in_subject = [] for subject in subject_all: course = Courses.objects.get(id=subject.course_id.id) student_count = student.objects.filter(course_id=course.id).count() subject_list.append(subject.subject_name) student_count_list_in_subject.append(student_count) # For Staffs staff_attendance_present_list=[] staff_attendance_leave_list=[] staff_name_list=[] staffs = Staffs.objects.all() for staff in staffs: subject_ids = Subjects.objects.filter(staff_id=staff.admin.id) … -
Is it possible to user multiple custom user model in django?
I'm trying to make custom user model with AbstarcBaseUer in django 3.1. There are two types of user in my app. Reader, Publisher. Each model should have different fields, so I decided to make two tables for each. First I made Parent class for them, named User which inherit from AbstractBaseUser. class User(AbstarctBaseUser, PermissionMixin): email = models.EmailField(primary_key=True) USERNAME_FIELD = 'email' # and some other fields and setting Second I made Reader and Publisher class which inherit from User class. class Reader(User): # for Reader model Fields class Publisher(User): # for Publisher model Fields Is this structure available in django? And if it is, how do I override UserManger for these?