Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update history record in Django?
I got question about Django history. When I am in admin and change something in database, it will make an record in history of that object, that I made it or I update some record of that specific object. When I paste the data to database through some form (when the user is log in), it will not make an record in history. I also tried to update value and it works fine but it will not make and record in history, that this and this was changed... Can someone help me how to do it please? What should I add to this part of code? t = Pool.objects.get(pk=Pools_id) t.Status = "New" t.save() return HttpResponseRedirect('#') -
Django - change datafield on database
i am creating a real estate website in Django. I want users to insert/delete images for their properties. It´s all working as expected, except the delete images. In my views.py i have the code: listing = Listing.objects.get(id=1511) if listing: listing.photo_5 = None listing.save(['photo_5']) return True photo_5 is an Imagefield and i want to change the value of that field in database to None. I am saving the image to media folder and save the url in database. photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) Then when the user clicks in trash can icon, i have an ajax request (working and receives response from view) to delete the image from database. But there is the problem, i am not able to update the url in database or to delete. I already tried with update Listing.objects.all().filter(id = 1511).update(photo_5 = None) It seems that i can not change the value of photo_5. Why is not changing? -
is it bad to have en directory in locale? is there any use for it?
the main language is English for my website, some tutorials suggest to use django-admin makemessages -a and others suggest to use django-admin makemessages -l -de but when i use -a it make the en-us directory as shown below and it seems pretty much useless or is it? it there any merit for having a en-us directory for a website with English as it's main Lang? or should i just delete it? . ├── db.sqlite3 ├── some_industry ├── locale │ ├── en_us │ │ └── LC_MESSAGES │ │ └── django.po │ └── de │ └── LC_MESSAGES │ └── django.po ├── machine_request │ ├── __init__.py │ ├── admin.py │ ├── locale │ │ ├── en_us │ │ │ └── LC_MESSAGES │ │ │ └── django.po │ │ └── de │ │ └── LC_MESSAGES │ │ └── django.po │ ├── migrations │ ├── static │ │ └── machine_request │ ├── templates │ ├── urls.py ├── manage.py └── users ├── __init__.py ├── admin.py ├── locale │ ├── en_us │ └── de └── views.py -
why is form.is_valid returns false?with this error?
what is this error???? <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li></ul> -
Removing Brackets from itertools combination list results
I have this code import itertools import random def gen_reset_key(): key = random.randint(100, 199) return key key_combinations = list(itertools.combinations(str(gen_reset_key()), 2)) key_one = key_combinations[0] key_two = key_combinations[1] key_three = key_combinations[2] print("Key one is: {}".format(key_one)) print("Key two is: {}".format(key_two)) print("Key three is: {}".format(key_three)) The output is: Key one is: ('1', '9') Key two is: ('1', '9') Key three is: ('9', '9') I want to remove the brackets and speech marks from the output. How can I achieve that? so that my output would be: Key one is 19 Key two is 19 Key three is 99 -
Django admin site customization
\models class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True) School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True) Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True) Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True) Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True) Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE,null=True) Remarks = models.TextField(max_length=500,null=True) def __str__(self): suser = '{0.Student_Users} {0.Education_Levels}' return suser.format(self) what i want to search class StudentsEnrolledSubject(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True) Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records} {0.Subject_Section_Teacher}' return suser.format(self) Can i search here if i select what ever i want in section, my search will appear below? do you guys have an idea or better solution? -
UserSocialAuth model for shopify not able to create while performing authentication using python social_core shopify library
My aim is to get access token from shopify so that i can create webhook.I am using https://github.com/python-social-auth/social-core library to authenticate. Though i am able to navigate to shopify store admin section but i am not able to get "access token" from shopify.Generally UserSocialauth is the object which is having model attributes "extra_data" which gives access token but when i am going to shell of Django to list UserSocialAuth.objects.all().There is no model created for shopify app.Any Help https://github.com/python-social-auth/social-core/blob/master/social_core/backends/shopify.py -
Foreign Key column with keys from different models
Lets say I have 4 models, A, B, C, X A contains A1,A2,...An (similarly B and C) I have an object in X, say X1 which is related to an object from category either A, B or C. I have a column in X's model as category. How can I relate it to different models of A, B and C? If this cannot be done with a single column, what is the best way to implement this? Sorry for asking a noob question. Thanks in advance :) -
Password reset email not sending
I have a dynamic email configuration so that i customize the PasswordResetView like this to use my dynamic email .But this is not working properly . ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it [17/Oct/2019 14:49:42] "POST /password-reset/ HTTP/1.1" 500 148748 I think i need to pass this backend like this email = EmailMessage(.....,connection=backend) but i got stuck here.how can i do this here ? Any idea or solution for this? Is this approach is correct or not ? Any help would be great. form_class = EmailValidationOnForgotPassword but this form_class is working fine but email is not sending urls.py path('password-reset/', CustomPasswordResetView.as_view(),name='password_reset'), views.py class CustomPasswordResetView(PasswordContextMixin, FormView): config = EmailConfig.objects.order_by('-date').first() backend = EmailBackend(host=config.email_host, port=config.email_port, username=config.email_host_user, password=config.email_host_password, use_tls=config.email_use_tls) email_template_name = 'app/password_reset_email.html' extra_email_context = None form_class = EmailValidationOnForgotPassword from_email = config.email_host_user html_email_template_name = None subject_template_name = 'app/password_reset.html' success_url = reverse_lazy('password_reset_done') template_name = 'app/password_reset.html' title = 'Password Reset' token_generator = default_token_generator @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def form_valid(self, form): opts = { 'use_https': self.request.is_secure(), 'token_generator': self.token_generator, 'from_email': self.from_email, 'email_template_name': self.email_template_name, 'subject_template_name': self.subject_template_name, 'request': self.request, 'html_email_template_name': self.html_email_template_name, 'extra_email_context': self.extra_email_context, } form.save(**opts) return super().form_valid(form) INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token' -
Return file as a download in Django Python
I have made a site using Django and I have made a function that returns an autogenerated pdf from database data. To make the PDF I use pyFPDF. pdfreport = FPDF() #Code for the PDF here pdfreport.output(name='mypdf.pdf') With this code everything works well, the PDF is correctly generated. But in order to return the file as an HTTP Response, I save the file with dest='S' and make the response. pdf = pdfreport.output(dest='S') response = = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return(response) Using this, the response is correct and I got the file to save, the browser load the file as a pdf, but the pdf is blank. And I don't know why this happen. I have tried saving the file, open the file with open() and attach its content, but I still got the same result, a blank pdf. pdfreport.output(name=pdfname) pdf = open(pdfname, 'r') response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"' return(response) Anyone that could help me? -
Deploying django project in cloudfoundry
I am new to django. I have a django project with multiple application. My project name is : DCMS_API. Procfile web: gunicorn DCMS_API.wsgi:application My manifest.yml: --- applications: - name: facility path: ./facility - name: connect_DB path: ./connect_DB buildpacks: - https://github.com/cloudfoundry/apt-buildpack.git - https://github.com/cloudfoundry/python-buildpack.git env: ACCEPT_EULA: Y i am trying to host it in cloudfoundry. i am uploading using following commands: cf login -a ****.com -u @.com -o DJANGO Cf target -s Development cf push But in cloudfoundry it is hosting as multiple applications different URL. facility.*****.com & connect_DB.*****.com How do we add a single project? like *****.com/facility & *****.com/connect_DB Not sure how to put it as. giving a same domain name/ URL, just adding the application name at the end rather than hosting 2 separate application or hosting the project. -
Single Sign On with Django and Salesforce
I'm trying to implement SSO between my Django app (the identity provider) and Salesforce (the service provider). My app is supposed to send SAML assertions to Salesforce. I have generated a self-signed certificate with which I'm build the SAML assertion (the xml tree). I configured my Salesforce SSO settings and uploaded the public certificate I previously generated on my local machine. Now when I try to validate the xml tree (or the base64 encoded version of it), I get this error in their UI which I can't pass because the error is very obscure and doesn't tell me much about the root of the problem. My guess is that Salesforce can't read the certificate part of the XML I'm sending, but I don't know why. Has anyone seen this before? -
Switched from Django Server to Apacher Server and RUINED my layout
The layout(using bootstrap) was perfect when I deployed my blog using the Django server as is. But, when I turned of the Django server and switched it to the Apache2 server, the format got completely ruined. I am not sure how the format was affected by me switching to an Apache2 server. Everything else remains the same except I had to make sure the I was correctly pointing to the static files right? Messed up version The Correct version2 I followed an amazing youtube tutorial to a tee, but still nothing. Here is the Apache configuration I used, as per the youtube video(Of course, I made sure to change the YOURUSER/YOURPROJECT to the correct location on my server) Alias /static /home/YOURUSER/YOURPROJECT/static <Directory /home/YOURUSER/YOURPROJECT/static> Require all granted </Directory> Alias /media /home/YOURUSER/YOURPROJECT/media <Directory /home/YOURUSER/YOURPROJECT/media> Require all granted </Directory> <Directory /home/YOURUSER/YOURPROJECT/YOURPROJECT> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/YOURUSER/YOURPROJECT/YOURPROJECT/wsgi.py WSGIDaemonProcess django_app python-path=/home/YOURUSER/YOURPROJECT python-home=/home/YOURUSER/YOURPROJECT/venv WSGIProcessGroup django_app -
Django coding - Why is it necessary to pass two separate arguments?
I am looking to add email account verification in Django and found a nice open source code that I can adopt. But there is one line which I'm not familiar with. Why does the function "password_reset_confirm" need to return two **kwargs in separate brackets and how each of them is used in the class "PasswordResetConfirm"? This question might be related to Python rather than Django. But anyway, thank you for your help! urls.py url(r"^password/reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za- z]{1,13}-[0-9A-Za-z]{1,20})/$",views.password_reset_confirm, name="reset- password-confirm",) views.py from django.contrib.auth import views as django_views class PasswordResetConfirm(django_views.PasswordResetConfirmView): template_name = "account/password_reset_from_key.html" success_url = reverse_lazy("account:reset-password-complete") token = None uidb64 = None def form_valid(self, form): response = super(PasswordResetConfirm, self).form_valid(form) account_events.customer_password_reset_event(user=self.user) return response def password_reset_confirm(request, uidb64=None, token=None): kwargs = { "template_name": "account/password_reset_from_key.html", "success_url": reverse_lazy("account:reset-password-complete"), "token": token, "uidb64": uidb64, } return PasswordResetConfirm.as_view(**kwargs)(request, **kwargs) -
Docker-compose service exited with code 0
I'm quite new to Docker. I'm trying to run Django on Docker. Following is my docker-compose file. version: '2' services: django: build: context: . dockerfile: ./deploy/dev/Dockerfile tty: true ports: - "8000:8000" volumes: - ./app:/src/app depends_on: - "workflow_db" - "rabbitmq" env_file: - ./deploy/dev/envvar.env workflow_db: image: postgres:9.6 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django rabbitmq: image: "rabbitmq:3-management" hostname: "rabbitmq" environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: "rabbitmq" RABBITMQ_DEFAULT_PASS: "rabbitmq" RABBITMQ_DEFAULT_VHOST: "/" ports: - "15672:15672" - "5672:5672" volumes: postgres_data: DockerFile FROM python:3.7-alpine RUN apk update && apk add --no-cache gcc libffi-dev g++ python-dev build-base linux-headers postgresql-dev postgresql postgresql-contrib pcre-dev bash alpine-sdk \ && pip install wheel #Copy over application files COPY ./app /src/app #Copy over, and grant executable permission to the startup script COPY ./deploy/dev/entrypoint.sh / RUN chmod +x /entrypoint.sh WORKDIR /src/app #Install requirements pre-startup to reduce entrypoint time RUN pip install -r requirements.txt ENTRYPOINT [ "/entrypoint.sh" ] And finally my entrypoint.sh ! /bin/bash cd /src/app || exit echo "PIP INSTALLATION" && pip install -r requirements.txt echo "UPGRADE" && python manage.py migrate # echo "uwsgi" && uwsgi "uwsgi.ini" I do django-compose up, it builds the image, but django_1 exited with code 0. However, if I uncomment the last line of entrypoint.sh, it runs … -
ReverseManyToOne create object from children through django form
Using: Python 3.7.3 django 2.2.5 mysql 5.7.27 I have the following models: class Item(models.Model): ... class Comments(models.Model): Item = models.ForeignKey('Item', default=None, null=True, on_delete=models.SET_DEFAULT) Comment = models.TextField(max_length=512, default="", blank=True) I would like to create a Comments object, when creating the Item through a django form. I tried to do: class ItemInsertForm(forms.ModelForm): ... Comments = forms.CharField(required=False, widget=forms.Textarea(attrs={'placeholder':"Use comments to describe item details \ or issues that other users should know", 'rows':5, 'cols':50, } ) ) def clean_Comments(self, *args, **kwargs): _comment = self.cleaned_data.get('Comments') _comments = Item.comments_set.create(Comment=_comment) return _comments but I get the following error: 'ReverseManyToOneDescriptor' object has no attribute 'create' Both tables are empty, so no Item and no Comments currently exist. I guess that's why there is no 'create' method available. Is there a way I could achieve what I want? Or is there another way to manage the comments for the Item object? I created another table to be able to associate multiple comments to the same item and differentiate between them. A character field in the Item class would concatenate all comments in a single string. -
"Failed to establish a new connection" when trying to access Elasticsearch Cloud with elasticsearch-dsl Python package
I'm experimenting with Elasticsearch and indexing some Django data using the elasticsearch-dsl Python package. I have created a relatively basic test, search.py, but receive a connection error when I try to index any data. from elasticsearch_dsl.connections import connections from elasticsearch_dsl import Document, Text from elasticsearch.helpers import bulk from elasticsearch import Elasticsearch from . import models connections.create_connection(hosts=['ELASTICSEARCH_ENDPOINT_URL'], http_auth='USERNAME:PASSWORD') class MyIndex(Document): title = Text() description = Text() class Index: name = 'my-index' def bulk_indexing(): MyIndex.init() es = Elasticsearch() bulk(client=es, actions=(a.indexing() for a in models.MyModel.objects.all().iterator())) When I run bulk_indexing() I get the following error: elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x1282266d8>: Failed to establish a new connection: [Errno 61] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x1282266d8>: Failed to establish a new connection: [Errno 61] Connection refused) I suspect the syntax is wrong or I am missing some credentials when creating a connection, but I cannot find any further information. I am using Elasticsearch v7.4.0 deployed using Elastic Cloud. I can connect when I access the URL via my browser. -
I want to know a good way to implement pagination within a modal
I would like to apply pagination within the modal so that only 20 posts per page are displayed. How can I implement a pagination view? Can you recommend a good example or resource? Can't I ask this question? I'll erase this question if it matters -
How can I access POST data in get_context_data method in Django?
I want to send back as context data, what i got from request.POST in form_valid method. How Can i access that POSTdata in get_context_data() method? -
new read_only + default behaviour of drf 3.8 gives error
here is an example of the error : model: from django.db import models class Hero(models.Model): alias = models.(max_length=60) character = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name serializer: class HeroSerializer(serializers.ModelSerializer): character = HyperlinkedRelatedField(read_only=True, default=<some user object>) class Meta: model = Hero fields = ('character', 'alias') Viewset: class HeroViewSet(NestedViewSetMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.ReadOnlyModelViewSet): queryset = Hero.objects.all() serializer_class = HeroSerializer Test: def test_created_successfully(self): alias = 'blab blah' response = self.client.post(self.url, {'name': name}) self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) now this test used to pass is drf 3.7.7 as i upgraded to drf 3.8.2 this error started to occur django.db.utils.IntegrityError: null value in column "character_id" violates not-null constraint DETAIL: Failing row contains (blah_blah, null). they said that now default + read_only fields are excluded from writable fields so you have to explicitly save those fields by writing perform_create or overriding create , update and save functions of serializer so i wrote this in the viewset def perform_create(self, serializer): serializer.save(character=<some user object>) for reference this perfrom_create is called inside create method of mixins.CreateModelMixin def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) so it worked here but now if the same serializer is changed to(character field is changed to name and … -
View taking too much time to process images with Heroku and S3
I am running a Django application in Heroku which handles multiple image uploads from the user and storage them to Amazon S3. The problem is that the execution of this proccess requires usually more than 30s (the time execution limit of Heroku). I tested it and the line which takes longer time is the one saving the image file in the ImageField. This is done like that because the image has to be cropped and processed by ProcessImageFile(). However this function is not taking long time, but the save method itself, maybe because it storages the files in S3 one by one while saving them. Here is the view (omitted irrelevant lines): @login_required def image_create(request): if request.method == 'POST': images = request.FILES.getlist("files") crop_points = json.loads( request.POST.get('crop_points')) #Validation of inputs in the form: images and other fields if len(images) < 3 : return JsonResponse({'val_result': 'min_error'}) if len(images) > 12: return JsonResponse({'val_result': 'max_error'}) #We Create the gallery, iterate over the images provided by the form, validate, insert custom fields and save them in bulk associating it to the gallery. with transaction.atomic(): new_items = [] gallery = Gallery.objects.create( user=request.user ) for i, img_file in enumerate(images): new_item = Image() new_item.user = request.user #-----THIS IS … -
django "Models aren't loaded yet" while running migrate or makemigrations
I'm trying to run python manage.py migrate/makemirations on my test server (using sqlite) but I get 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.' I've seen other questions and answers on this but the solutions do not work on my issue. I've tried looking at the traceback but it doesn't have much information pointing to where the error is coming from on my app. Here is the traceback: Traceback (most recent call last): File "manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/home/isppme/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/isppme/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/isppme/lib/python3.6/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/isppme/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/isppme/lib/python3.6/site-packages/django/core/checks/model_checks.py", line 15, in check_all_models models = apps.get_models() File "/home/isppme/lib/python3.6/site-packages/django/apps/registry.py", line 178, in get_models self.check_models_ready() File "/home/isppme/lib/python3.6/site-packages/django/apps/registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Python - DJango -psutil: monitoring remote machines and application status
I have some Python scripts that check memory usage and resources in several remote machines in our network. The script also checks the status of some vital services that serve our web application. At the moment we are using a manual process meaning that you run the script and read the results. I want to build a live monitor that continuously shows the state of the system. I have never done something of this kind. My idea would be to run the script on a timer to be executed at certain intervals and then pass the result to a graphical interface build using Django. My question is if this is the right approach. Is there a better way to use python for this kind of operations. Thank you for your suggestions and help. -
How to complement the block of parent template?
I have first.html: {% block title %} hi there {% endblock %} {% block content %} blah-blah {% endblock %} {% block footer %} bye {% endblock %} and second.html. How can I incude all first.html page to second.html and complement content block like this: hi there blah-blah this text is from second.html bye I've tryed {% extends "first.html" %} this text is from second.html (just nothing added) and {% extends "first.html" %} {% block content %} this text is from second.html {% endblock %} (block content is overrided). -
How to list blog posts of a particular user in Django REST Api
How to list blog posts of a particular user. using ListAPIView, all blog posts are listed. How to list blog posts of a particular user? #views.py class BlogList(generics.ListAPIView): queryset = models.Blog.objects.all() serializer_class = serializers.BlogSerializer #serializers.py class BlogSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'user_id', 'title', 'content', 'created_at',) model = models.Blog #urls.py path('', views.BlogList.as_view()),