Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i get total number of leaves approved - excluding compoff leaves from approved leaves
I'm writing code for a leave_management - in which "i want to add casual leaves and sick leave and print all Approved Leaves" excluding "comp-off leaves approved"- how can i do it.? this is my - views.py file employees = Employee.objects.filter(email=request.user.email) if Leave.objects.filter(emp__in=employees).exists(): leaves = Leave.objects.filter(emp__in=employees).order_by('-created_datetime') total_employee_leaves = {} applied_leaves = {} tot_emp = {} rem_emp = {} actual_total_leaves = {} for t in TotalLeave.objects.all(): total_employee_leaves[t.name] = Leave.objects.filter(emp__in=employees,leave_type__name=t.name,leave_type__year__year=datetime.now().year).aggregate(Sum('days'))['days__sum'] total_employee_leaves[t.name] = {} total_employee_leaves[t.name]['available'] = TotalLeave.objects.filter(year__year=datetime.now().year).values_list('days',flat=True).get(name=t.name) for key, value in total_employee_leaves.iteritems(): total_employee_leaves[key]['applied'] = Leave.objects.filter(emp__in=employees,leave_type__name=key,leave_type__year__year=datetime.now().year).aggregate(Sum('days'))['days__sum'] total_employee_leaves[key]['approved'] = Leave.objects.filter(emp__in=employees,approval_status=True,leave_type__name=key,leave_type__year__year=datetime.now().year).aggregate(Sum('days'))['days__sum'] if total_employee_leaves[key]['approved'] is not None: total_employee_leaves[key]['remaining'] = total_employee_leaves[key]['available'] - float(total_employee_leaves[key]['approved']) #--used to print the number of current month currentmonth=datetime.now().strftime("%m") #print currentmonth getmonth =Employee.objects.get(email=request.user.email) # to get the number of the month employee joined doj_month_num=getmonth.doj.month #print doj_month_num a=doj_month_num-1 #print a b=(float(currentmonth)-float(a)) total_no_of_leaves = Leave.objects.filter(emp__in=employees,approval_status=True).aggregate(Sum('days'))['days__sum'] #print total_no_of_leaves balancepermonth= (b*1.5)-total_no_of_leaves print balancepermonth -
Can't call Celery in Django
So the problem is that when I try to call main task from Django views.py page shows that loading icon and thats it, nothin else happens. There is no output in Django or Celery console. When I try and run the task from python shell it runs without a problem and saves result in db. I added add task for test purposes and when I run add task it returns an error because of missing 'y' argument which is normal. But what is up with that main task? There is my code just in case. settings.py import djcelery INSTALLED_APPS = [ ... 'djcelery', 'django_celery_results', ] CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_ACCEPT_CONTENT = ['json'] CELERY_ALWAYS_EAGER = False djcelery.setup_loader() celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'acpvs.settings') app = Celery('acpvs') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def … -
importError: No module named django.core.wsgi while using openstack dashboard
I am using Openstack Liberty and Ubuntu 14.04. After installing openstack dashboard , things were working pretty fine and then I decided to uninstall and reinstall the openstack dashboard package due to a colleague configuring SSL wrongly and changing the dashboard theme to customize it. Now, I get the following error . mod_wsgi (pid=30567, process='horizon', application='cpph-ch01-blade02|/horizon'): Loading WSGI script '/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi'. sys.path is: ['/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Target WSGI script '/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi' cannot be loaded as Python module. Exception occurred processing WSGI script '/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi'. Traceback (most recent call last): [:error] [pid 30567:tid 140400988059392] File "/usr/share/openstack-dashboard/openstack_dashboard/wsgi/django.wsgi", line 8, in <module> [:error] [pid 30567:tid 140400988059392] from django.core.wsgi import get_wsgi_application [:error] [pid 30567:tid 140400988059392] ImportError: No module named django.core.wsgi In the target script shown below, I print the syspath . Not sure if this matters but I have the target wsgi script at /usr/local/lib/python2.7/dist-packages/django/core/wsgi.py 1 import logging 2 import os 3 import sys 4 # print 5 print >>sys.stderr, "sys.path is: " + str(sys.path) 6 from django.core.wsgi import get_wsgi_application 7 from django.conf import settings 8 # Add this file path to sys.path in order to import settings 9 sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '../..')) 10 os.environ['DJANGO_SETTINGS_MODULE'] = 'openstack_dashboard.settings' 11 sys.stdout = … -
NoReverseMatch Reverse for 'my_url' not found
urls.py from django.conf.urls import include, url from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.views.generic import TemplateView from django.conf import settings from .views import Search app_name = 'base' urlpatterns = [ url(r'^index/$', Search.as_view(), name='index'), url(r'^newresume/$', views.newresume, name='newresume'), url(r'^profile/(?P<pk>[0-9]+)/$', views.profile, name='profile'), url(r'^update_info/(?P<pk>[0-9]+)/$', views.update_info, name='update_info'), ] views.py def profile(request, pk): student = get_object_or_404(Students, pk=pk) return render(request, 'base/profile.html', {'student': student}) _tweet_search.html <div class="studentfio"> <a href="{% url 'profile' pk=student.pk %}"><h4>{{ student.job }}</h4></a> </div> Console error Hi all, help me with this error, please. I made a AJAX-request, after this i get an error, how can i fix that ? -
Deleting associated model instances from within model.save() not working
I'm having a problem that's somewhat difficult to explain, so please bear with me. First of all, here are the relevant versions in case this ends up mattering: Django 2.0.3, Python 3.6.4, PostgreSQL 10.3. Essentially, I have this structure for a few of my Django models: class Capability(models.Model): relationships = models.ManyToManyField('self', symmetrical=False, through='CapabilityRelationship', blank=True) name = models.CharField(max_length=255) class CapabilityRelationship(models.Model): from_capability = models.ForeignKey(Capability, on_delete=models.CASCADE, related_name='from_set', blank=True, null=True) to_capability = models.ForeignKey(Capability, on_delete=models.CASCADE, related_name='to_set') number = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)]) def _get_complete_numbers(self): # generate the complete numbers using depth-first search def save(self, *args, **kwargs): # Get the complete numbers before saving. If we're not able to generate the complete numbers, something is # wrong, an error will be raised, and we don't want to save. complete_numbers = self._get_complete_numbers() super().save(*args, **kwargs) # Call the "real" save() method. # Delete all old complete numbers. self.capabilityrelationshipcompletenumber_set.all().delete() # Save the new complete numbers. for complete_number in complete_numbers: CapabilityRelationshipCompleteNumber.objects.create(capability_relationship=self, complete_number=complete_number) class CapabilityRelationshipCompleteNumber(models.Model): capability_relationship = models.ForeignKey(CapabilityRelationship, on_delete=models.CASCADE) complete_number = models.CharField(max_length=255, unique=True) To describe these models in words, I have a Capability model, which has a many-to-many relationship with itself (captured in CapabilityRelationship). In practice, this will be a "tree" where each node can have multiple children and multiple parents (i.e., it's a … -
How to nest a model inside a model in Django database
I have the following models, currently connected by ForeignKey: class Topic(models.Model): text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__ (self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): if len(self.text) > 50: return self.text[:50] + "..." else: return self.text Is it possible to connect them in a way that in Django admin site I could go to a particular topic and have a list of all the entries displayed? Currently nothing gets displayed and I can only see the connection when I go to a particular entry (there is a dropdown saying to which topic current entry belongs). -
Display 5 Django lists in one table
I am trying to display 6 lists in one table in HTML. One column will display the subject names, 4 cols will display the grades per grading period on each subject and the last col will display the final grade. I am having trouble displaying it onto the html. test.html {% for object in object_list %} <tr> <td>{{ object.schedule.name }}</td> <td>{% for grade in quarter_grades.0 %} {{grade}} {% endfor %} </td> </tr> {% endfor %} I would like to know what is the best approad to do this? -
Cross-platform python venv
I build a Django Site using venv on my windows laptop. Uploaded the venv to Digital Ocean server running ubuntu(using putty). Once you have made a venv on windows what is the best way to get a working env on linux? -
Python3, Django2, MariaDB and config files on Windows
I am working on a Django project using PyCharm. I have Django 2.0 and python 3.6. I am developing on a Windows machine and using git to deploy to a remote test site. On my desktop I have the latest stable MariaDB installed with a DB config file in my home directory. The remote machine is a linux box. My project settings.py file has a DB section like: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(os.path.expanduser('~'), '.my.cnf'), 'read_default_group': "myappdev" if DEBUG else "myapp", 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } } This works fine on the linux box. The default file is found and the correct group/section is read. On Windows, not so much. In a Windows terminal I can start python and type: >>> insert os >>> os.path.join(os.path.expanduser('~'), '.my.cnf') 'C:\\Users\\me\\.my.cnf' and see the path I expect but in PyCharm's debug mode the config file is not being opened or the correct section is not being found. I know the cnf file works because from the Windows command prompt I can try to start the client: C:\Program Files\MariaDB 10.2\bin>mysql --defaults-extra-file=c:\Users\me\.my.cnf Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 11 Server version: … -
request.user is false condition not working in template
Here's my template: {% if instance.ad or instance.user == request.user or request.user.is_authenticated == False %} I recently added request.user.is_authenticated == False in this condition and now it is not working. It should fire if the user is not logged in. Any idea what the problem is? -
django:When I click on the text1 page, the page does not jump to my article
When I click on text 1, the page does not respond this is urls: from django.conf.urls import url from . import views urlpatterns = [ url(r'$',views.blog_title,name='blog_title'), url(r'(?P<article_id>\d)/$',views.blog_article,name='blog_article'), ] this is views: def blog_article(request,article_id): article = models.BlogArticle.objects.get(id = article_id) return render(request,'blog/article.html',{'article':article}) this is html: <div> <a>{{ article.body }}</a> </div> this is models: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BlogArticle(models.Model): title = models.CharField(max_length=300) author = models.ForeignKey(User,related_name='blog_post',on_delete=models.DO_NOTHING) body = models.TextField() pub = models.DateTimeField(default=timezone.now) def __str__(self): return self.title -
how return json as text file in django rest framework
That's a very naive question which means that I don't understand something very basic about how DRF works, but still: What is the way get a response from DRF in a form of text file containing json? I have a ListAPIView: class MyModelJSONView(generics.ListAPIView): serializer_class = MySerializer queryset = MyModel.objects.all() I guess I should re-write the get method of this ListAPIView somehow to get a text file (I assume by adding Content-Disposition to a response. But how? -
I can't update my post using formset
I have searched this issue but couldn't get the right answer where as there are so many questions being asked before related to that,i am using a model for post with multiple fields and other model (having foreign key of post model) for multiple image fields.I Want to update the posts i create,anybody please help me, thanks in advance Here's my views.py for update_post def update_post(request, post_id): ImageFormSet = modelformset_factory(PostPicture, form=AddPictures, extra=10, min_num=1) post_form = get_object_or_404(Posts, pk=post_id) if request.method == "POST": form = AddFile(request.POST, instance=post_form) formset = ImageFormSet(queryset=PostPicture.objects.filter(post=post_id)) if form.is_valid() and formset.is_valid(): form.save() formset.save() for form in formset: if form: image = form['image'] photo = PostPicture(post=form, image=image) photo.save() messages.success(request, 'Post updated Successfully!') return render(request, 'vehicles_app/update_post.html', { 'form': form, 'formset': formset, 'post_form': post_form, 'post_id': post_id, }) else: print(form.errors, formset.errors) else: form = AddFile() formset = ImageFormSet(queryset=PostPicture.objects.none()) return render(request, 'vehicles_app/update_post.html', {'form': form, 'formset': formset, 'post_form':post_form, 'post_id': post_id}) here's the views.py for my post(addfile) def addfile(request): query = request.POST.get('form-0-id') ImageFormSet = modelformset_factory(PostPicture, form=AddPictures, extra=10, min_num=1) if request.method == 'POST': form = AddFile(request.POST) formset = ImageFormSet(request.POST, request.FILES, queryset=PostPicture.objects.none()) if form.is_valid() and formset.is_valid(): post_form = form.save(commit=False) post_form.user = request.user post_form.save() for form in formset.cleaned_data: if form: image = form['image'] photo = PostPicture(post=post_form, image=image) photo.save() messages.success(request, … -
Django Template: Passing a variable from an include, into a dot notated path
If I am passing in a variable to a template via an include... {% include "module.html" with id=someVar %} on the other side, how can I place it inside a dot noted path in order to call an object from a source? <img class="brand-logo" src="{% static data.someVar.logo %}"> -
How can I edit a Django project in Ubuntu EC2 after it was cloned from Git?
I created an Ubuntu EC2 instance and uploaded my Django project (formerly uploaded to git) by following the steps used in the YouTube tutorial here. The Django project worked fine on my local computer using the 127.0.0.1:8000 url & port. I want to keep developing it on the Ubuntu EC2 instance, but after adding a new url, view, and template, the project breaks. As a test, I copied edits and new files back to my local computer and tried to recreate the problem, but it worked fine. Is it not possible to edit Django projects on Ubuntu EC2? Will I have to solely develop in Git and re-push to EC2 every time I want to updated my website? Thanks! -
test a custom template tag filter in django
I have an app_filter.py in a folder templatetags in the app: from django import template register = template.Library() @register.filter(name='tenRange') def tenRange(numberString): # If it is blank if numberString == '': return -1 number = int(numberString) lowerLimit = 3 mediumLimit = 5 medium2Limit = 8 newLimit = 10 if number < -1: return -2 elif 0 <= number and number < lowerLimit: return 3 elif lowerLimit <= number and number < mediumLimit: return 2 elif mediumLimit <= number and number <= medium2Limit: return 1 elif medium2Limit <= number and number <= newLimit: return 0 # If above the new limit elif number > newLimit: return -1 # If there is an error else: return -1 How would I [unit?] test the conditions (with different ints, variable types, etc...) in test_template_tags.py in the tests folder? My current limited understanding... I can't seem to find a good working example, and the docs hint at rendering a template with a specific context. I'm not sure that is required, but if it is (convention), then can you please help provide how to provide a template and context? (is it the same as rendering it from the view?, if so, how do you just find the … -
Checking if single field is valid
I'm attempting to check to see if the image field in my form is valid and, if its not, reset it to None. My code in views.py looks like this. I've commented on the 2 lines that kind of explain my intentions, but aren't valid/working. def edit_user_profile(request): if request.method == 'POST': form = EditUserProfileForm(request.POST, request.FILES, instance=request.user.userprofile) if form.is_valid(): form.save() return redirect('/accounts/profile/websitesetup2/') else: if form.image.is_valid: #not valid code (problem a) pass else: form.image = None #not valid code (problem b) args = {'form': form} return render(request, 'accounts/page1.html', args) else: form = EditUserProfileForm(instance=request.user.userprofile) args = {'form': form} return render(request, 'accounts/page1.html', args) I can't seem to figure out how to: a) Check to see if just the image field is valid b) Reset the image field to None If you have any ideas, it would be much appreciated. Thanks! -
Django email confirmation sending, but link not working | Allauth, Anymail, Mailgun, HTTPS
I have a django web app and am using Django Cookiecutter. My web app is currently https and connected and configured properly to send confirmation emails. Once a user attempts to sign up the email confirmation gets sent. The email has a link to verify the account, however, the email confirmation link is being sent as http, not https. When I click the email confirmation link, I just get a new tab opened with the link, and a blank white infinite loading screen. I reached out to Mailgun and they told me everything is fine with the mailgun config. Instead of paraphrasing, here is the direct email response they sent: I looked into the domain, , and I think I see something that may be causing issues. The domain's HSTS setting is set to 60 seconds. After 60 seconds the domain's HTTP to HTTPS rewrite expires and allows the user to load our tracking links successfully. At this time Mailgun does not support HSTS nor do we have any workarounds when using HSTS with our tracking features. If the tracking cookie (anything after /c/ in the URL) wasn't generated by the domain in the URL, the link will not resolve. … -
What is the best way to store questions with sub questions in database and store students result against those?
I am designing a database to store exam questions and result of students against the exams. Question_Meta: I have created this table which will store data of questions(exam id, type of question, marks etc.) MultiPart_Question: But to handle the questions with multiple sub questions, i have created this table which will have a foreign key from Question_Meta table and sub question details. Exam_Result: To store marks of students on question basis, i have this table which will have exam_id, student_id, question_meta_id(Question_Meta table) and marks fields. Exam_Result_MultiPart: But to store the marks on sub question basis, i created this table. It has student_id, question_part_id(MultiPart_Question) and marks fields. Now i have to display the complete exam result in django admin but i do not know how can i combine the data from Exam_Result and Exam_Result_MultiPart tables. Information that is required to be shown on list view page should have columns Exam, Question No, Sub Question No, Student, Marks. How can i achieve this in django admin? Also please guide me if i have used the correct approach in designing database schema? Thanks -
Is there a way to track transaction changes in Django ORM?
In django, is there a way to find which rows were changed during a transaction? There are CDC frameworks out there, however I would like to find the changes of a specific transaction with some sort of an ID. I would also want this to be synchronous with the rest of the runtime code. Cheers -
Django: is it a good idea to user DRF's Serializer rather than native Django forms to create forms
I am using Django. I was working on a webapp which has lot of forms. I used Django's Native Form class to create and validate forms. Now the same application i want to create api endpoints. When i was going through Django rest Framework, i found that Serializers are similar to Forms. But for sake of api end points again i have to write all the validation login i created in Forms. What i was feeling is can i shift to DRF and completely avoid Forms so that my forms and also the api end points both are taken care. -
Middleware ExceptionHandler not called
In my app directory api module I added this class: from django.http import HttpResponse class ProcessExceptionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_exception(self, request, exception): print("Exception Middleware executed") // WE NEVER GET THERE return HttpResponse('Exception caught') then in urls.py: class ServiceError(Exception): pass def test(): raise ServiceError() return "" urlpatterns = [ url(r'^test/$', test), ] I added the middleware class at the end of settings.py MIDDLEWARE: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'api.middleware.ProcessExceptionMiddleware', ] I get the init on the middleware but the call to process_exception() in my middleware doesn't happen. I can trace the code to see the method convert_exception_to_response(get_response) getting called, which converts any exception to a response. -
ERRORS: Pillow is not insalled while pip says its insalled
C:\Users\Bittu\Desktop\blog-api\src>python manage.py makemigrations SystemCheckError: System check identified some issues: ERRORS: posts.Post.image: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "pip install Pillow". C:\Users\Bittu\Desktop\blog-api\src>pip install pillow Requirement already satisfied: pillow in c:\program files (x86)\python36-32\lib\site-packages -
Django Count Aggregation Filter on Related Field Not Working
Suppose I've got 2 models Coupon and UserRedemption (and of course a user model). They look like: Coupon(models.Model): offer = models.TextField() # not important to this task limited_use = models.BooleanField(default=False) max_uses = models.IntegerField(default=0) UserRedemption(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) coupon = models.ForeignKey(Coupon) so pretty basic. There are coupons in my app and each coupon has a list of times it's been redeemed by various users. Some coupons are "limited use", ie they can only be used a certain number of times by a given user. My goal: return a list of coupons excluding the coupons which have been used the maximum number of times by the user making the request. I'm attempting to do this by annotating the coupons with the number of times it's been redeemed by the current user (n_user_redemptions) and filtering the list for coupons where limited_use = False OR max_uses > n_user_redemptions. Here is my attempted method on the Coupon class: @classmethod def get_available_user_coupons(cls, user): coupon_redemption_count = Count('userredemption', filter=Q(userredemption__user=user)) return cls.objects.annotate(n_user_redemptions=coupon_redemption_count).filter(Q(limited_use=False) | Q(max_uses__gt=F('n_user_redemptions'))) However, it's not filtering properly for the user passed in from the request. It always sets n_user_redemptions to the count of all redemptions of that coupon by all users, not just the ones for the … -
Django - Iterate POST variables and asign to object fields
(Using python 3.5.2 and Django 2.0.1) So I have a html form with +30 input fields (this is a requirement, sadly) and I want to iterate them and assign them in an object. What I have does something like this: fields=['name','surname','address','postal_code'] #Goes on for all the +30 fields client=Client() if form.is_valid(): for i,value in zip(fields,request.POST.values()): client.i = value So the fields are in the same order as the POST input I thought this would work but it does not. I'm guessing is the client.i but there is no error saying that i is not a field of client. Of course I could do like client.name = request.POST.get('name') for every +30 input field but it looks very unprofessional. I hope you guys can help me. Cheers!