Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Most Pythonic/Django way to dynamically load client libraries at runtime
I'm writing a Django application in which we will have multiple client libraries that make calls to third party APIs. We want to be able to determine which client library to load at runtime when calling different endpoints. I'm trying to determine the most Django/Pythonic way to do this The current idea is to store class name in a model field, query the model in the View, and pass the class name to a service factory that instantiates the relevant service and makes the query. I've also considered writing a model method that uses reflection to query the class name For example lets say we have a model called Exchange that has an id, a name, and stores the client name. class Exchange(models.Model): exchange_name = models.CharField(max_length=255) client_name = models.CharField(max_length=255) def __str__(self): return self.exchange_name Then in the View we might have something like: from rest_framework.views import APIView from MyProject.trades.models import Exchange from django.http import Http404 from MyProject.services import * class GetLatestPrice(APIView): def get_object(self, pk): try: exchange = Exchange.objects.get(pk=pk) except Exchange.DoesNotExist: raise Http404 def get(self, request, pk, format=None): exchange = self.get_objectt(pk) service = service_factory.get_service(exchange.client_name) latest_price = service.get_latest_price() serializer = PriceSerializer(latest_price) return Response(serializer.data) This syntax may not be perfect but it hasn't been … -
Django - Can not upload file using my form
Here's the situation: I'm quite new to Django and I'm trying to upload some files using a form I created. When I click on the submit button, a new line is created in my database but the file I selected using the FileField is not uploaded.But I can upload files via the admin page without any trouble. I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem I would be really thankful. Here you can find some code related to my form: forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(View): template_name = 'phyto/phyto_admin_fichiers.html' form = forms.PhytoFileForm() def get(self, request): return render(request, self.template_name, {'form': self.form}) def post(self, request): form = forms.PhytoFileForm(request.POST, request.FILES) form.save() return render(request, self.template_name, {'form': self.form}) phyto_admin_fichiers.html {% block forms … -
Throttles connection in day using Djang REST Framework
I want to limit the amount of connection to the web in a day. I have searched on Internet that using Djano REST Throttling, but I don't know how to use Django REST API. I wish I had a sample code to solve the problem. Thanks. -
Setting cache in nginx does not delete files for inactivity
I have an S3 bucket and AWS RDS Postgres database attached to my EC2 instance. I want to reduce S3 egress by setting up a linux server that caches data. For that reason I have attached the uWSGI of my django app to a nginx server. Although I have specified the inactive time for the proxy_cache_path, the cached files do not get deleted from my folder. Please help. I have set up the nginx.conf file in sites-available and created a symlink in sites-enabled and reload my nginx server. This is my conf file: ` proxy_cache_path /home/clyde/Downloads/new/automatic_annotator_tool/queried_data keys_zone=mycache:10m inactive=2m use_temp_path=off max_size=1m; upstream django { server local_ip; } server { listen 8000; server_name public_ip; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste location /static { alias /home/clyde/Downloads/new/automatic_annotator_tool/django_app/static; } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /etc/uwsgi/sites/uwsgi_params; proxy_cache mycache; } location /images { alias /home/clyde/Downloads/new/automatic_annotator_tool/queried_data; proxy_cache mycache; expires 2m; proxy_cache_valid any 2m; } location /nginx_status { stub_status; allow public_ip; deny all; } } This is the uwsgi command i run for starting the webserver: uwsgi --socket :8001 --module uvlearn.wsgi -p 2 --master` … -
How include location when upload photo?
I'm using IstangramApi this is my py: from InstagramAPI import InstagramAPI InstagramAPI = InstagramAPI("username", "password") InstagramAPI.login() # login photo_path = '/home/user/image/index.jpeg' caption = "Sample photo" location = "Rome" InstagramAPI.uploadPhoto(photo_path, caption=caption, location=location) without location it work... how can i post with location? It seems not official documentation.... Please Help -
How to add new input text in admin page in django?
Whenever I try to add new user in django admin page, it gives me username, password and new password input text but I have added Id_payment also in registration page but it is not showing. forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True) Id_number = forms.CharField(max_length=15, required=True) class Meta: model = User fields = ['username','email','password1','password2','Id_number'] -
Django form hidden field but previously load with value
I have a form with 6 field where 2 of then need to be preloaded with a specific values. Then I need those 2 fields to be hidden since the user doesn't need to deal this those. I found plenty of ask here in stackoverflow, most of the are applicable to my problem using HiddenInput() method, but when I preload the field, the HiddenInput() method doesn't work any more. here is my forms.py code class SurveyCreateForm(BSModalForm): def __init__(self, *args, **kwargs): self.wellbore = kwargs.pop('wellbore', None) self.profile = kwargs.pop('profile', None) super(SurveyCreateForm, self).__init__(*args, **kwargs) self.fields['wellbore'] = forms.ModelChoiceField(queryset=Wellbore.objects.filter(pk=self.wellbore), empty_label=None) self.fields['profile'] = forms.ModelChoiceField(queryset=SurveyProfile.objects.filter(pk=self.profile), empty_label=None) class Meta: model = Survey fields = ['wellbore', 'profile','md','inc','azm','time_stamp'] # Django Form : 2 : Model Forms @2:45 labels = {'wellbore':'Wellbore', 'profile':'Profile','md':'MD','inc':'Inclination','azm':'Azimuth','time_stamp':'Date Time'} widgets = {'wellbore':forms.HiddenInput(), 'profile':forms.HiddenInput() } and here the html template <form method="post" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Add New Survey</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div style="margin: 10px 10px 10px 10px;"> <table> {{ form.as_table }} </table> </div> <div class="modal-footer"> <p> <button type="button" class="submit-btn btn btn-primary">Save</button> </p> </div> </form> I need those fields to be populated but at the same time hidden from the user. Thanks in advance. -
How to render two form fields as one field in Django forms?
I'm working on Django application where I need to render a form differently. The form contains multiple fields related to a person. Firstname Lastname email address city country Phone Pincode There are two flows in my application. In the first flow I can render all the form fields and save them when the user enters some data and submit. But in the second flow, I need to display only three fields as below. Name - Combination of Firstname and Lastname Email Phone The data entered in the name field should be split and saved as Firstname and Lastname. And for other remaining mandatory fields in the form that are not rendered, I can fill empty values and save the model in Backend. What is the best way to render the forms differently for each flow? Python: 3.7.3 Django: 2.1.5 -
when I deploy my project to heroku, it is not sending a confirmation email on signup but when I signup in my local computer I get the mail
django app gaierror at / [Errno -2] Name or service not known Request Method: POST Request URL: https://mangoinstagram2.herokuapp.com/ Django Version: 1.11 Exception Type: gaierror Exception Value: [Errno -2] Name or service not known Exception Location: /app/.heroku/python/lib/python3.6/socket.py in getaddrinfo, line 745 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.8 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Tue, 30 Jul 2019 09:07:58 +0300 -
Dynamic choices model
I'm working on my first commerce website. I have various products with totally different choices.(models,colors,quality,etc) So I want each of my products to have different choices. I'm confused what kind of Field should I add to my product Model. And how to I manage to add choices to each product. Thank you very much class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=5,decimal_places=2) category = models.ForeignKey('Category', null=True, blank=True,on_delete=models.DO_NOTHING) slug = models.SlugField(default='hello') image = models.ImageField(null=True, blank=True) available = models.BooleanField(default=True) -
How to set the time for AXES_LOCK_OUT_AT_FAILURE in django?
I am trying to lockout the users if the user attempt too many failed login attempts.And after 5 minutes I want to give access to login user again and I tried like this.I followed this documentation and write this settings in my settings.py file.However i failed to set the times for AXES_COOLOFF_TIME.I got this error : Exception Type: TypeError Exception Value: can't subtract offset-naive and offset-aware datetimes settings.py INSTALLED_APPS = [...., 'axes',] AUTHENTICATION_BACKENDS = ['axes.backends.AxesBackend',] MIDDLEWARE = [..............., 'axes.middleware.AxesMiddleware', ] from django.utils import timezone now = timezone.now() AXES_COOLOFF_TIME = now + timezone.timedelta(minutes=5) -
Use Django Permission in Pure Javascript
I used Django Permission in Django Template before like {% if perms.assets.change_log %} and it works. I want to this to render a server-side datatable in JavaScript but it failed, like <script> console.log(perm.assets.change_log) </script> There is nothing output on the console. Could you please help me with this? Thanks a lot. -
How to filter through textfield in models in django
I am trying to create a small search feature within my django project and i need to filter through my data My models are all in textfield formats, and when i try to use .filter() to search for what i want, i get an error saying that an instance of textfield has no filter. is there any way to work around this? #My Model class api_data(models.Model): data_source = models.TextField() brief_description_of_data = models.TextField() datasets_available = models.TextField() brief_description_of_datasets = models.TextField() country = models.TextField() api_documentation = models.TextField() #what I'm trying to do def index(request): query = request.Get.get('q') if query: queryset_list = api_data.datasets_available.filter(Q(title__icontains=query)) -
Is there a way to save form input to class self in django?
I have a form class where I ask for a username and password. I created my own authenticate function. I simply want to pass the username and password input to the authenticate function. I've tried saving it as self.user/self.pw or passing it directly. Thanks in advance! I am using Django lockdown. I don't need to save the username and password to a database because I'm using my own authentication function. class loginform(forms.Form): username = forms.CharField ... password = forms.CharField... def authenticate(self, request, username, password): print("this actually prints") '''authenticate with passed username and password''' -
Django - Not able to add ForeignKey or OneToOneField to User model
I have a Profile model in which I am creating a OneToOneField to User Model. Code: user=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user', null=True) I am able to run makemigrations but on running migrate, I get the following error. ValueError: invalid literal for int() with base 10: 'user' -
How to solve the problem of 'auth', '0011_update_proxy_permissions'?
I am trying to load the page of django. I downgraded django to version 2.1.3 but it gave me error message. Whenever django version is 2.2.8 and I add user in admin page, it gives me another error. I also equaled uses_savepoints = True, which is by default False Error after downgrading django django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_auto_20190724_1222 dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') Error in 2.2.8 django version NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s10368_x1" -
Image not closing correctly?
I am overwriting my save model function to resize profile pictures before saving them. My function looks like this: def save(self, *args, **kwargs): super(Profile, self).save(*args, **kwargs) if self.avatar: with Image.open(self.avatar) as image: image_path = self.avatar.path image_name = self.avatar.path[:-4] image_ext = self.avatar.path[-4:] resize_images(image, image_path, image_name, image_ext) image.close() My resize_images function looks like this: def resize_images(image, image_path, image_name, image_ext): image = image.resize((400, 400), Image.ANTIALIAS) image.save(image_path, optimize=True, quality=95) medium_image = image.resize((250, 250), Image.ANTIALIAS) image.close() medium_path = image_name + "_medium" + image_ext medium_image.save(medium_path, optimize=True, quality=95) small_image = medium_image.resize((100, 100), Image.ANTIALIAS) small_path = image_name + "_small" + image_ext small_image.save(small_path, optimize=True, quality=95) medium_image.close() mini_image = small_image.resize((50, 50), Image.ANTIALIAS) mini_path = image_name + "_mini" + image_ext mini_image.save(mini_path, optimize=True, quality=95) small_image.close() mini_image.close() When I save an image, it works perfectly, however, when I try to upload another image just a few seconds later, I get this error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\samal\PycharmProjects\youchoices\media\users\179\avatars \179312.jpg' The culprit of this is the resize_images function because when I comment that out, this error goes away after reuploading every few seconds. However, I don't understand what I'm doing wrong. I'm closing the images, but why is it still complaining? -
Can not access imported module from inside Python function
I have a Django web app and app trying to make a script in the project directory that will create some random instances of a model (Person). For some reason, I can't access any of my import statements. I can't even use the simple 'Random' module that is built in. I keep getting an error saying 'NameError: name 'random' is not defined'. I am running this script inside of my Django project, so I am running the script by the following command: python manage.py shell < insert_into_database.py I have the following code: import io import random import string import pycountry import names domains = ["hotmail.com", "gmail.com", "aol.com", "mail.com", "yahoo.com"] letters = string.ascii_lowercase[:12] def get_random_email(domains, letters): # length of each email address length = 10 random_domain = random.choice(domains) random_name = ''.join(random.choice(letters) for i in range(length)) random_email = [random_name + '@' + random_domain for i in range(1)] # Create 1000 random records for i in range(1000): email = get_random_email(domains, letters) -
How lo load Stripe objects in Django pagination
I want to paginate invoices from Stripe @login_required def invoice_list(request): customer = stripe.Customer.list(email=request.user.username) for invoice_search in customer['data']: customer_invoice_list = stripe.Invoice.list(customer=invoice_search['id']) page = request.GET.get("page", 1) paginator = Paginator(customer_invoice_list, 20) try: invoices = paginator.page(page) except PageNotAnInteger: invoices = paginator.page(1) except EmptyPage: invoices = paginator.page(paginator.num_pages) context = { 'invoices': invoices, } return render(request, 'invoice_list.html', context) That is my code, I got error: Unhashable type In Django 1.11 documentation say can load list or queryset, I obtain Invoices List, why can't paginate?? -
"name 'log' is not defined" error django python
I'm getting the error "name 'log' is not defined". Below is my code, but I have almost the exact same code on a different file which works fine. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse, HttpResponseRedirect, JsonResponse import json from .models import * import os, sys # Create your views here. def count(request, start, step): try: stop = 100 count_list = [] while(start<stop): count_list.append(start) start = start + step return count_list return JsonResponse(count_list) except Exception as e: exc_type, exc_obj, exc_tb = sys.exc_info() other = sys.exc_info()[0].__name__ fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] errorType = str(exc_type) return JsonResponse({"isError": True, "error":str(e), "errorType":errorType, "function":fname, "line":exc_tb.tb_lineno, "log":log}) -
Bootstrap-select widget when cloned to be used in a dynamic django 2 formset doesn't work right/won't show up?
I followed this tutorial to add a formset to my django2 project that can add and delete forms. For my project I have a markings form where a user can select from a large amount of markings to add to a image. The problem arises however that since I have a bootstrap-select widget that the new cloned widgets that are made when adding a form is either using the first selects's dropdown searchbar and don't have any choices in them(i.e. they are not initialized to be their own, perhaps cause the DOM is not refreshing?) or when I try to initialize them using newElement.find('.bootstrap-select').replaceWith(function() { return $('select', this); }) newElement.find('.selectpicker').selectpicker('render'); where newElement is my cloned element from var newElement = $(selector).clone(true); the widget just does not display at all. Without me trying to re-initialize the widgets they appear like this, blank with no choices: https://imgur.com/7rfjA6t When I try to re-initialize them they are not appearing: https://imgur.com/j8aCSLc Here is my javascript add a form functions $(document).on('click', '.addMarkingRow', function(e){ e.preventDefault(); cloneMore('.markingRow:last', 'form'); return false; }); function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' … -
Filter Value Displaying Strange in Django
I am using a filter and .aggregate to sum up the value of a column 'cases' in my 'manifests' model. When this displays in the template it gives me the correct amount, but when the page displays it shows as, for example, "{'cases__sum': 1192}" . The number 1192 there is indeed the sum, but I don't want the rest of the text to show to the user! How can I stop this and get just the number? VIEWS.PY def add_manifest(request, reference_id): form = CreateManifestForm(request.POST or None) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) try: order = Orders.objects.get(id=reference_id) instance.reference = order except Orders.DoesNotExist: pass instance.save() form = CreateManifestForm(initial={'reference': Orders.objects.get(reference=reference_id)}) reference = request.POST.get('reference') manifests = Manifests.objects.all().filter(reference=reference) total_cases = Manifests.objects.filter(reference=reference).aggregate(Sum('cases')) #totaling the cases for the readonly field totalCNF = 0 for item in manifests: totalCNF += item.cases * item.CNF context = { 'form': form, 'reference_id': reference_id, 'manifests' : manifests, 'total_cases': total_cases, 'totalCNF': totalCNF, } return render(request, 'add_manifest.html', context) ADD_MANIFEST.HTML <div class="column"> <label for="form.reference" class="formlabels">Case Total:</label><br> <input type="text" value="{{ total_cases }}" readonly> </div> I just want the number not the whole reference to display in this html input box -
how to fix an error when installing mysqlclient
i can't install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/suainul/dev/Env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-dcdyrtea/mysqlclient/setup.py'"'"'; file='"'"'/tmp/pip-install-dcdyrtea/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-o6fcabnw --python-tag cp37 cwd: /tmp/pip-install-dcdyrtea/mysqlclient/ Complete output (31 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.7 creating build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.7/MySQLdb creating build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.7/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/MySQLdb x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -Dversion_info=(1,4,2,'post',1) -D__version__=1.4.2.post1 -I/usr/include/mysql -I/usr/include/python3.7m -I/home/suainul/dev/Env/include/python3.7m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.7/MySQLdb/_mysql.o MySQLdb/_mysql.c:37:10: fatal error: Python.h: Tidak ada berkas atau direktori seperti itu #include "Python.h" ^~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing … -
Sequel -C copy database runs succesfully but does not copy any of the records in any table
I am trying to copy my sqlite3 database to a postgresql database. It runs succesfully, but no data is inserted into the tables. What is the cause? sequel -C sqlite:db.sqlite3 postgres://username:password@localhost/database Databases connections successful Migrations dumped successfully Tables created Begin copying data Finished copying data Begin creating indexes Finished creating indexes Begin adding foreign key constraints Finished adding foreign key constraints Primary key sequences reset successfully Database copy finished in 1.0044088 seconds -
Having two different forms in a Django template
In my project, i have a template where i'm trying to put two forms for different use cases. I've never come across this problem before, so i don't really know where to go from here to use two forms in the same page. At first i thought of creating another view to handle each form, but i think that this solution would create problems with the rendering of my templates, other than not being sustainable if i should have this problem again with another template. After making some research, i found a solution but it works for class based views, but i'd like to avoid that since my view is already a function based view, and i would have to make a lot of changes in my code. Would it be possible to solve this problem with a function based view? Every advice is appreciated First field class FirstForm(forms.ModelForm): firstfield = forms.CharField() secondfield = forms.CharField() class Meta: model = MyModel fields = ("firstfield", "secondfield") def save(self, commit=True): send = super(FirstForm, self).save(commit=False) if commit: send.save() return send** Second Form class SecondForm(forms.ModelForm): firstfield = forms.FloatField() secondfield = forms.Floatfield() thirdfield = forms.CharField() class Meta: model = MyModelTwo fields = ("firstfield", "secondfield", "thirdfield") def …