Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Permission denied to upload folder Django
I am trying to upload images in django. I have set static directory in settings.py STATIC_URL = '/assets/' STATIC_ROOT = os.path.join(BASE_DIR, "assets") SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = ( os.path.join(SITE_ROOT, 'assets'), ) here is my model image Field doImage=models.ImageField(upload_to='doImage/%Y/%m/%d',verbose_name='Do Image') Now when i tried to upload it then i faced permission denied 13 error. I had tried command chmod with 777 to give a permissions to folder sudo chmod -R 777 assets i also had tried change user of file using command sudo chown -R root:root assets But both things didn't worked for me. So anyone have idea that what's going wrong let me know. -
Django Count rows with duplicate values
I am working on counting rows with duplicate values in a django Model and running into a little hitch. I have looked at this question Django Select Rows with duplicate Values and the solution is perfect. But my question is, What if I want to Count the rows and group them according to: Name of the duplicated row, and how many times it has been duplicated, instead of just displaying the name of the repeated rows. my code so far: views.py dupes = Application.objects.values('school_name').annotate(Count('id')).filter(id__count__gt=1) query = Application.objects.filter(school_name__in=[item['school_name'] for item in dupes]) The query variable returns a queryset with the Applications that have duplicate values for the field school_name while this line: repeated_names = Application.objects.values('school_name').annotate(Count('id')).order_by().filter(id__count__gt=1).values_list('school_name', flat='true') returns a list of the duplicated school names. What I expect is something like: (school_name=school_name_1, count=2), (school_name=school_name_2, count=3).. etc. -
how to fix footer at the bottom of responsive page
I have a responsive page. I want to fix footer at the bottom of this page. I have searched a lot and find many working solution. However, all of them are failed when it comes to the responsive page. The problem is that when I set position for footer to be fixed, once I reduce the screen size the footer stay in its place and gets cover by contents. I set the z-index to make it on the outer layer. How ever. it stays in the middle of the screen while the hight gets bigger. I know the page layout I made does not looks wright but i do not know what to change.Please look at the code and advice me what to change. Note: 1- I used javascript to make the margin-top change with screen size 2- I used Django for back end and extends base page to this form page this is the base page: <!DOCTYPE html> <html> <head> <title> </title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="description" <meta name="viewport" content="width=device-width,initial-scale=1"> {% load staticfiles %} <link rel="stylesheet" type="text/css" href=" {% static 'towns/style/bootstrap_3.3.7_dist/css/bootstrap.min.css' %}" > <link rel="stylesheet" type="text/css" href="{% static 'towns/style/bootstrap_3.3.7_dist/css/bootstrap_theme.min.css' %}"> <!-- to add future links when it is … -
How to break for loop in jinja2
hy users please tell me how i break for loop in jinja 2 i am use for loop with if condition and i want if my if condition is true then for loop is break this is my code function refercheck(){ var input_value = document.getElementById('refer').value; {% for i in refer %} document.getElementById("valid").innerHTML = ''; if( input_value == "{{i.refercode}}" ){ $('#valid').append('Referred By {{i.username}}'); } i am use this function in input onkeyup="refercheck()" and i send the dict from view function my dict key is refer i am send all user data and check the input is same as other user refercode this is give me only last row refercode is same please tell me how i break loop when my if condition is true or other solution for it -
Custom validation is not working inside forms.py
I want to validate my email field like: if email contains [gmail.com,outlook.com,yahoo.com] then raise validation Error.But it's not working,don't know where i am doing wrong. plz help me views.py from django.shortcuts import render from django.views.generic import View from access.utils import is_valid from access.mixin import HttpResponseMixin import json from access.forms import Employer_Form from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator @method_decorator(csrf_exempt,name = 'dispatch') class Emp_Registration_view(View,HttpResponseMixin): def post (self,request,*args,**kwargs): data = request.body json_data = is_valid(data) if not json_data: return self.render_http_response(json.dumps({'msg':'Please send valid json only'}),status=400) emp_data = json.loads(data) form= Employer_Form(emp_data) if form.is_valid(): form.save(commit=True) return self.render_http_response(json.dumps({'msg':'Registered Successfully'})) if form.errors: return self.render_http_response(json.dumps(form.errors),status=400) forms.py from access.models import Employer_Registration from django import forms class Employer_Form(forms.ModelForm): def clean_email(self): email = self.cleaned_data['emp_email'] email_lists = ['gmail.com','yahoo.com','outlook.com','hotmail.com'] data = emp_email.split('@') if data in email_lists: raise forms.ValidationError("email is not valid") return email class Meta: model = Employer_Registration fields = '__all__' -
Is it necessary to add endpoints for resources that are only accessible to the admin in django
Say I have resources that are only accessible to an admin. Do I really need to create an endpoint to list out all these resources considering django has an admin interface where the admin can view all these resources. -
how to insert sample data into mongodb using mongoengine with django
Using django + mysql we can insert some sample data from .yaml file. I want to know how to insert sample data using mongoengine + django -
Django; 2 model/class/tables pass into one template
Forgive me if I ask something foolish, I very new to coding industry I been working on Django project to create dashboards to show case monitoring of an hydroponics greenhouse. So I create two model; class tank_system(models.Model): PH = models.DecimalField(default=7.5,max_digits=3, decimal_places=1) EC = models.DecimalField(default=13.3,max_digits=3, decimal_places=1) Winlet = models.DecimalField(default=20.1, max_digits=3, decimal_places=1) Woutlet = models.DecimalField(default=20.3,max_digits=3, decimal_places=1) WaterLevel = models.IntegerField(default=500) TempWater = models.IntegerField(default=25) tanks = models.IntegerField(default=1) datetime = models.DateTimeField(default=timezone.now()) class ambient (models.Model): TempRoom = models.IntegerField(default=25) CO2 = models.DecimalField(default=20.0, max_digits=3, decimal_places=1) O2 = models.DecimalField(default=20.0,max_digits=3, decimal_places=1) Humdity = models.IntegerField(default=25) Room = models.IntegerField(default=1) datetime = models.DateTimeField(default=timezone.now()) and I render the data of two model into one single template here my views; from django.shortcuts import render, get_object_or_404 from CGI.models import tank_system, ambient def index(request): tank = tank_system.objects.all() room = ambient.objects.all() return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank},{'room': room}) when I try this I only got data form 1 table Here my html template; {% extends "base.html" %} {% block content %} {%load staticfiles%} {% load static %} <div class = "containor"> <div class ="row" id = "row1"> <div class ="col-sm-6" style="background-color:"> <h2>Camera</h2> </div> <div class ="col-sm-6" style="background-color:"> <h2>Ambinet</h2> </div> </div> <div class = "containor"> <div class="row" id="row2"> <div class ="col-sm-6" id="Cam1" style="background-color:"> <div class="containor"> <video id="livestream" width="550" height="350" autoplay></video> … -
Transfer of data from the button to the post form on the next page. Django
I am trying to pass the get parameter from the previous page assigned to my button to the next page add it to my form and save it in my database. My code looks like this: views.py def massage_order(request): parametr_html_product_name = request.GET('parameter') if request.method == 'POST' and 'btn_massage_order' in request.POST: ordering_form = OrderingMassageForm(data=request.POST) if ordering_form.is_valid(): massage_product = parametr_html_product_name [...] else: ordering_form = OrderingMassageForm() templates.html <a href="{% url 'app:massage_order' %}?parameter={{ product.name }}&parameter_1={{ product.price }}&parameter_2={{ product.time }}&parameter_3={{ masseur.name }}"> <div class="btn-group btn-action-label" role="group" aria-label="Like"> <div class="btn btn-sm btn-outline-primary btn-label">{{ product.price }} zł/ {{ product.time }} min</div> <button type="button" class="btn btn-sm btn-primary btn-action"> <span>Zamów masaż</span> </button> </div> </a> But I receive a mistake every time 'Multi Value Dict Key Error' i found his solution parametr_html_product_name = request.GET.get('parameter', False) but in this situation, my variable is False and not the name of the product (what it expects). How can I pass the variable 'html parameter product name' to my form? I tried to add it to the list (also without a positive effect). Any help will be appreciated. Why, despite adding a variable to the Django list, does not it see in my form? list = [parametr_html_masseur_name, parametr_html_product_name] [...] massage_product = list[1] [...] -
Django: ManyToManyField related name not working
Im trying to output all the events that a member is one of the sponsors and speakers of that event. Using member.event_set.all works fine for members that were event speakers. But if I use member.msponsor_set.all for members that were event sponsors nothing is returned. Here is my event model... class Event(models.Model): member_speaker = models.ManyToManyField(Member) member_sponsor = models.ManyToManyField(Member, related_name='msponsor') -
How to set password in APIView - Django
I want to set password of user whose i am saving data. Comment line i was trying to set but it is not setting and error is comming set_password is not defined. How can i set a password whose instance i am saving in APIView. from rest_framework.views import APIView from rest_framework import status class EmployeeAddAPIView(APIView): def post(self, request, *args, **kwrgs): serializer1 = EmployeeRegisterSerializer(data=request.data) serializer2 = EmployeeProfileSerializer(data=request.data) user_role = ACLRoles.objects.get(id=4) if serializer1.is_valid(): print(serializer1.validated_data['email']) # password = set_password(random_password) profile = serializer1.save( username = serializer1.validated_data['email'], # password = password ) if serializer2.is_valid(): serializer2.save( user_id = profile.id, user_company_id = self.request.auth.application.company.id, user_role_id = user_role.id ) print(serializer2.errors) return Response(serializer1.errors, serializer2.errors) return Response(serializer1.errors, serializer2.errors) Previously in my app i was setting password some like this: new_user = ur_form.save(commit=False) new_user.username = new_user.email new_user.set_password(random_password) new_user.save() -
Django: How to prefetch related for a model instance. Perhaps by wrapping in a queryset?
I use Django rest framework and I have decent nesting in my model relations. I'm working on optimizing my queries. Many of my functions consume or manipulate a single instance of model and it's often further downstream in the data flow that it turns out I need some prefetching. One classic instance of this is with DRF serializers. Here's an example. @api_view(['GET']) def fetch_user_profile(request): profile = request.user.profile # has many nested relationships return Response(UserProfileSerializer(profile).data, status=status.HTTP_200_OK) # this ends up taking many queries I've seen some solutions suggesting passing queryset with prefetch_related in the context although I haven't been able to get a full picture on how that would work (I've only found a couple of places that discuss it partially, might open a whole other question on that). An easy fix (and one that would generalize beyond serializers) would be if I can have a wrapper function to wrap my instance in a queryset and then call prefetch on that, passing it into the serializer. Something like: def queryset_wrap(instance): return type(instance).objects.filter(id=instance.id) I'm wondering if there's a better way to do this. -
I/O on Closed File error in Django When generating thumbnail of uploaded image
I'm building a django site, and when I upload an image (the model is Photo) through the admin view, I want to generate an arbitrary thumbnail of it and save that off to a Thumbnail Image Field. The thumbnails are generating nicely, but when the Photo model tries to save, I get that I've tried to perform an I/O operation on an object that's closed: "I/O operation on closed file". The stack trace traces back up to the call to the superclass, so I think it's made it through the generate_thumbnail function. What am I doing wrong? Any help would be appreciated. from PIL import Image from io import BytesIO from django.core.files.base import ContentFile class Photo(models.Model): photo=models.ImageField(upload_to='photos/',blank=True) thumbnail = models.ImageField(upload_to='thumbs/', editable=False, null=True) def save(self,*args,**kwargs): if self.photo: self.generate_thumbnail() super(Photo, self).save(*args,**kwargs) def generate_thumbnail(self): img =Image.open(self.photo) img.thumbnail([consts.THUMB_HEIGHT,consts.THUMB_WIDTH],Image.ANTIALIAS) name = os.path.basename(self.photo.name) thumb_name, thumb_ext = os.path.splitext(name) thumb_ext=thumb_ext.lower() outname="thumb_"+thumb_name+thumb_ext if thumb_ext in ['.jpg','.jpeg']: filetype='JPEG' elif thumb_ext == '.gif': filetype='GIF' elif thumb_ext=='.png': filetype = 'PNG' else: raise Exception("Failed to generate thumbnail. Is the filetype valid?") temp_thumb=BytesIO() img.save(temp_thumb,filetype) temp_thumb.seek(0) self.thumbnail.save(outname,ContentFile(temp_thumb.read()),save=False) temp_thumb.close() return True -
Django TemplateDoesNotExist at / debug_toolbar/base.html after deployiing to EC2
I am trying to deploy a Django app on EC2 Instance. I had put my EC2 instance in the Allowed_Host correctly. but it kept giving me a Disallowed_Host error. I have been trying to fix that but Now I get the. Django TemplateDoesNotExist at / debug_toolbar/base.html Error Can anyone advise on what I am doing wrong? Below are my screenshots and code Also below is the Traceback just in case I have attached my settings.py file below import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "1111111111111111111111" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ["ec2-11-111-111-11.compute-1.amazonaws.com", "127.0.0.1", "Siteevent.com", "www.Siteevent.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'bootstrap3', 'accounts', 'groups', 'posts', 'proof', 'feeds', 'questions', 'tasting', 'verification', 'cart', 'stripe', 'order', 'report', 'django_cleanup', 'bootstrap_datepicker_plus', 'social_django', 'storages', 'captcha', ] AUTHENTICATION_BACKENDS = [ 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', 'accounts.authentication.EmailAuthBackend', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'Site.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR, os.path.join(BASE_DIR, 'order', 'templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', 'cart.context_processors.counter', … -
Django migrations for foreign key does not reflect in MySQL database
# Generated by Django 2.1.5 on 2019-02-18 10:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projectName', '0003_auto_20190218_1604'), ] operations = [ migrations.AlterField( model_name='projectdetails', name='userdetails', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='projectName.UserDetails'), ), ] This is my migration file named 0004_auto_20190218_1614.py. I ran makemigrations and migration command. All the other addition and deletion of columns are successful but in this case where I have added a foreign key the changes have not been reflected in database. When I try to insert the record. I get this exception _mysql_connector.MySQLInterfaceError: Unknown column 'userdetails_id' in 'field list' and then this: During handling of the above exception, another exception occurred: AttributeError: 'NoneType' object has no attribute 'strip' -
Django serializer update function very long code
I have written an update method for my API.But in the end it ended up taking more than 100 lines of code.Just wanted suggestions and tips on how to shorten the code My update method: def update(self, instance, validated_data): levels = self.initial_data.get('levels') categories = self.initial_data['selectedCategories'] instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) instance.tenant = self.context['request'].user.tenant levels_it_has = [workflow_level.level for workflow_level in WorkflowLevel.objects.filter(workflow=instance).order_by('level') ] for level in levels: # Check if editing existing level if WorkflowLevel.objects.filter(workflow=instance,level=level['level']).exists(): level_var = WorkflowLevel.objects.get(workflow=instance,level=level['level']) level_var.level = level['level'] level_var.operation=level['operation'] level_var.save() #If creating new Level else: level_var = WorkflowLevel() level_var.workflow = instance level_var.level = level['level'] level_var.operation = level['operation'] level_var.save() ########### Level Permissions ############3######### for permission in level['workflow_permissions']: permission_obj = WorkflowPermission.objects.get(short_name=permission['short_name']) permissions_in_level = [ perm.permission.short_name for perm in WorkflowLevelPermission.objects.filter( level=level_var,permission=permission_obj, level__workflow=instance).select_related('permission') ] if not level_permissions.exists(): permission = WorkflowLevelPermission() permission.level = level_var permission.permission = permission_obj permission.save() new_perms=[ perm.permission.short_name for perm in WorkflowLevelPermission.objects.filter( level=level_var, level__workflow=instance).select_related('permission') ] ####################### DELETE PERMISSIONS #################################### if len(new_perms) > len(level['workflow_permissions']): short_names = [perm['short_name'] for perm in level['workflow_permissions'] ] perm_to_delete = [item for item in new_perms if item not in short_names] workflow_permission_to_delete = WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance,permission__short_name__in=perm_to_delete) workflow_permission_to_delete.delete() if len(level['workflow_permissions']) == 0: WorkflowLevelPermission.objects.filter(level=level_var,level__workflow=instance).delete() ####################### DELETE LEVELS #################################### if len(levels_it_has) > len(levels): level_numbers = [lev['level'] for lev in levels] level_to_delete = … -
How to Update models field based on another field of same models
class PurchaseOrder(models.Model): purchase_order_id = models.AutoField(primary_key=True) purchase_order_number = models.CharField(unique=True) vendor = models.ForeignKey(Vendor) i am creating Purchase Order(po) table. when po created i have to update purchase_order_number as "PO0"+purchase_order_id ex PO0123 (123 is Primary key). so i am using def save in models to accomplish this def save(self): if self.purchase_order_id is not None: self.purchase_order_number = "PO"+str(self.purchase_order_id) return super(PurchaseOrder, self).save() It is working fine with single creation but when i try to create bulk of data using locust(Testing tool) its giving an error duplicate entry for PurchseOrdernumber Can we modify field value in models itself some thing like this purchase_order_number = models.CharField(unique=True,default=("PO"+self.purchase_order_id ) -
DRF serializer check undefined field
I used drf and also used serializer to check user input. Here is my serializer.py class BoardSerializer(serializers.Serializer): user_id = serializers.IntegerField(required=True) body = serializers.CharField(required=False) And use it like this. serializer = BoardSerializer(data=request.data) if serializer.is_valid(): .... It seems that doesn't check undefined field. For example, If I request with {'user_id':1, 'body': 'abc', 'akak': 1}, is_valid() do not catch field 'akak' and just pass the data. Is there any function to validate if fields is defined in serializer or not? Thanks. -
Trouble with importing ListView
I'm using python 3.7 and django 2.1. Trying to create a class based view, and first have to import it in my views.py. So I put: from django.views.generic import Listview which is what the tutorial said to do. When I run the server, I get: ImportError: cannot import name 'Listview' from 'django.views.generic I tried it with django.views.generic.list import ListView, but that didn't work either. Anyone have any ideas? Pretty new to coding, let me know if there's a better way to ask the question as well. I was as specific as I could be. -
auto populate slug field is not working in django
I am trying to make posts which uses slug as post url. I add slug field But its not auto populating. I want to make it auto populate. So far I have done this. I add pre_save at the end. I tried to save posts from django admin it says something like this This field is required. posts/models.py from django.db import models from django.core.validators import FileExtensionValidator from django.db.models.signals import pre_save from django.utils.text import slugify # Create your models here. class Category(models.Model): title = models.CharField(max_length = 120, verbose_name="Title" ) updated_at = models.DateTimeField(auto_now_add=True, verbose_name="Updated at") created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Posts(models.Model): title = models.CharField(max_length=60) slug = models.SlugField(unique = True) file_upload = models.FileField(null= True, blank=True, validators=[FileExtensionValidator(['pdf'])]) content = models.TextField() category = models.ForeignKey(Category, null= True,verbose_name="Category", on_delete=models.CASCADE) updated = models.DateTimeField(auto_now=True, auto_now_add=False) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) # class Meta: # verbose_name = "Post" # verbose_name_plural = "Posts" # ordering = ['-created_at'] def __unicode__(self): return self.title def __str__(self): return self.title def create_slug(instance, new_slug=None): slug = slugify(instance.title, allow_unicode = True) if new_slug is not None: slug = new_slug qs = Posts.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s"%(slug, qs.first().id) return create_slug(instance, … -
Django migrations not applying after moving from test PC to production server/DB
I am unable to run the inital migrations in my django project on my production server. I started working on my Django app on my computer with a sqlite db. I was able to run the initial migrations (auth, admin, etc.) and they created tables in my sqlite db with no problem. I was also able to get tables created for the models in my app. Today I moved the same django project to my webfaction server via git and I am unable to get my MySQL db populated with tables at all. As soon as I created the db, I ran migrate but it said there were no migrations to apply. I tried deleting the migrations folder in my app, but that didn't help at all, probably because there is no django_migrations table to compare any migrations against. It seems as if the initial migrations are stored where django is installed. This is not part of my git repo, so anything there that might indicate whether the migrations have been made wouldn't be pulled over. I tried running python manage.py migrate admin And the same thing with auth, but it did't work I'm not really sure what the proper … -
Datatables not working unless port is specified (proxy_pass)
Data tables seem to only be working when navigating directly to my Django web application at http://server.com:9001 even when I've proxied all HTTP traffic to 9001. Screenshot when viewing from http://server.com:9001/stores Screenshot when viewing from http://server.com/stores The datatable just simply refuses to work. What's even more odd is I have another data table at /servers doing the same thing, but an identical table at /closed-stores works consistently (I've refreshed dozens of times in a row to try and get it to break & it won't). Each of these tables' JS is simply $('#table-id').Datatable(); but I'll leave this out as its clearly working, so I believe its my Nginx.conf maybe, or something to do with Django? I'll note as well there are 0 errors in console during all scenarios. Nginx.conf server { listen 80 default_server; #listen [::]:80 default_server; server_name _; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_pass http://127.0.0.1:9001; } location /static { autoindex on; alias /home/usr/applications/it-database/static/; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } } Its worth noting that these tables have been working perfectly without a single issue … -
Calling a variable from another class that's contained within a for loop
variable from another class that's contained within a for loop. Problem calling it see my example Tried to move code around and making global variables but did not work. import requests class Values: def get_crypto_data_dict(self): usd_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=usd&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" gbp_url = "https://api.coingecko.com/api/v3/coins/markets?" \ "vs_currency=gbp&order=market_cap_desc&per_page=250&page=1" \ "&sparkline=false&price_change_percentage=24h" previous_request = None crypto_dict = None crypto_dict = dict() requests1 = requests.get(usd_url) results1 = requests1.json() requests2 = requests.get(gbp_url) results2 = requests2.json() for i in range(0, 250): crypto_dict[results1[i]['id']] = { 'coin_name': results1[i]['name'], 'changes': results1[i]['price_change_percentage_24h'], 'usd': results1[i]['current_price'], 'gbp': results2[i]['current_price'] } # print(crypto_dict['bitcoin']['coin_name']) = will show coin name class Portfolio(Values): def __init__(self, coin, holdings): self.coin = coin self.holdings = holdings def Get_User_Coins(self): continues = True coins_holdings = {} while (continues == False): coin = input("Enter the Coin Name i.e(Bitcoin(BTC) is bitcoin): ") holdings = input("Enter the amount of holdings of the coin: ") print("\n") # Attatch to the current user def Pull_Coin_Dat(Values): # 'burst': {'coin_name': 'Burst', 'changes': 10.4028903177228, 'usd': 0.00425861382756581, 'gbp': 0.00329588603402332}} print() lol = Portfolio('xrp', 600) lol.Pull_Coin_Dat() To be able to call crypto_dict located in Values class from Pull_Coin_Dat function. -
Django Transaction when open connection? @transaction.commit_manually @transaction.atomic
i want to know when is dbConnection opened for exampel as follow logic Does wait db Connection to external_api_call or not? @transaction.commit_manually def do_something(): # 1. now db connection open? # api_call response= requests.get(~~~~) # 2. or db connection opened here? aa= User.objects.get(id=1) -
Is there any way to bypass the server my Django site is hosted on when uploading files, and just immediately upload to S3 instead?
I am using boto3 to upload massive media files (2GB+) from my Django website to an s3 storage bucket. My issue is that when uploading a file larger than 2.5MB - the connection is immediately timed out and no debug information displays I assume what is happening is that Django is using the temporary file upload handler, but the temp file handler won't work on the server the Django app is running on (pythonanywhere free tier). This works flawlessly locally, because it just has to copy to the OS, not the server. I would like to skip the web server so I am not using all the storage/bandwidth s3.upload_file needs the local path of the file in order to be able to upload it to S3, the only way I could find to do that is grab the temp_path of the file. # method to chunk the upload process if file is over 2.4MB def s3_multipart_upload(f, video_id): # our server path file_path = "media/" new_folder = str(video_id)+"/" file_name = f.name server_path = file_path + new_folder + file_name # the file gets copied to ~/tmp/ so grab that path local_path = f.temporary_file_path() # create s3 client connection s3 = boto3.client('s3', settings.AWS_S3_REGION_NAME, …