Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I initialise group names in Django every time the program runs?
I have this code and I want it to just create the groups every time the program runs so that if the database is deleted it will still be a sufficient program itself and someone won't have to create groups again, do you know an easy way to do this? system_administrator = Group.objects.get_or_create(name='system_administrator') manager = Group.objects.get_or_create(name='manager') travel_advisor = Group.objects.get_or_create(name='travel_advisor') -
django configure multiple upload buttons to transfer file to s3
I want to upload multiple files from multiple upload buttons to s3 from django.I know basic concept for uploading files to s3 for single upload buttons..how can we apply same concept if we have more than one upload buttons at a same time?(I used post method to send the files to s3) -
did an upgrade on KIWI I am using DOCKER container to run with now my manage.py fails for django asserts
I did an upgrade per the documentation at https://kiwitcms.readthedocs.io/en/latest/installing_docker.html Upgrading Steps to Reproduce cd Kiwi/ git pull # to refresh docker-compose.yml docker-compose down make docker-image if you build from source or docker pull kiwitcms/kiwi # to fetch latest version from Docker Hub docker pull centos/mariadb # to fetch the latest version for MariaDB docker-compose up -d docker exec -it kiwi_web /Kiwi/manage.py migrate Actual results When I run docker exec -it kiwi_web /Kiwi/manage.py migrate I get an assert of: sudo docker exec -it kiwi_web /Kiwi/manage.py migrate Traceback (most recent call last): File "/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "/venv/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/venv/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 233, in get_new_connection return Database.connect(**conn_params) File "/venv/lib/python3.6/site-packages/MySQLdb/init.py", line 84, in Connect return Connection(*args, **kwargs) File "/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 179, in init super(Connection, self).init(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2005, "Unknown MySQL server host 'db' (-2)") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Kiwi/manage.py", line 12, in execute_from_command_line(sys.argv) File "/venv/lib/python3.6/site-packages/django/core/management/init.py", line 401, in execute_from_command_line utility.execute() File "/venv/lib/python3.6/site-packages/django/core/management/init.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/venv/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv … -
Making Django migrations backwards compatible with SQL-Server
We have a Django application that previously only used Postgres as its DB backend. Now a client would like to use the application with MS SQL-Server. Previously, a developer added a unique constraint on a text field. It's a small table, so the index doesn't overwhelm things, and of course Postgres thinks this is fine, so testing didn't detect any problems. We have an existing release (several releases back, in fact), that includes a migration to add that constraint. Let's say this was called app/migrations/0002_add_unique.py Now we get the request for SQL-Server compatibility. We added a site configuration option to let an installer specify the DB engine as well as the connect string, so you can pick MS SQL-Server rather than Postgres, but of course migrations breaks when it tries to create the database in SQL-Server. Migrations has to run in the correct order, so SQL-Server blows up trying to add the illegal constraint before it gets to the migration that either removes the constraint or changes the text field to a long varchar. We solved this in the current release candidate by modifying the old 0002_add_unique.py migration so that it doesn't add the uniqueness constraint. There is also a … -
windows10 workon "env_name" no response
I'm using python 3.8.1 to build a django project using virtualenv I create my virtualenv by "mkvirtualenv my_django_environment" after that i use "workon" command and i can see this env really created. and when i tried to activate it , it just shows nothing, just like below: C:\Users\User>workon Pass a name to activate one of the following virtualenvs: my_django_environment C:\Users\User>workon my_django_environment C:\Users\User>python it just didn't happen anything! but i try this on my laptop (windows 10) it work well. i have no idea how to solve this. -
Django - Cannot test request as authenticated user with django-allauth
I have a new django project (2.2), a custom user model and django-allauth to manage user registration (not via social, just with the email confirmation) and I'm trying to test some protected views. In the setUp method of the test I create a new user and create a new EmailAddress (from allauth.account.models) with verified and primary set to True. Next I try to login with: self.client.login(username=username, password=password) and I get True so everything is working so far and the user is logged. Now if I try to get any views that requires login I always get a 301 redirect to the login page! I looked around but didn't find a solution to my problem so far. Let me show you some code: user creation in setUp username = 'test@test.com' password = 'testtesttest' new_user = User.objects.create_user( username=username, email=username, password=password, ) new_user.save() new_user.is_active = True new_user.save() new_email_address = EmailAddress( user_id=new_user.id, email=username, verified=True, primary=True, ) new_email_address.save() login and test logged in logged_in = self.client.login(email=username, password=password) self.assertTrue(logged_in) # and this works as expected Now if I try to request a view that requires login: response = self.client.get("/protected") I get <HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/protected/"> What am I doin't wrong? Thanks in advance for the … -
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')