Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnboundLocalError in Django web application
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\StaffViews.py", line 31, in staff_home students_count = student.objects.filter(course_id__in=final_course).count() Exception Type: UnboundLocalError at /staff_home/ Exception Value: local variable 'student' referenced before assignment View.py def staff_home(request): # Fetching All Students under Staff subjects = Subjects.objects.filter(staff_id=request.user.id) course_id_list = [] for subject in subjects: course = Courses.objects.get(id=subject.course_id.id) course_id_list.append(course.id) final_course = [] # Removing Duplicate Course Id for course_id in course_id_list: if course_id not in final_course: final_course.append(course_id) students_count = student.objects.filter(course_id__in=final_course).count() subject_count = subjects.count() # Fetch All Attendance Count attendance_count = Attendance.objects.filter(subject_id__in=subjects).count() # Fetch All Approve Leave staff = Staffs.objects.get(admin=request.user.id) leave_count = LeaveReportStaff.objects.filter(staff_id=staff.id, leave_status=1).count() #Fetch Attendance Data by Subjects subject_list = [] attendance_list = [] for subject in subjects: attendance_count1 = Attendance.objects.filter(subject_id=subject.id).count() … -
Django rest framework filter not working with django-2.1
1 I'm using Django 2.1, Django REST Framework(3.9) and Django Filters to filter the queryset. Program model has a foreign key to Department and thus want to filter based on DepartmentID When I try to search filter in rest framework it does not return filtered data. What am I doing wrong? class ProgramFilter(filters.FilterSet): class Meta: model = Program fields = ('programCode', 'pro_name', 'pro_shortForm', 'DepartmentID') class ProgramViewSet(viewsets.ModelViewSet): queryset = Program.objects.all() serializer_class = ProgramSerializer filterset_class = ProgramFilter filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) __basic_fields = ( 'programCode', 'pro_name','pro_shortForm', 'DepartmentID') filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilter) filter_fields = ('programCode', 'DepartmentID') search_fields = ('DepartmentID') -
i want to show a html page in my Root Domain in Django
I Want to Show a HTML page in Root Domain in Django, tried to many times but, can't solve this problem, anyone help please. -
Codecoverage of a running server
For python you've got the codecoverage library to check your codecoverage. This works fine for unittests. However I'm interested to get the code coverage when running integration tests. I'm running the integration tests with cypress.io. So cypress.io is accessing a development server and runs the tests that way. I've tried to instrument the django development server the following way coverage run -p --source=code_folder ./manage.py runserver After the tests have run I run coverage combine and coverage report. Code that should have ran is marked as missing. So it seems like it's not properly instrumented. How can this be amended? -
Sending data between web-based app and desktop app
What is a generic concept of how to send data between a web-based app with Django and a desktop app with PyQT? For eg., user A fills in a form and uploads a data file to the web-based app. Another user B running the desktop app is to do some computation on the data file without the need to go into the web app (he has internet access, of course), and send result back to display on the web app of user A. You may ask, why not both users using the web app. This is due to responsibility separation and hardware access (user B has, but not user A). If someone could point to where or what to read up on this, thanks very much. -
Retrieve SocialAccount token and refresh token from django-allauth
I am trying to interface with the Gmail API using Django and django-allauth for authentication. I have configured my project according to the django-allauth documentation for Google. I am able to log in with a Google account and can see the account details on the Django admin page. Still I am unable to retrieve the token and refresh token to create a google.oath2.credentials.Credential object to pass to the Gmail API. Here is my current attempt: from allauth.socialaccount.models import SocialApp, SocialAccount from google.oauth2.credentials import Credentials def get_credentials(request): app = SocialApp.objects.get(provider='google') account = SocialAccount.objects.get(user=request.user) user_tokens = account.socialtoken_set.first() creds = Credentials( token=user_tokens.token, refresh_token=user_tokens.refresh_token, client_id=app.client_id, client_secret=app.client_secret ) return creds However, the user_token object is coming back as None, so the account.socialaccount_set must be empty. I'm not sure how this is possible if the request.user is correctly populated (I have verified that it is correct). Am I missing something? Any help is appreciated! -
Django - How to get checked objects in template checkboxes?
Im new in Django, I'm using xhtml2pdf for rendering data objects from template to PDF file , and i want to allow users to render only checked objects by checkboxes into pdf, is there anyway to filter that in Django ? Thanks views.py : def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode('ISO-8859-1')), result, link_callback=link_callback) if pdf.err: return HttpResponse('Error') return HttpResponse(result.getvalue(), content_type='application/pdf') class ViewPDF(View): @method_decorator(login_required(login_url='livraison:login_page')) def get(self, request, *args, **kwargs): checked_objects = [i dont know how to get them] queryset = Livraison.objects.filter(id__in=[checked_objects]) # i want something does that data = { 'livraisons' : queryset, 'now' : f'Livraisons-{date.today()}' } pdf = render_to_pdf('pdf_template.html', data) return HttpResponse(pdf, content_type='application/pdf') -
ReactJS with Python as Backend
What is the best approach to use ReactJS as front end and Python as a backend? I already built a tool using Tkinter which have simple UI. I want to use ReactJS and rebuild this application that anyone can install on their desktops. Is it possible? If so can anyone briefly explain the workflow or any online resources would be appreciated. Thank you! (I have a basic knowledge using Djnago) -
Is Nginx needed using an openshift router in django app?
I have a question. Is it necessary to use nginx when using an openshift router. I will add that the application is written in Django and uses gunicorn. If Nginx is needed please explain why. greetings -
CREATING DOWNLOAD LINK WITH EXPIRATION THROUGH EMAIL DJANGO/PYTHON
I'm building a function that sends an email with pdf download link that expires in a day.The download link is unique and looks like this: http://127.0.0.1:8000/download?e=eJzTyCkw4AozNDMwsriXoAIqENGQ==&h=aa23401994b8 And I added this on my views.py if expiring_date > day_opened: with open('example.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="example.pdf"' return response else: with open('yourLinkHasExpiredPage.html', 'rb') as html: response = HttpResponse(html.read(), content_type='text/html') return response I don't have a problem returning the pdf file, the problem starts when I try to open the link again after a day and it returns to server 500 error instead of the page that says the link has expired. -
How to build one to one chat system with django
Is there any django expert who has experience to build chat system quite similar to Facebook. I want to ask that how can I build chat with django, do I have to use django restframe also? And what is the easiest and robust way to create chats. I have search about it and it feels like more harder than I imagined. I am actually feeling discouraged after searching about implementing chats in website. So if you guys have experience with chat system already than tell me something really helpful or give me complete guideline to build chat system. Many many thanks in advance to all my seniors. I am new with django so please briefly explain your answers. -
How to negate a queryset function in django?
I have this queryset in django 3.1 class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) def active(self): return self.filter(status__in=["PENDING"]).filter( date_created__gt=timezone.localtime() - self.model.ACTIVE_THRESHOLD ) Notice that in active function there is just negation from expired function in the second filter. I did it like this, because I could not figure out a more simple solution. But it feels like there should be a way to negate what a queryset function filters? What I imagine and what feels much more natural is something like class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) def active(self): return self.filter(status__in=["PENDING"]).not(self.excluded) Is something like this possible? or should I just go for something like: class AuthenticationQuerySet(InheritanceQuerySet): def expired(self): return self.filter(self._expired_condition) def active(self): return self.filter(date_resolved__isnull=True, status__in=["PENDING"]).exclude(self._expired_condition) @property def _expired_condition(self): return Q(date_created__lt=timezone.localtime() - self.model.ACTIVE_THRESHOLD) ? but this seems just really ugly and hacky... Thanks for suggestions! -
Broken Comment section after implementing like button AJAX in Django Blog
For some reason nobody is able to make comments after I implemented the like button, which requires the user to be logged. @login_required def like(request): if request.POST.get('action') == 'post': result='' id = request.POST.get('postid') post= get_object_or_404(Post, id=id) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) post.like_count -= 1 result= post.like_count post.save() else: post.likes.add(request.user) post.like_count += 1 result = post.like_count post.save() return JsonResponse({'result': result, }) The error says: ValueError: invalid literal for int() with base 10: 'xxx-xxx-xxx (slug parameter) ValueError: Field 'id' expected a number but got 'xxx-xxx-xxx' (slug parameter). I'm really lost with this, I think that the Ajax code may not be working well or not well coded: $('#myForm').trigger("reset"); $(document).on('click', '#like-button', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: "{% url 'like' %}", data: { postid: $('#like-button').val(), csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function (json) { document.getElementById("like_count").innerHTML = json['result'] console.log(json) }, error: function (xhr, errmsg, err) { } }); }) </script> The button works perfectly well. The web only get broken when u try to add a comment. path('article/<slug:slug>/comment/', AddCommentView.as_view(), name='add_comment'), class AddCommentView(CreateView): model = Comment form_class = CommentForm template_name = 'add_comment.html' def form_valid(self,form): form.instance.post_id = self.kwargs['slug'] return super().form_valid(form) Any suggestion will be appreciated. Thanks in advance. -
Keep getting random No reverse match error in django blog page while trying to make a comment section appear under each post?
User posts is a page where the logged in user can view their own posts and it functions fine. I don't know why django says the error is in my base template near the html navbar of the page. Here is my comment model class comment(models.Model): linkedpost = models.ForeignKey(Post, related_name="postcomments", on_delete=models.CASCADE) commentauthor = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(max_length=100) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.linkedpost.title My home page template where the blog posts are looped through and the comments are also looped through under each post. {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> <div> <h2>Comments</h2> {% for cmnts in post.postcomments.all %} #<a class="mr-2" href="{% url 'user-posts' cmnts.author.username %}">{{ cmnts.commentauthor }}</a> <small class="text-muted">{{ cmnts.date_posted|date:"F d, Y" }}</small> <p class="article-content">{{ cmnts.body }}</p> {% endfor %} </div> </div> </article> {% endfor %} Project Urls.py urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/loginpage.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), path('passwordreset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='passwordreset'), path('passwordreset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='passwordresetdone'), … -
Passing data between veiws.py and template.html in django
I am new in Django. I want to write a very simple code to create a string in views.py and shows in an html file in templates.: views.py from django.shortcuts import render from django.http import JsonResponse def index(request): F = 100 response = str(F + 10) response1 = {"Main": response} template_name = "homepage.html" return render(request, template_name, response1) urls.py urlpatterns = [ path('', views.index, name='homepage.html'), path('admin/', admin.site.urls)] homepage.html <html> <head> <h1>User Information</h1> </head> <h2>Answer: {{response1}}</h2> </html> What I get on webpage is the headers without {{response1}} -
ModuleNotFoundError: No module named 'mysite.polls' in django tutorial while testing
I am coding along tutorial from django documentation site: https://docs.djangoproject.com/en/3.1/intro/tutorial05/ I got a following problem: While trying to run test on my app (with: py manage.py test polls in Pycharm commndline) i get following error: > ImportError: Failed to import test module: mysite.polls Traceback > (most recent call last): File > "C:\Users\micha\Anaconda3\envs\DjangoTutorial\lib\unittest\loader.py", > line 470, in _find_test_path > package = self._get_module_from_name(name) File "C:\Users\micha\Anaconda3\envs\DjangoTutorial\lib\unittest\loader.py", > line 377, in _get_module_from_name > __import__(name) ModuleNotFoundError: No module named 'mysite.polls' The file structre of my project is as follwoing: link to the directory tree img It looks like testing unit automaticcaly adds 'mysite' in front of 'polls' What i tried: I have tried to lookup for an answer in django test documentation. Only solution that i was able to find was to change command to like like this: py manage.py test polls.tests Then it runs my test properely. As far as I understand django documentation, django should automatically find every 'test*' file in polls yet in case of mine it cannot find 'polls' module. Can you tell me why it happens? -
uWSGI + Django - Confused between no of process and threads while deploying
I think i am stuck in some basics. My system has 8 cores (4 physical and 4 logical cores) I developed a basic django application. I want to deploy it with uWSGI. To achieve concurrency I have to specify number of processes and threads in uWSGI config. Here come's the confusion. To start with, I have 2 options Option 1: No of process = 8 Option 2: No of process = 4 No of threads per process = 2 https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#adding-concurrency-and-monitoring If I get 8 simultaneous request, what is the impact in both the options? What does the no of thread per process exactly means here? If my app does not use multithreading, will option 2 will be useful to me? Python GIL will be disabled in option 2, so there must be some disadvantages to it. I appreciate, if someone can guide me. Thank You! -
Reorder Django ModelForm Fields After Adding Additional Field
I have this model: class StudentResult(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) test = models.FloatField(default=0) exam = models.FloatField(default=0) I created a ModelForm from it and added session_year (which is not in the model) as shown below: class EditResultForm(FormSettings): session_list = Session.objects.all() session_year = forms.ModelChoiceField( label="Session Year", queryset=session_list, required=True) def __init__(self, *args, **kwargs): super(EditResultForm, self).__init__(*args, **kwargs) class Meta: model = StudentResult fields = ['subject', 'student', 'test', 'exam'] session_year displays as the last form element. How can I display it as the first form element. I tried: fields = ['session_year', 'subject', 'student', 'test', 'exam'] But since session_year is not in the model, it raised an error. How can I achieve this? -
Django not rendering template from class based view
I only need to display a column from my table as dropdown on the template. I'm using class based view and not sure what am I doing wrong since i just need to diplay the data as it is. <app/models.py> class DBModel(models.Model): id = models.BigAutoField(primary_key=True) url = models.TextField(blank=True, null=True) user_name = models.TextField(blank=True, null=True) class Meta: db_table = 'demotable' def __str__(self): return str(self.url) <app/forms.py> class ChooseForm(forms.ModelForm): list = forms.ModelChoiceField(queryset=DBModel.objects.all().distinct(), empty_label="(Nothing)") <app/views.py> class ChooseView(CreateView): template_name = 'form_list.html' form_class = ChooseForm def get(self, request, *args, **kwargs): form = self.form_class(request.GET) return render(request, self.template_name, {'form' : form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) return render(request, self.template_name, {'form': form}) <templates/form_list.html> <form method="post"> {% csrf_token %} {{ form.list }} <button type="submit" class="btn btn-primary btn-border" name="show-list">Continue..</button </form> <app/urls.py> urlpatterns = [ url('main_page/', views.ChooseView.as_view(), name='main_page') ] -
Django: Haystack with ajax
Let me cut to the chase. All i want is to render a SearchQuerySet as a list/dictionary or anything that can be serialized by JsonReponse. Is there a method or special technique that achieved this? -
Django: How to filter objects on values coming from functions?
I have two models: Company and Service. In order to filter on Service objects based on the company website, I do the following: company = Company.objects.get(id=some_id) service = Service.objects.filter(website=company.website) Now, suppose I have a function f(website) that only returns the hostname of the website, and I want to filter for instances where f(website of the service) would be equal to f(website of the company). Now, company = Company.objects.get(id=some_id) service = Service.objects.filter(f(website)=f(company.website)) gives syntax errors (obviously). What is the proper way to do this simple filtering? -
creating queues dynamically with realtime data, and assigning task to those quese in celery in python
i am getting realtime data of live football matches and i want to create a multiple queues for every matches in celery. For example whenever i will get data for match_id = 203, than i will create one queue named 203 and i will submit my task of processing this match data in 203 queue, like this for each match there should be a queue, where i will process all incoming data for that match only. mode of incoming data will be like this, sometime i can get data for match_id 203 than after i can get data for match_id = 204 or match_id=3,and agaiin new data for match id=203 means there will not be any sequence or pettern. and there will be multiple incoming updates for each match and in no particular order. All creation of queues for each match and assigning task to their queues respectively, should happen dynamically I wont know in advance how many matches will be there, there can be maximam 200 live matches at any time How i can achieve this in python using celery, i am using redis with celery -
What makes the developer efficiency low?
I am conducting a survey to understand what blocks a software developer in their day to day work life to focus primarily on coding. Please help out with filling a 2 minute survey -> https://forms.gle/XsdPevQMQGMfYYkR8 This is a part of a study and I plan to seek feedback from people who have had a first hand experience developing software. -
Fatal error and unable to create django process
So I am trying to create a new project with Django. However, when I tried to create a new project, I got an error message. Here's what my command prompt looks like so far Microsoft Windows [Version 10.0.19041.572] (c) 2020 Microsoft Corporation. All rights reserved. C:\Users\Ben>cd Documents C:\Users\Ben\Documents>django-admin startproject photoshare Fatal error in launcher: Unable to create process using '"c:\users\ben\appdata\local\programs\python\python38-32\python.exe" "C:\Users\Ben\AppData\Local\Programs\Python\Python38-32\Scripts\django-admin.exe" startproject photoshare': The system cannot find the file specified. C:\Users\Ben\Documents> I've never had this issue before, so....hoping someone can help me figure it out?! I've been tying my head around it all afternoon. -
Can't get Django to render template
I am trying to get my view to render my HTML through a POST request from javascript but I can't make it work using the onclick="" function of an tag? I'm struggling to find an answer as I'm not sure how to pose the question so I will just try to show.... My view looks like: def photos(request): BASE_DIR = Path(__file__).resolve().parent.parent workingDir = os.path.join(BASE_DIR, 'main', 'static', 'gallery', 'img') vehicle = request.POST.get('car') # Assigns the 'pass_vehicle' JS function returned value to 'vehicle' variable print(request) # Debug number_of_images = len(os.listdir(f'{workingDir}/{vehicle}/')) - 1 # Retrieve number of images within folder for <p> tag cols = [(3, 6, 3), (8, 4), (6, 6), (4, 8)] # CSS columns used below for displaying images in specific layout on HTML page htmlText = [] imgNum = 0 while imgNum <= 25: # During development limit number of pictures to display (will have specific amount in deployment) for colNum in cols: for x in range(len(colNum)): # Generate HTML to display each image within folder within the CSS column layout above imgNum += 1 inputText = f'<div class="col-6 col-md-6 col-lg-{colNum[x]}" data-aos="fade-up">\n <a href="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" class="d-block photo-item" data-fancybox="gallery">\n <img src="/main/static/gallery/img/{vehicle}/img_{imgNum}.jpg" alt="Image" class="img-fluid">\n <div class="photo-text-more">\n <span class="icon icon-search"></span>\n</div>\n</a>\n</div>' htmlText.append(inputText) context = …