Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django LDAPS TLS started failing with error SERVER_DOWN
Today we had the pleasure of LDAPS failing in a Django application. Our Pip requirements includes: python-ldap==3.3.1 django-auth-ldap==3.0.0 Our Django settings file includes: AUTH_LDAP_SERVER_URI = "ldaps://ldaps.server.net.au:636" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0, ldap.OPT_NETWORK_TIMEOUT: 5.0, ldap.OPT_TIMEOUT: 5.0, } The vague error we're seeing is: Caught LDAPError while authenticating sighmon: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 115, 'ctrls': [], 'info': '(unknown error code)'},) It had been working nicely for ~2 years prior to today. We tried pinning django-auth-ldap to various older versions, but all failed in the same way. -
AttributeError: 'datetime.datetime' object has no attribute 'save' - While saving time
I am building a BlogApp and I am trying to save time when the post was liked. Than I create a field of like_time so i can save the time while liking the post BUT When I save the time of like post then it is showing AttributeError: 'datetime.datetime' object has no attribute 'save' models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date_post_added = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField(User,related_name='like ',blank=True) like_time = models.DateTimeField(auto_now=True) views.py def like_post(request,blogpost_id): blogpost = get_object_or_404(BlogPost, pk=blogpost_id) if request.GET.get('submit') == 'like_post': blogpost.like.add(request.user) blogpost.like_time.save() else: redirect('home') Like is successfuly adding BUT time is not saving and showing error. I also tried by adding :- from django.utils import timezone blogpost .like_time.save(timezone.now()) BUT It showed me same error. Than i tried :- import datetime timestamp = datetime.datetime.now() blogpost.like_time.save(timestamp) It also showed same error. Any help would be much Appreciated. Thank You in Advance. -
uploded image not saved in media folder
settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [BASE_DIR / "static"] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, "media/") MEDIA_URL = '../media/images/' urls.py if settings.DEBUG: # Use static() to add url mapping to serve static files during development (only) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py profile_image = models.ImageField(upload_to="../media/images") file path: -main_project /app #django app /media/images #media folder inside image folder /main #django main app /static/css #static folder for js,css,images,fonts /templates #html templates I have also tried other way but still, my image is not uploaded in media folder -
Printing pdf on network printer using python
I am currently working on application that generates pdf file and i am trying to send it to network printer. I am using reportlab to create pdf and docker and docker-compose to run app. I can't send the pdf file to the printer. Does anyone knows how to print pdf on network printer? -
Dataframe.ixmax on timezone-signed datetime data
I extracted some datetime data from my django app: data = list(MyModel.object.values_list("date1", "date2")) # >>> [ ( None, datetime.datetime(2020, 4, 9, 15, 43, 59, 433515, tzinfo=<UTC>) ), ( datetime.datetime(2020, 4, 9, 15, 44, 27, 328075, tzinfo=<UTC>), datetime.datetime(2020, 4, 9, 15, 44, 27, 328075, tzinfo=<UTC>), ) ] I input this in a dataframe: df = pd.DataFrame(data, columns=["date1", "date2"]) and I want to know for each row which date column is the highest so I use the idxmax function on axis=1: result = df.idxmax(axis=1) However I get this error: TypeError: reduction operation 'argmax' not allowed for this dtype My column types are datetimes so they argmax should work on them. df.dtypes # >>> # date1 datetime64[ns, UTC] # date2 datetime64[ns, UTC] # dtype: object Am I missing something? -
How secure image url in Django Rest Framework? [closed]
I'm building an API that stores some pictures from different users. I want to build a system, where only the user(who add a picture) and admin can view the picture. Any ideas on how to make it? As a result, I want to get something like this: https://office.kentonfinance.com/api/clients/60f984637c3cc260ea471526/documents/uccppuzhganfp0e2m94nrgvnv.png https://office.kentonfinance.com/api/clients/ code for user_id /documents/ picture name P.S. Searching in Google and in StackOverflow didn't give the result. -
Efficiently creating object from user inputted data in django
I am creating a web app where users will enter some details regarding a patient, an algorithm will then process these and generate some treatment recommendations. My question is how to both best design my models and then how best for the algorithm to access the user inputted data. These are my current models for capturing the user inputted data. The Diagnosis, Problem, CurrentMed and PastMed models all have flexible number of entries (the user can dynamically add rows to the entry form) which is why I do not have a single larger Patient model: models.py class Patient(TimeStampedModel): # get a unique id for each patient patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) age = models.IntegerField("Age", default=0) class Sex(models.TextChoices): MALE = "male", "Male" FEMALE = "female", "Female" UNSPECIFIED = "unspecified", "Unspecified" sex = models.CharField( "Sex", max_length=20, choices=Sex.choices, default=Sex.UNSPECIFIED) creator = models.ForeignKey( settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) class Diagnosis(TimeStampedModel): DIAG_CHOICES = [ (‘cancer’, ‘Cancer’), (‘influenza’, ‘Influenza’), ('unspecified', 'Unspecified'),] diag_name = models.CharField( "diag", max_length=200, choices=DIAG_CHOICES, default="unspecified") patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Problem(TimeStampedModel): PROB_CHOICES = [ (‘pain’, ‘Pain’), (‘wheeze’, ‘Wheeze’), ('unspecified', 'Unspecified'),] prob_name = models.CharField( "prob", max_length=200, choices=PROB_CHOICES, default="unspecified") patient = models.ForeignKey(Patient, on_delete=models.CASCADE) class Med(TimeStampedModel): MED_CHOICES = [ (‘Antibiotics’, ( (‘penicillin’, … -
Can not call Django view function via ajax function
viwes.py def post_upload(request, resolution, format, size): print(resolution) print(format) print(size) return render(request, 'upload .html') urls.py path(r'^post_upload/$', views.post_upload, name='post_upload') give.js: $(".btn").bind('click', function(){ console.log('download button clicked'); var resolution = $(this).closest("tr").find(".resolution").text(); var format = $(this).closest("tr").find(".format").text(); var size = $(this).closest("tr").find(".size").text(); var csrf_token = $("input[name='csrfmiddlewaretoken']").val(); console.log(resolution,format,size, csrf_token); $.ajaxSetup({ headers: { 'X-CSRFToken': csrf_token } }); $.ajax({ type: 'POST', url : "{% url 'post_upload' %}", data: { resolution: resolution, format: format, size: size, }, dataType:"html", success: function(data, status, xhr){ //do something with your data } }); return false; }); html file: {% csrf_token %} <button type="button" name="url" value="{{ request.GET.url }}" type="submit" id="download" class="btn btn-success" >Download</button> </form> <script src="{% static 'js/popper.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js'%} "></script> <script src="{% static 'js/plugin.js' %}"></script> <!-- sidebar --> <script src="{% static 'js/jquery.mCustomScrollbar.concat.min.js' %}"></script> <script src="{% static 'js/custom.js' %}"></script> <script src="https:cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script> <script src="{% static 'js/give.js' %}"></script> -
Django: fetching data from database. "WaitForSingleObject()" is taking 96% of execution time. Any Solution?
I'm using Django and trying to fetch data from PostgreSQL database. The table contains 2000 records and the request is taking 4-15 seconds. Upon profiling I saw that "WaitForSingleObject()" is taking most of the time. any solutions? -
VS Code and Django: Exception has occurred: ImportError
I'd like to automate some daily thinks on my job and struggle with this problem at the moment. System Versions: Python 3.9.6// VS Code: 1.59.1// Django: 1.6.0 I tried to create my first site and followed this tutorial: https://code.visualstudio.com/docs/python/tutorial-django I can run the server in the terminal with "python manage.py runserver". But when I try to run with debugger launch profile (the green arrow) the ImportError Msg occur. "Exception has occurred: ImportError Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" The manage.py consists of a def main() method with a try/except block: def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'web_projct.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) I don't know why but I couln't find the "execute_from_command_line".py in die django.core.managment directory. I set a lot of system variable for the pythonpath so I would not think that this is the erroer cause. Do I have explained my problem understandable? Is there somebody with … -
Cannot insert the value NULL into column 'id', table 'XXX'; column does not allow nulls
I have the below model: class Loan(models.Model): id = models.BigAutoField(primary_key=True) date = models.DateField(default=timezone.now) description = models.TextField(max_length=255) When I try to save date and description I get the above error below is my admin.py file: @admin.register(Loan) class LoanAdmin(admin.ModelAdmin): pass How can I solve this? -
Django. Foreign key
I have 2 tables: Side and AdditionalCost now AdditionalCost has the following foreign key field: side = models.ForeignKey(Side, on_delete=models.CASCADE, related_name='costs') I want to have another foreign key field in AdditionalCosts: number_of_additional_installations = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="number_of_additional_installations") The Side model has the following field: number_of_additional_installations = models.IntegerField(null=True, blank=True, db_column='number_of_additional_installations', verbose_name='Количество доп монтажей') But I get the following error: ERRORS: <class 'kinetics.apps.address_program.admin.AdditionalCostInline'>: (admin.E202) 'address_program.AdditionalCost' has more than one ForeignKey to 'address_program.Side'. address_program.AdditionalCost.number_of_additional_installations: (fields.E302) Reverse accessor for 'AdditionalCost.number_of_additional_installations' clashes with field name 'Side.number_of_additional_installations'. HINT: Rename field 'Side.number_of_additional_installations', or add/change a related_name argument to the definition for field 'AdditionalCost.number_of_additional_installations'. address_program.AdditionalCost.number_of_additional_installations: (fields.E303) Reverse query name for 'AdditionalCost.number_of_additional_installations' clashes with field name 'Side.number_of_additional_installations'. HINT: Rename field 'Side.number_of_additional_installations', or add/change a related_name argument to the definition for field 'AdditionalCost.number_of_additional_installations'. I cannot figure out why this happened because I see that code has these lines: buyer_org = models.ForeignKey("acl.Organization", on_delete=models.SET_NULL, null=True, blank=True, related_name='buyer_costs') client_org = models.ForeignKey("acl.Organization", on_delete=models.SET_NULL, null=True, blank=True, related_name='client_costs') that are obviously two foreign fields that relate to columns of one model. If you need full code of the models let me know, it is quite large but I can add it if you need. Thank you p.s. If I rename the related_name of number_of_additional_installations, i still get the … -
How to upload a django app in docker container to AWS ECS
I have built a django application in docker container and I want to upload it Amazon ECS but I don't know how to go about it. Does anyone have a tutorial they can point me to -
DJANGO Python how to save data to database(mysql) and generate qrcode in another page using the data that save to database
DJANGO Python how to save data to database and generate QR code in another page using the data that save to database -
How to delete many to many relation objects in Django model
I have a model Post having many to many relation images. When a post is deleted, I would like all associated images to be also deleted. class Post(models.Model): images = models.ManyToManyField(Image, blank = True, related_name = 'posts') Are there something like models cascade options or I have to do something else? -
How to call app name when calling a one to one model in django?
This is my apps: user students university Now, how to use same names for two model ? for instance each student and university have profile model. At first when i do "Class Profile" under student It gets a new table named student_profile now in students app i can user student_profile = user.request.profile But how to do the same for university ? The table gets created like univerity_profile But how to use on views ? university_profile = user.request.profile How to use the app name when calling user.request.profile ? -
Getting started with the Stripe API
I want to add customer to customer payment in my project so I decided to go with Stripe API. But the documentation after "getting started" has a lot of stuff and seems confusing to me. Is there a proper way or sequence to follow it? I'd like to do it in Django -
how to solve this error ValueError: unicode object contains non latin-1 characters in django? [closed]
I want to show a message in Persian language when the user logs out of the account, but I receive this error: ValueError: unicode object contains non latin-1 characters The message I want to display is: شما خارج شدید How should I solve this problem? thanks -
Can Django handle two related post requests in succession? And The input from the first post will be saved and used for the second post
I have tried to build a web application that return the calories of a type of food. I use an API for pulling information and representing to the users. After seeing the result, if the users decide that she/he wants this food information to be stored in the dataset for future reference, they will save it. I want all this process to be wrapped inside one template and one view base fucntion and I have tried something like this: My model: class Ingredient(models.Model): MEASUREMENT=[('ml','ml'), ('gram','gram')] name=models.CharField(blank=False, max_length=200) quantity=models.DecimalField(blank=False, max_digits=8,decimal_places=0,default=100) measure=models.CharField(blank=False,max_length=4,choices=MEASUREMENT,default='gram') calories=models.DecimalField(blank=False,null=False,decimal_places=2,max_digits=8,default=0) def __str__(self): return self.name My views: from django.shortcuts import render from django.http.response import HttpResponseRedirect, HttpResponse from .models import Ingredient from .forms import IngredientForm import requests, json import requests import json api_url = 'https://api.calorieninjas.com/v1/nutrition?query=' def ingredient_form(request): add=False kcal=0 if request.method == 'POST': name=str(request.POST.get('name')) if Ingredient.objects.filter(name=name).exists(): track=Ingredient.objects.filter(name=name) add=True for val in track: if val.measure==str(request.POST.get('measure')): add=False amount=float(request.POST.get('quantity')) kcal=(amount/float(val.quantity))*float(val.calories) break if add==True: query = str(request.POST.get('quantity')) + ' '+str(request.POST.get('measure'))+' ' + str(request.POST.get('name')) response = requests.get(api_url + query, headers={'X-Api-Key': 'ZwDpQLeGgrYKVgNd7UE7/Q==ZwxlN5PK4cfBMhua'}) data = response.json() if len(data['items'])==0: return HttpResponse('Does not exits') else: kcal = float(data['items'][0]['calories']) else: add=True query = str(request.POST.get('quantity')) + ' '+str(request.POST.get('measure'))+' ' + str(request.POST.get('name')) response = requests.get(api_url + query, headers={'X-Api-Key': 'ZwDpQLeGgrYKVgNd7UE7/Q==ZwxlN5PK4cfBMhua'}) data = response.json() if … -
Changing User image in updating time in django
I am making User Profile for learning. in updating time user default image doesn't change. but username and email change to new username and email.only user image don't change. if I change profile image form admin page, it will change. but from Update page don't change. I can't find problem where is it. sorry for grammar mistakes :) /models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField( default='user.png', upload_to='static/images') def __str__(self): return self.user.username def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) /forms.py from django import forms from .models import UserProfile from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserForm(UserCreationForm): class UpdateUser(forms.ModelForm): email = forms.EmailField(required=True) class Meta: model = User fields = ('username', 'email') class UpdateProfile(forms.ModelForm): class Meta: model = UserProfile fields = ('image', ) /views.py from .models import UserProfile from django.contrib import messages from django.shortcuts import render, redirect from .forms import UserForm, UpdateUser, UpdateProfile from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login, authenticate, logout # Create your views here. def Home(request): if request.user.is_authenticated: user = request.user user, … -
Django import-export with FK constraint
I have been attempting to import data into my Django project using Django import-export. I have two models Ap and Job, Job has a FK relationship with Ap. Using the Admin, I can select the file and the type, CSV. So far my program seems to run, but gets hung up on the FK. I'm close, something is off and causing the import script to fail. Models.py class Ap(models.Model): line_num = models.IntegerField() vh = models.IntegerField() vz = models.IntegerField() status = models.CharField( choices=statuses, default="select", max_length=40) classified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Job(models.Model): aplink = models.ForeignKey(Ap, related_name=( "job2ap"), on_delete=models.CASCADE) job_num = models.IntegerField() description = models.CharField(max_length=200) category = models.CharField( choices=categories, default="select", max_length=40) status = models.CharField( choices=statuses, default="select", max_length=40) dcma = models.BooleanField(default=False), due_date = models.DateField(blank=True), created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) views.py class ImportView(View): def get(self, request): form = ImportForm() return render(request, 'importdata.html', {'form': form}) def post(self, request): form = ImportForm(request.POST, request.FILES) job_resource = JobResource() data_set = Dataset() if form.is_valid(): file = request.FILES['import_file'] imported_data = data_set.load(file.read()) result = job_resource.import_data( data_set, dry_run=True) # Test the data import if not result.has_errors(): job_resource.import_data( data_set, dry_run=False) # Actually import now else: form = ImportForm() return render(request, 'importdata.html', {'form': form}) resource.py class CharRequiredWidget(widgets.CharWidget): def clean(self, … -
Single page pdf usinng headless chrome
I want to create a pdf from HTML as a single page pdf The tech's that I have been using is Chrome headless Django Python Now the currently when we try to use chrome headless it prints the HTML file as a multiple pages Problem We want to have a single page pdf rather then having a multiple page pdf Note By single page pdf i don't mean that it should just print the first page Any help or guidance will be a great help and thanks in advance -
Digitalocean space access denied
I created a digital ocean storage space. The url of the space is as https://storagespace.nyc3.digitaloceanspaces.com However, when I click on the url to open on the browser I get the following error: <Error> <Code>AccessDenied</Code> <BucketName>storagespace</BucketName> <RequestId>tx000000000000001618a5e-0081246af3-1805687a-nyc3c</RequestId> <HostId>1805987a-nyc3c-nyc3-zg03</HostId> </Error> I have no idea what this error means or why I'm having it. I connected the s3 bucket with my django website and the static files are not being served to the browser as well, instead I get 403 forbidden error. Please how do I remove this access denied error? -
How to say "yes" to collectstatic prompt
I am trying to deploy a django app by Elastic Beanstalk. In my container-commands.config file, container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic <- What to do? option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: practice-ecommerce-app.settings When i ran eb deploy, I got errors, and following is cfn-init-cmd.log 2021-08-24 03:39:31,949 P14507 [INFO] -----------------------Command Output----------------------- 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] You have requested to collect static files at the destination 2021-08-24 03:39:31,950 P14507 [INFO] location as specified in your settings. 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] This will overwrite existing files! 2021-08-24 03:39:31,950 P14507 [INFO] Are you sure you want to do this? 2021-08-24 03:39:31,950 P14507 [INFO] 2021-08-24 03:39:31,950 P14507 [INFO] Type 'yes' to continue, or 'no' to cancel: Traceback (most recent call last): 2021-08-24 03:39:31,950 P14507 [INFO] File "manage.py", line 22, in <module> 2021-08-24 03:39:31,950 P14507 [INFO] main() 2021-08-24 03:39:31,950 P14507 [INFO] File "manage.py", line 18, in main 2021-08-24 03:39:31,950 P14507 [INFO] execute_from_command_line(sys.argv) 2021-08-24 03:39:31,950 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line 2021-08-24 03:39:31,950 P14507 [INFO] utility.execute() 2021-08-24 03:39:31,950 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute 2021-08-24 03:39:31,950 P14507 [INFO] self.fetch_command(subcommand).run_from_argv(self.argv) 2021-08-24 03:39:31,951 P14507 [INFO] File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/core/management/base.py", … -
dj-rest-auth: ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION not working
I'm using dj-rest-auth, allauth, and simple jwt to implement authentication. In django-allauth, setting ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION=True will automatically login user after the email is verified. But posting key to "/dj-rest-auth/registration/verify-email/" only returns {"detail":"ok"}. The source code below explains why: # allauth class ConfirmEmailView(TemplateResponseMixin, LogoutFunctionalityMixin, View): # ... def post(self, *args, **kwargs): # ... if app_settings.LOGIN_ON_EMAIL_CONFIRMATION: resp = self.login_on_confirm(confirmation) if resp is not None: return resp # this is a HttpResponseRedirect object # ... # dj-rest-auth class VerifyEmailView(APIView, ConfirmEmailView): # ... def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.kwargs['key'] = serializer.validated_data['key'] confirmation = self.get_object() confirmation.confirm(self.request) return Response({'detail': _('ok')}, status=status.HTTP_200_OK) Since I'm using JWT, how could I override this view to login user after verification and return access code?