Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
set attribute error while trying to open admin panel in django
i am new to django and building a app when i added api app after creating api app i could not access the admin panel and i could not find how to slove this error any help would be appreciated, whene ever i try opening admin panel it shows the following error in command prompt: Internal Server Error: /admin/ Traceback (most recent call last): File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 249, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 499, in index app_list = self.get_app_list(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 482, in get_app_list app_dict = self._build_app_dict(request) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\contrib\admin\sites.py", line 449, in _build_app_dict model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name) File "C:\Users\Ganesh Akshaya\.virtualenvs\lcodev-bnkaAQPk\lib\site-packages\django\urls\base.py", line 55, in reverse app_list = resolver.app_dict[ns] File "C:\Users\Ganesh … -
How to download file from file field in django framework
I want to download a file from the file field through Django views. I tried al lot but didn't get it. Now if I click on the media link it will show in the browser and I want to download it. Thanks in advance. models.py class Question(models.Model): title = models.CharField(max_length=254) file = models.FileField(upload_to='exam/question') def __str__(self): return self.title -
MAX_ENTRIES is not working in django-redis
I am using Redis for caching in my multi-tenant system. And for testing purpose of the MAX_ENTRIES, I put 'MAX_ENTRIES': 2 in Both filebased.FileBasedCache and cache.RedisCache. Filebased is working fine ( it doesn't save more than 2 items as expected) But Redis is saving all the data and it is not deleting after reaching the limit. My 2 caches- 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'BACKEND': 'django_redis.cache.RedisCache', Here is the Screenshot of the Redis db:2 where values are not being deleted -
bad operand type for unary +: 'list' - Django Error
I deployed a django application a while ago and I just checked the website today and it gave me this error: bad operand type for unary +: 'list' Kindly let me know what might be the probelm -
why are arguments passed in dictionary falling into args in python 3?
My understanding according to, https://realpython.com/python-kwargs-and-args/ args getting mapped to kwargs in python is if you pass dictionary as an argument to the function, we receive it in kwargs. I'm trying to do it in a following way, views.py uniqueurl_extra_form = UniqueUrlExtraFieldsForm(request.POST or None, request.FILES or None, {"store_id" : store_details['store_id']}) forms.py class UniqueUrlExtraFieldsForm(forms.Form): def __init__(self, *args, **kwargs): store_id = kwargs.get("store_id", None) super(UniqueUrlExtraFieldsForm, self).__init__(*args, **kwargs) print(args, kwargs) but what I'm getting is (None, None, {'store_id': 41141}) {} Why is my dictionary getting received in args instead of kwargs? and kwargs returning empty? What am I doing wrong here? -
Unable login using google social login
I used to login using same query i have written for my project but since few days i am unable to login using google social login. def google_login(request): if "code" in request.GET: params = { "grant_type": "authorization_code", "code": request.GET.get("code"), "redirect_uri": request.scheme + "://" + request.META["HTTP_HOST"] + reverse("social:google_login"), "client_id": settings.GP_CLIENT_ID, "client_secret": settings.GP_CLIENT_SECRET, } info = requests.post("https://accounts.google.com/o/oauth2/token", data=params) info = info.json() if not info.get("access_token"): return render( request, "404.html", { "message": "Sorry, Your session has been expired", "reason": "Please kindly try again to update your profile", "email": settings.DEFAULT_FROM_EMAIL, "number": settings.CONTACT_NUMBER, }, status=404, ) I am getting the error messages as above mentioned because I think it's not taking the tokens. Can someone help me. -
How to fix required field error on Django's ImageField?
I'm trying to take an image as input from user. Eventhough I'm selecting an image it gives this field is required error. When I change required to False I encounter a different problem. After I select an image and post the form I don't see any file in request.FILES. When I check request.POST I see the file name but if I check form.cleaned_data the field returns none value. I added "method=multipart/form-data" to html and my forms.py and views.py is as below. I appreciate if you tell me what I am doing wrong. forms.py views.py -
django, Changing field values in model before saving to database
class PlayerList(models.Model): name = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE) d_code = models.CharField(primary_key=True, max_length = 200, editable=False) Serializers.py class PlayerSerializer(serializers.ModelSerializer): class Meta: fields = ["name", "position", "h_code", "d_code"] model = PlayerList view.py class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def get(self, request, *args, **kwargs): d_code = request.data.get('h_code') + 'test' print(d_code) print(d_code) : h000001test When entering a value through api, I want to implement that the entered value is changed to another value in view.py and saved in the db. I want to save d_code processed by def get in db. I don't know what to do. Can you please let me know? There is no answer, so I will post again. -
student management system add_students_save problem in Django python
def add_student_save(request): if request.method != 'POST': return HttpResponse("Method Not Allowed") else: first_name = request.POST.get("first_name") last_name = request.POST.get("last_name") username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") address = request.POST.get("address") session_start = request.POST.get("session_start") session_end = request.POST.get("session_end") course_id = request.POST.get("course") sex = request.POST.get("sex") # try: user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=3) user.students.address = address course_obj = Courses.objects.get(id=course_id) user.students.course_id = course_obj user.students.session_start_year = session_start user.students.session_end_year = session_end user.students.gender = sex user.students.profile_pic = "" user.save() # messages.success(request, "Successfully Added Student") # return HttpResponseRedirect("/add_student") # except: # messages.error(request, "Failed to Add Student") # return HttpResponseRedirect("/add_student") enter image description here -
How to order a list in django with name?
Here I tried like this but it is not giving me the correct ordering. from operator import attrgetter ls = [obj.attribute for obj in qs] ordered_ls = sorted(ls, key=attrgetter('name')) -
Python Django issue with makemigrations
I'm new at Django but recently I've been having some errors when entering the python manage.py makemigrations command. I tried to understand my mistake by reading the following log but I really can't: Migrations for 'main': main\migrations\0004_main_about.py - Add field about to main Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable -
do i will lose data in database if i delete migration files in django?
I have Django Project and I want to add some table in my database but I'm not able to add it because I have some Problem in Migrations files , Do I will lose my data in database if I removed all migrations files -
Unable to use django template using extends from another app
My Django project templating structure is AuthApp/ login.html MainApp/ base.html I want to use base.html file in login.html file, using below code. {% extends 'MainApp/base.html' %} {% block content %} {% endblock %} But its not inheriting the base template. Please suggest. -
Apexchart graph updateseries function not working?
Working on Apexcharts but my Updateseries in AJAX Call not working kindly help!!! Whenever I am inserting dates in datepicker in front.Data is coming from Backend as I can see in my console but Update Series/Graph is not updating in front end. Working in Django Framework. Please share as many examples of UpdateSeries in Apex Charts as posible -
Update single <td> value in the table row using ajax in django
I am trying to Block/Unblock the user without refreshing the page. If the status=1, it will show Block option, and if the status=0 it will show Unblock option After calling the function, the status will change either 0 or 1 in views.py The function is working fine but it is showing after refreshing the page How to display that value without refreshing the page <table id='usersTable' class="table table-bordered"> <thead> <tr> <th>S.No.</th> <th>Name</th> <th>Email</th> <th>Block/Unblock</th> </tr> </thead> <tbody> {% for userid, name, email, status in comb_lis %} <tr id='usr-{{name}}'> <input type="hidden" id="{{userid}}" name="{{userid}}" value="{{userid}}"> <input type="hidden" id="{{name}}" name="{{name}}" value="{{name}}"> <td>{{forloop.counter}}</td> <td>{{name}}</td> <td>{{email}}</td> <td> <a href="#" onclick="restrictUser(document.getElementById('{{userid}}').value, document.getElementById('{{name}}').value)"> {% if status == "1" %} Block {% else %} Unblock {% endif %} </a></td> </tr> {% endfor %} </tbody> and this is the ajax function function restrictUser(userid, name) { $.ajax({ url: '/restrict-user-ajax/'+userid, dataType: 'json', success: function (data) { if (data.status) { alert("User Blocked!"); } } }); } Any help is appreciated -
Troubles when I pass get_connection to EmailMultiAlternatives (django-post_office)
I need to make the connection dynamic for example: settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'post_office.EmailBackend' # EMAIL_HOST = 'smtp.office365.com' # EMAIL_USE_TLS = True # EMAIL_PORT = 587 # EMAIL_HOST_USER = '123s@123.sg' # EMAIL_HOST_PASSWORD = '*********' views.py from django.core.mail import EmailMultiAlternatives, get_connection def email_template_participants(): connection = get_connection(host=arg.email_backend.email_host, use_tls=arg.email_backend.use_tls, port=arg.email_backend.port, username=email_back, password=arg.host_password) ....... email_message = EmailMultiAlternatives(subject, body, from_email, to_email, connection=connection) template = get_template('email_participants.html', using='post_office') html = template.render(context_html) email_message.attach_alternative(html, 'text/html') email_message.attach_file(attach_file(id) template.attach_related(email_message) email_message.send() running this code : emails fail. On status: ConnectionRefusedError ( Unable to establish a connection as the target computer expressly denied that connection ) If I uncomment EMAIL_HOST, EMAIL_USE_TLS, etc the connection is denied, because they not always match, only works when they match, 1 in 15. Otherwise. if I only change EMAIL_BACKEND to 'django.core.mail.backends.smtp.EmailBackend'. It works Perfect. What can I do ???? I need all Benefits from post_office, (crons, mails listed, inlined images, etc ) -
Operators can be used to access the fields in the object by Django ORM?
Which of the following Operators can be used to access the fields in the object by Django ORM? (.) Operator (') Operator (,) Operator Both (.) and (') Operator -
! Push rejected, failed to compile Python app. -Heroku
I am trying to depoly my website but I am getting this error I am depolying it with github and the site I am using is called Heroku I am not sure why I am getting this error but I have already done all the steps I need to depoly the My runtime.txt My requirements.txt my Procfile idk if it has annything to do with my apps but here. -
Extending a column in the user table in django is not creating a entry in table
I have extended the Django user table with a boolean variable. class UserLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isFresher = models.BooleanField() I have made changes in the admin inline. class LoginInline(admin.StackedInline): model = UserLogin can_delete = False verbose_name_plural = 'loginTable' class UserAdmin(BaseUserAdmin): inlines = (LoginInline,) I have got the flag in the admin table. When I add a user to the user table I can see the flag. If I check the flag then I can see an entry True with user_id in the UserLogin table. If the flag is not checked then I can not see an entry in the table? How to make this False entry into the table? -
Stylizing ManyToMany Form (Django)
I have a question regarding the stylizing of a ManyToMany field form submission. Currently, I am using the Checkbox widget. The problem is this field will eventually have 80+ options. I was curious if there are any better widgets for this case? If not, how could I go about implementing a search and select for this field on the front end? Thank you! P.S: I do understand the second question could involve a lot of code, so please feel free to provide an approach to the problem instead. class CourseUpdateForm(forms.ModelForm): activesubjects = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Profile fields = ['activesubjects'] -
How do you modify the Django Admin UI?
Whenever I see a tutorial customizing the Admin interface this is always the way they customize it like changing the header text and image, changing the color, etc. Is there a better way of making it more like this implementing the Vue Admin Dashboard to the Django Admin? and also, in this website https://djangopackages.org/grids/g/admin-interface/ is this the Only Admin UI you can use? -
Django rate limiting outgoing requests
I'm new to Django and Python, so my understanding of the fundamentals might be wrong. I'm building an app with Django + Nginx + Gunicorn. For every client request, the app needs to call another service to retrieve information. The information is then used to serve the client. Currently, the app does this by: Establishing a TCP connection to the service Exchange data Closes the connection When the request load is high, this connection overhead becomes an issue. On top of that, I should be worried about the number of sockets being created. I think creating a connection pool to rate limit the number of outgoing requests would be a good idea. However, I don't really know how get started...I have a couple of questions: How can I create a ConnectionPool object in Django that is accessible by all of my Django app? Assuming that I'm able to create a connection pool in Django, and I have two Gunicorn workers, will both workers maintain their own separate connection pools? -
django, Changing field values in model before saving to database
models.py class PlayerList(models.Model): name = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE) d_code = models.CharField(primary_key=True, max_length = 200, editable=False) Serializers.py class PlayerSerializer(serializers.ModelSerializer): class Meta: fields = ["name", "position", "h_code", "d_code"] model = PlayerList view.py class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def get(self, request, *args, **kwargs): d_code = request.data.get('h_code') + 'test' print(d_code) print(d_code) : h000001test When entering a value through api, I want to implement that the entered value is changed to another value in view.py and saved in the db. I want to save d_code processed by def get in db. I don't know what to do. Can you please let me know? -
In django how to GROUP_BY raw and bellow my question
How to gourp_by() column based on RID. My Actual output HERE IMAGE Whatever values are displayed in the Months Names like [Jan, Feb,...., Des], all the values come from the one table column. I want to display all values in one particular column like the below image. Expected output HERE IMAGE Models.py Here my registration table(primary key table). class Registration(models.Model): Registration_ID = models.IntegerField(auto_created=True,primary_key=True) Surname = models.CharField(max_length=20) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) MobileNumber = models.IntegerField() Email = models.CharField(max_length=50) Password = models.CharField(max_length=30) Gender = models.CharField(max_length=10) FamilyMembers = models.IntegerField() PlotNumber = models.IntegerField() PlotType = models.CharField(max_length=20) Partition = models.CharField(max_length=10) FlatNumber = models.CharField(max_length=10) Rent = models.CharField(max_length=10) RentalFloor = models.CharField(max_length=10) Is_Active = models.BooleanField(default=0) Is_Admin = models.BooleanField(default=0) Owner_Rent = models.IntegerField(null=True,default=0) Rental_Rent = models.IntegerField(null=True,default=0) Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Registration' Here my maintenance table(foreign key table). class Maintenance(models.Model): Maintenance_ID = models.IntegerField(auto_created=True,primary_key=True) Registration_ID = models.ForeignKey(Registration, on_delete=models.CASCADE) ReceiptNumber = models.IntegerField(null=True) ReceiptDate = models.DateField(null=True) FromDate = models.DateField() ToDate = models.DateField() FeeType = models.CharField(max_length=30) PaymentMode = models.CharField(max_length=20) Remark = models.CharField(max_length=20, null=True) BankName = models.CharField(max_length=30,null=True) ChequeNumber = models.CharField(max_length=30,null=True) ChequeDate = models.DateField(null=True) Money = models.IntegerField() Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Maintenance' Views.py paginator = Maintenance.objects.all().order_by('Registration_ID_id') page = request.GET.get('page', 1) Qry_All_Maintenance_List = Paginator(paginator, 25) … -
Django --> python manage.py runserver
I had previous django project named 'bike_project'. And i had two settings module for development and production inside settings folder of bike_project. During that project i had set DJANGO_SETTINGS_MODULE = bike_project.settings.development in command prompt. But now when i create new django project (seller bike), the project is created. But when i run python manage.py "command", I get following error. D:\seller_bike>python manage.py runserver Traceback (most recent call last): File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line …