Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using SendGridAPIClient in django to send emails but email is not getting sent
''' def send_functional_email(user,mail_subject): data = {} send_email = user.email message = Mail( from_email='support@abc.com', to_emails=send_email, subject=mail_subject, ) domain = settings.HOST_DOMAIN_NAME print('domain:', domain) try: sg = SendGridAPIClient( 'send grid key in here') sg.send(message) except Exception as e: data['email_error'] = True return data mail_subject='task has been created' send_functional_email(request.user,mail_subject) ''' On debugging i get this error python_http_client.exceptions.BadRequestsError: HTTP Error 400: Bad Request. The mail_subject is different according to the purpose of email -
How to speed up tasks times (Managing celery tasks with Supervisord)
I am currently running my django webapp on AWS ubuntu instances. My celery tasks are currently being managed by Supervisor. So last night I was working with my backend, doing some clean up and unleashed about 60,000 tasks. Each taking about anywhere between 40 - 110 seconds per task for each of my ubuntu instances. Any recommendations on how I can avoid accumulating a huge AWS bill and be able to knock out my 60,000 tasks quicker? At the moment I started up an additional 10 instances to take on more tasks per minute. -
Get all fields options in django
I was wondering if it was possible to get all options of a field at once in django. To be clearer let's say I have a model like this: class TestClass(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) field1 = models.PositiveSmallIntegerField( validators=[MinValueValidator(0), MaxValueValidator(50)], blank=False, null=False, verbose_name=_('Little description'), help_text=_('Little Help text')) field2 = models.CharField( max_length=250, blank=False, null=False, verbose_name=_('Verbose Name'), help_text=_('Help Text)) I know that I can do 'TestClass._meta.get_fields()' to get all fields present in my model and their type (PositiveSmallInteger, CharField for instance). I also know that I could do 'TestClass._meta.get_field('field1').help_text' and the result would be 'Little Help text'. What I want to know is if there is a way for a field to get all its options at once, something that could look like 'TestClass._meta.get_field('field1').options()'. Or even better for a model to get all options of all field at once. I will override Field class for now but I was curious Thank you ! -
django-formtools not saving form data
I was able to set up multi-step form using django-formtools. What I noticed however is that, after submitting the form, the data failed to save, although the process was 'successful'. I have tried to look at my code over and over but it does not seem clear where I may be getting it wrong. Here is my views.py class FormWizardView(SessionWizardView): template_name = "accounts/testforms.html" form_list = [EmployeeSignUpForm, FormStepTwo] def done(self, form_list, **kwargs): return render(self.request, 'accounts/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) -
How to add extra data to ListModelMixin [Django Rest Framework] list method Response without completely changing it?
I am using DRF ListModelMixin to retrieve list of objects from DB. I am completely satisfied with its' Response but I need to somehow add extra data. If Response gives just list of retrieved objects, in my case it this list has to be in data property of a bigger dictionary like: { 'success': 'True', 'data': #here is the list from ListModelMixin list Response, } And if list is empty method has to return the same dictionary but with success property being False. I tried to do it in my own way. I don't know if it is a good practice. Any suggestion on better way? Thank you all. My attempt: ''' class ProjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Project.objects.all() serializer_class = ProjectListSerializer filter_backends = (filters.DjangoFilterBackend, OrderingFilter, SearchFilter) filterset_fields = ('title', 'goal', 'collected', 'status', 'stage', 'category__id') search_fields = ('title', 'school__title', 'school__city') ordering_fields = ('id', 'created_at', 'goal', 'collected') def list(self, request): response_data = super().list(self, request).data data = { 'success': True, 'data': { 'total': len(response_data), 'items': response_data, } } return Response(data=data, status=status.HTTP_200_OK) ''' -
How do I restrict non-superuser users in Django admin from choosing all user groups/permissions?
I was able to disable selection fields but a user can still use Choose all to select all the groups or all the permissions. How can I disable/remove Choose all for a regular user? Here is the code that I used so far: class UserAdmin(BaseUserAdmin): inlines = (AccountInline, ) def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) is_superuser = request.user.is_superuser disabled_fields = set() # type: Set[str] # Prevent non-superusers from editing their own permissions if not is_superuser: disabled_fields |= { 'username', 'is_staff', 'is_superuser', 'user_permissions', 'groups', 'last_login', 'date_joined', } for f in disabled_fields: if f in form.base_fields: form.base_fields[f].disabled = True return form -
Reason: Worker failed to boot
I have been trying to deploy my application heroku.But I am getting this error: I have already set heroku secret key but still it's sowing this error Also i am deploying a website oinline for first time that's why i don't know how the stuff works properly. Also in my settings i have three files the base,development and the production.The secret key is in the base and in the wsgi it refers to whole settings folder.Is that the cause of this error? 2020-02-11T14:50:26.224390+00:00 app[web.1]: [2020-02-11 14:50:26 +0000] [4] [INFO] Reason: Worker failed to boot. 2020-02-11T14:50:26.308802+00:00 heroku[web.1]: State changed from up to crashed 2020-02-11T14:50:26.290385+00:00 heroku[web.1]: Process exited with status 3 2020-02-11T14:52:26.000000+00:00 app[api]: Build started by user barbiemaker9927@gmail.com 2020-02-11T14:58:31.619104+00:00 app[api]: Deploy e9abcbdb by user barbiemaker9927@gmail.com 2020-02-11T14:58:31.619104+00:00 app[api]: Release v14 created by user barbiemaker9927@gmail.com 2020-02-11T14:58:31.949746+00:00 heroku[web.1]: State changed from crashed to starting 2020-02-11T14:58:55.486522+00:00 heroku[web.1]: Starting process with command `gunicorn fellas.wsgi —-log-file` 2020-02-11T14:58:58.248503+00:00 heroku[web.1]: State changed from starting to up 2020-02-11T14:58:57.889223+00:00 app[web.1]: [2020-02-11 14:58:57 +0000] [4] [INFO] Starting gunicorn 20.0.4 2020-02-11T14:58:57.890204+00:00 app[web.1]: [2020-02-11 14:58:57 +0000] [4] [INFO] Listening at: http://0.0.0.0:27603 (4) 2020-02-11T14:58:57.890384+00:00 app[web.1]: [2020-02-11 14:58:57 +0000] [4] [INFO] Using worker: sync 2020-02-11T14:58:57.897068+00:00 app[web.1]: [2020-02-11 14:58:57 +0000] [10] [INFO] Booting worker with pid: 10 2020-02-11T14:58:57.945704+00:00 … -
Combine results from two annotated queries
I'm trying to query django in order to get the following result: subject_name, total_grades,passed_grades,passed_precentage like maths,20,15,75.0 The queries are: from django.db.models import Count passed_bysubjects = grades.objects.filter(yeardata__year="2011-2012",grade__gte=5).values('code__name').annotate(Passed=Count('grade')) total_bysubject = grades.objects.filter(yeardata__year="2011-2012").values('code__name').annotate(Total=Count('grade')) I've done as I post below, but I wonder if there is a better method. results = list(total_bysubject) for a in passed_bysubjects: for b in results: if a['code__name'] == b['code__name']: b['Passed'] = a['Passed'] b['Percentaje'] = (b['Passed'])*100/b['Total'] Could this be achived by using django methods? Thank you -
Django AttributeError on trying to save instance of Model
I have the following code in my Django model: from __future__ import annotations from typing import Tuple, List, Dict, Callable from datetime import date from django.contrib.auth.models import User from django.db.models import Model, ForeignKey, CASCADE, CharField, TextField, DateField from enum import Enum class RequestState(Enum): OPEN = 'OPEN' ACCEPTED = 'ACC' DECLINED = 'DEC' DELETED = 'DEL' _state_parser: Dict[str, RequestState] = { "OPEN": RequestState.OPEN, "ACC": RequestState.ACCEPTED, "DEC": RequestState.DECLINED, "DEL": RequestState.DELETED } class ActionRequest(Model): issuer = ForeignKey(User, on_delete=CASCADE, null=False, related_name="issuer") receiver = ForeignKey(User, on_delete=CASCADE, null=False, related_name="receiver") _state = CharField(max_length=4, default=RequestState.OPEN.value, null=False) action = TextField(null=False) issue_date = DateField(null=False, default=date.today) last_change_date = DateField(null=False, default=date.today) class InvalidRequestStateException(Exception): def __init__(self, request: ActionRequest): self.request = request super(str(self)) def __str__(self): return f'ActionRequest is in invalid state: {self.request.state}' @property def state(self) -> RequestState: return _state_parser[self._state] @state.setter def state(self, state: RequestState) -> None: self._state = state.value and when i try creating a new model instance and saving it like this: action_request = ActionRequest( issuer=user, receiver=receiver, action=action ) action_request.save() i get the following error: File ~\app\views\action_request_view.py", line 53, in post action_request.save() File "~\venv\lib\site-packages\django\db\models\base.py", line 678, in save if field.is_relation and field.is_cached(self): File "~\venv\lib\site-packages\django\db\models\fields\mixins.py", line 20, in is_cached return self.get_cache_name() in instance._state.fields_cache AttributeError: 'str' object has no attribute 'fields_cache' I am using Django3.0. … -
Can any one share how to create custom user in django
I am trying to create custom user in django, i want to do authentication on custom user, i tried djanog documentation but it could not help me, so please share some website or video on how to create custom user in django like same as default user in django -
Why Django app is slow on server but its work fast on my local device?
When I test my django on my local device for instance send the request to specific endpoint. I receive the response quite faster and quicker as compare to when I deployed the same app on my daddy ESXI cloud and send the same request there even though I used nginx server to serve my app its still slow than the localhost. Even though the resources on server/cloud are much big than my local device. -
Custom model manager that uses model methods in Django
in my model, i have 3 methods. i want to use get_days_remaining method to get all policies expiring in 30 days. Class TravelPolicy(models.Model): .... .... def get_period_of_cover(self): some logic def get_days_left_to_run(self): some logic def get_days_remaining(self): return float(self.get_period_of_cover()) - float(self.get_days_left_to_run()) currently doing TravelPolicy.objects.all() returns over 10,000 policies, while i might policies in order of few 100s expiring in next 30 days. How can i get only the policies expiring in 30 days using get_days_remaining method within my views before passing it to html file ? -
How much HTML i need to learn to knockout DJANGO?
How much HTML,CSS knowledge required to be good at Django? I have been working with python since 2 years.But when i tried to learn Django i am facing issues like i cant get how to map home.html or any advanced html file with views.py .cant get the form logic and {{}}(curly bracket) logic ...I did google lot .But didn't find anything specific.It would be great if someone could help me fix this thing! THANKS IN ADVANCE! -
Django: only one field form translation is not applied (among dozen) but don't understand why?
I use translation in all my forms but I don't know why only one field is not translated whereas all other are correctly translated... I have 3 differents forms that are linked with my model Aveugle The third forms display (AveugleResultForm) it is the simpliest form and only update the unb_rec field in database I can see my french translation appears when I click on F5 but immediately the english label is displayed... forms.py class AveugleResultForm(forms.ModelForm): # surcharge méthode constructeur (__init__) pour avoir accès aux variables de sessions # https://stackoverflow.com/questions/3778148/django-form-validation-including-the-use-of-session-data def __init__(self, request, *args, **kwargs): self.request = request super(AveugleResultForm, self).__init__(*args, **kwargs) self.language = request.session.get('language') YESNO = Thesaurus.options_list(2,self.language) self.fields["unb_rec"] = forms.ChoiceField(label = _("I certify that I have read the treatment received by the patient"), widget=forms.Select, choices=YESNO) class Meta: model = Aveugle fields = ('unb_rec',) models.py class Aveugle(models.Model): unb_ide = models.AutoField(primary_key=True) unb_val = models.IntegerField("I have read ITBM procedure and want to unblind treatment", null=True, blank=True) unb_pro = models.IntegerField("Procedure flow", null=True, blank=True) unb_nom_dem = models.CharField("Surname and firstname of the person requesting unblind", max_length=20, null=True, blank=True) unb_nom_rea = models.CharField("Surname and firstname of the person requesting realizing unblind", max_length=20, null=True, blank=True) unb_dat = models.DateField("Date request", null=True, blank=True) pat = models.CharField("Patient code",max_length=10, unique=True, null=True, blank=True, error_messages={'unique':"Patient\'s … -
How do i save foreign key to database using form
i made a post of two images and each have a comment box. When i comment on each post, the comment do not display until i manually select the image_caption on the image i commented on, which i have linked with a ForeignKey. How do i submit a comment form and automatically save the image_caption name in database. What i tried: text.commented_image = Image.objects.first(), this work by saving the image_caption automatically in database, but the problem is that if i comment on the second post it output display in the first comment. I attached a screen shot of this problem. I explained the issues in the comment section on the screenshot image. class Image(models.Model): imageuploader_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) first_upload_image = models.FileField(upload_to ='picmate/%Y/%m/%d/',null=True, blank=True) second_upload_image = models.FileField(upload_to ='picmate/%Y/%m/%d/',null=True, blank=True) image_caption = models.CharField(max_length=700) tag_someone = models.CharField(max_length=50,blank=True) image_likes = models.ManyToManyField('Profile', default=False, blank=True, related_name='likes') date = models.DateTimeField(auto_now_add=True, null= True) class Comments (models.Model): comment_post = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True, blank=True) commented_image = models.ForeignKey('Image', on_delete=models.CASCADE, related_name='comments',null=True, blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Comment' verbose_name_plural = 'Comments' ordering = ['-date'] def __str__(self): return self.author.__str__() def home(request): all_images = Image.objects.filter(imageuploader_profile=request.user.id) users = User.objects.all() next = request.GET.get('next') if next: return redirect(next) form = CommentForm(request.POST or … -
Why isn't my Django object saved to the database?
I'm writing tests in a Django project and I've got some factories set up to create test content. I now have some trouble in which an email address isn't saved to the database: device = DeviceFactory.create() device.owner.email = 'a@b.c' device.save() print(device.owner.email) # prints out 'a@b.c' print(device.id) # prints out 1 d = Device.objects.get(id=device.id) # get the object from the DB again print(d.owner.email) # prints out jon.avery@ourcompany.com (or any other mock email address the factory creates) Does anybody know why this doesn't save the record to the database? All tips are welcome! -
Django says "no changes detected" in django tutorial when migrating
I'm doing the Django tutorial from their website. When I type python manage.py makemigrations polls, django responds with No changes detected in app 'polls'. Same if I do python manage.py makemigrations polls I added 'polls.apps.PollsConfig' in mysite/settings.py's INSTALLED_APPS (I also tried with only 'polls') My polls/models.py is not empty path('polls/', include('polls.urls')), was added to mysite/urls.py Where could my mistake be ? PS: I read all topic about this on Stackoverflow, tried everything and nothing worked -
django modelformset_factory raises form not valid: id Select a valid choice. That choice is not one of the available choices
i am trying to create a student attendance sheet in django using django modelformset_factory...but when i save the formset it thows me the id is not valid here is my implementation i have two models one StudentAttendance and StudentClass: 1: the StudentAttendance model is responsible for stroring students attendance data here is the example class StudentAttendance(models.Model): classroom_id = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name='student_attendance') attendance_date = models.DateField() student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_attendance') status = models.CharField(max_length=20, choices=ATTENDANCE_CHOICES) comment = models.CharField(max_length=150, blank=True) #signed_by = models.ForeignKey(Teacher, on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.student_id) 2: the StudentClass model is a submodel that maps a student to his respective class class StudentClass(models.Model): """ This is a bridge table to link a student to a class when you add a student to a class we update the selected class capacity """ main_class = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name='class_student') academic_year = models.ForeignKey(AcademicYear, on_delete=models.CASCADE) student_id = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='student_class') @property def is_current_class(self): if self.academic_year.is_current_session: return True return False def __str__(self): return str(self.student_id) So my forms.py implementation is: class StudentsAttendanceForm(forms.ModelForm): class Meta: model = StudentAttendance fields = ('status', 'comment') #exclude = [ #'siqned_by', #] On my views.py: def student_attendance_manager(request): """ this function is responsible for querying the attendance parameters and present the student … -
Why does Django ORM require all() for filter() but not for order_by()?
In Django ORM why does order_by() does not require all() while filter() do? Example, Mymodel.objects.order_by('param') Mymodel.objects.all.filter('param') -
Django admin page: Inline selection for ForeignKey
I have two models : class Book(models.Model): name = models.CharField(null=True, max_length=50) author = models.ForeignKey(Author, null=True, blank=True, on_delete=models.DO_NOTHING) class Author(models.Model): name = models.CharField(null=True, max_length=50) I would like to add new Books in Admin pages, and then linked them in Author admin page. So the flow should be: Create few new Book objects Create new Author object and add to it multiple Book objects that has been already created I try it like this : class BookInLine(admin.TabularInline): model = Book can_delete = False min_num = 0 @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): inlines = [BookInLine] But this add me options to ADD NEW book to a Author... not to link already existing ones to it. How to handle this? -
How can I test overriden function in Django admin?
I have overriden function in admin module @admin.register(Donation) class DonationAdmin(admin.ModelAdmin): def log_change(self, request, object, message): log_obj = super().log_change(request, object, message) name_map = {name: value.label for name, value in DonationForm.base_fields.items()} extended_log = '' if message: changed_fields = message[0].get('changed').get('fields') extended_log = {key: value for key, value in request.POST.items() if key in changed_fields} extended_log = self.get_humanize_values(extended_log) extended_log = dict( zip( map(lambda x: name_map[x], extended_log.keys()), extended_log.values() ) ) return AdditionalLogEntry.objects.create( entry=log_obj, extended_log=extended_log) How can I test it? class DonationAdminTestCase(TestCase): def setUp(self) -> None: self.user = UserFactory() self.donation = DonationFactory() self.donation_admin = DonationAdmin(model=Donation, admin_site=AdminSite()) def test_log_change(self) -> None: self.user.is_staff = True self.user.save() self.client.force_login(self.user) # ??? -
How to get Form logic on a onepage django website?
I've tried a few ways to get my contact form working on my one-page website. I understand that you cannot link two views to one single template, but there must be a way to do this. Here's the last state of my code, where i just managed to render the form on my index.html template. I need to figure out how to get my form logic to work, as i want to send an email at the form submit. To be honest, reading the django doc about how to handle class-based Forms got me a little bit confused concerning the logic handling (link) When i submit this form i simply get the forced redirection to my "merci.html" template (thank you page that only contains a Thanks! paragraph). views.py : from django.shortcuts import render, redirect from django.views.generic.base import TemplateView from .models import * from projects.models import ProjectPost from blog.models import Post from .forms import ContactForm from django.http import HttpResponse from django.views.generic.edit import FormView from django.core.mail import send_mail from django.conf import settings class IndexTemplateView(TemplateView): template_name = 'index.html' # override get context data method def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # first, call super get context data context['myresume'] = MyResume.objects.first() context['aboutme'] = AboutMe.objects.first() … -
Use column field inside Django filter method
I have a field in the database which comes as a string (x). I need to convert it in a format to be used inside filter() method. How is this possible? Also when field is none i want to use something to return True. Like 1=1 to get rid of the error x = 'data_type=1' DeviceData.objects.filter(x) -
djang orm filter with self date column
i have a question. my model is like below. depart_date = models.DateField(null=True, blank=True, verbose_name=_("Depart Date")) days = models.IntegerField(default=0, null=True, blank=True, verbose_name=_("Day")) and i want filter my data depart_date + days >= today is it possible using orm query? it is so simple when i use raw query below ( when i using oracle ) SELECT * FROM MY_TABLE = WHERE depart_date + days >= > TO_DATE('2020-01-01', 'YYYY-MM-DD') than you for your help -
How to include a manytomany field in a postgres full text search in django
I am trying to do a full text search in postgres using these models class CustomUser(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) password2 = models.CharField(max_length=128) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) active = models.BooleanField(default=True) # Able to login practitioner = models.BooleanField(default=False) # has access to a clinc admin = models.BooleanField(default=False) # superuser staff = models.BooleanField(default=False) # staff timestamp = models.DateTimeField(auto_now_add=True) class Modalities(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Profile(models.Model): user = models.OneToOneField(User, related_name='prof_user', on_delete=models.CASCADE) bio = models.TextField(max_length=5000) mods = models.ManyToManyField(Modalities) phone = PhoneNumberField() clinics = models.ManyToManyField(Clinic) personnummer = models.CharField(max_length=12) street = models.CharField(max_length=50) city = models.CharField(max_length=50) consent = models.BooleanField() class Clinic(models.Model): practitioner = models.OneToOneField(User, related_name='prac_user', on_delete=models.CASCADE) lat = models.FloatField(null=True, blank=True) lng = models.FloatField(null=True, blank=True) name = models.CharField(max_length=128, ) phone = PhoneNumberField() description = models.TextField(max_length=5000) street = models.CharField(max_length=128, ) city = models.CharField(max_length=128, )``` So far I am able return search results with def search(request): search_vector = SearchVector('practitioner__first_name', 'name', 'description', 'street', 'city') results = Clinic.objects.annotate(search=search_vector).filter( search='Göteborg').values_list('name', 'street', 'city', 'lat', 'lng', 'pk', flat=False) def list_of_results(results): key_list = ['name', 'street', 'city', 'lat', 'lng', 'clinic_id'] r_list = [] object = [] for p in results: r_list.append([p[0], p[1], p[2], p[3], p[4], p[5]]) for array in r_list: object.append(dict(zip(key_list, array))) return object search_result = list_of_results(results) I would also like …