Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
onclick="return confirm('Are you sure you want to delete?');" Not working
here confirm pop-up is coming with the question but when we cancel its going to the delete link and deleting the data. can u help me to do this (on cancel - go back) -
One to many relationship , How can I add data to a one to many relationship field?
How can I add data to a one to many relationship field? The model structures are given below I am having two models, an Admin model and other one is the App model. An app may have multiple admins (App 1- u1 , u2... as app admins) class Admin(models.Model): email = models.EmailField() class App(models.Model): platform = models.IntegerField() # 1-iOS, 2-ANDROID bundle = models.CharField(max_length=255) admin = models.ForeignKey(Admin, on_delete=models.SET_NULL, null=True) Tried of saving a list of admins to the app but, it is not working as expected with this model structure. -
How can implement mulitiple filters?
from django.db.models import Q from .models import Model qs = Model.objects.filter(Q(field_1=value1)&Q(field_2=value2)) I know how to form query_set but how can I link it with the front-end dynamically, so that I can know which filter option does the user chose? -
easy-thumbnails for Django not saving siles to S3
I have an install of an application which I've been asked to take over from another developer. I am saving media to an AWS S3 bucket and using easy-thumbnails. For some reason, my easy-thumbnails are giving 404 errors rather than creating the desired images. For example, within the html file I might have: <img class="carousel-thumbnail" src="{% thumbnail object.image 'carousel_thumbnail' subject_location=object.image.subject_location %}" alt="{{ object.image.url }}"> object.image exists but the thumbnail doesn't get created. Instead a 404 error is shown (in console). Within settings.py I have THUMBNAIL_DEFAULT_STORAGE = 'core.storage.MediaStorage' And MediaStorage is defined as: class MediaStorage(S3Boto3Storage): """ This is our default storage backend for all media in the system. DEFAULT_FILE_STORAGE expects a class and not an instance """ def __init__(self, *args, **kwargs): kwargs.setdefault('file_overwrite', False) kwargs.setdefault('url_protocol', 'https:') kwargs.setdefault('querystring_auth', False) kwargs.setdefault('location', get_storage_env('media')) kwargs.setdefault('default_acl', 'public-read') kwargs.setdefault('object_parameters', { 'CacheControl': 'max-age=31536000' }) super(MediaStorage, self).__init__(*args, **kwargs) def _save_content(self, obj, content, parameters): """ We create a clone of the content file as when this is passed to boto3 it wrongly closes the file upon upload where as the storage backend expects it to still be open """ # Seek our content back to the start content.seek(0, os.SEEK_SET) # Create a temporary file that will write to disk after a … -
Django-Rest TypeError: Object of type type is not JSON serializable
I am trying to post a date and time to a DateTimeField format however getting a TypeError: Object of type type is not JSON serializable error My serializer code is class DailyAnnotationSerializer(serializers.ModelSerializer): start_date = serializers.DateField( format="%Y-%m-%d", required=False, input_formats=["%Y-%m-%d"]) end_date = serializers.DateTimeField( format="%Y-%m-%dT%H:%M:%S.%f%z", required=False, input_formats=["%Y-%m-%dT%H:%M:%S.%f%z"]) class Meta: model = DailyAnnotation fields = ['start_date', 'end_date', and in postman I am posting start_date:2019-12-30 end_date:2019-12-31T20:02:05.123456+0900 view @api_view(['POST',]) def api_create_dailyannotation_view(request): account = User.objects.get(subject_id__exact=request.POST['subject_id_search']) daily_annotation = DailyAnnotation(subject_id=account) if request.method == "POST": serializer = DailyAnnotationSerializer(daily_annotation,data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) any help is appreciated! -
i am trying to create autogenerated username from email the user provides but the error is happening
i am trying to create autogenerated username from email the user provides but the error is happening. username = email.split('@')[0] user = UserProfile.objects.create( email=new_data['email'], mobile_no=new_data['mobile_number']) user.username = new_data[username] user.set_password(new_data['password']) user.is_active = True user.save( -
Getting AttributeError in Django
I am using Stripe for handling payments in my Django app. Whenever I try to fill dummy card credentials and submit, it gives the following error. AttributeError, 'Payment' object has no attribute 'save' I cannot figure out how to save the payment object in 'views.py'. I have successfully applied migrations in my app and have migrated it, but still I am getting this error. The following is my views.py from django.conf import settings from django.shortcuts import render, get_object_or_404 from django.views.generic import ListView, DetailView, View from django.utils import timezone from django.shortcuts import redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required import stripe from django.contrib import messages # token = stripe.api_key stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create-token # stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. from .models import Item, OrderItem, Order, BillingInformation, Payment from .forms import CheckoutForm # def home(request): # context = { # 'items': Item.objects.all() # } # return render(request,'home.html',context) class HomeView(ListView): model = Item template_name = 'home.html' class ItemDetails(DetailView): model = Item template_name = 'product.html' @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( order_item=item, user=request.user, is_ordered=False ) order_qs = Order.objects.filter(user=request.user, is_ordered=False) if order_qs.exists(): order = order_qs[0] print(order) if … -
How to start a background thread when django server is up?
TL;DR In my django project, where do I put my "start-a-thread" code to make a thread run as soon as the django server is up? First of all, Happy New Year Everyone! This is a question from a newbie so it might seem dumb. Thank you for your patience and help in advance! Background Information Recently I am writing a MQTT forwarding program which receives MQTT message. I'd like user to set some rules to handle messages to be forwarded so I chose django to build a web server. User can edit the rules themselves on the web page. For the MQTT client I need to have a thread to receive MQTT message no matter if the user opens a webpage or not, so I cannot write it in the view.py. If I write a shell to start django server and my script separately, I am not sure how to pass the users settings from django server to my mqtt client script. Question 1. Is there a way to start a background thread as soon as I typed python manage.py runserver? 2. One of the user settings is the MQTT server host, so once the user change this entry on … -
Django: How to represent MoneyField in Forms
I am using https://github.com/django-money/django-money for my currency. The problem is it doesnt show anything in the form. Here is how I have defined in the model.py from djmoney.models.fields import MoneyField class Product(models.Model): price = MoneyField(max_digits=10, decimal_places=2, default_currency='USD') And in the forms.py class ProductEditForm(forms.ModelForm): price = forms.DecimalField(max_digits=5, decimal_places=2) class Meta: model = Product fields = ("price") I am using Django 1.11 and postgreSQL 9.4 Should I use forms.MoneyField ? How can I solve this form so that the price is displayed ? -
requests.exceptions.ConnectTimeout during sending push notification by FCM in Django
I'm using fcm_django for push notification. mostly it works correctly but in CELERY log, I can see some error about connection timeout and Max retries exceeded with url, for example: Traceback (most recent call last): File "/home/backend/www/env/lib/python3.5/site-packages/celery/app/trace.py", line 375, in trace_task R = retval = fun(*args, **kwargs) File "/home/backend/www/env/lib/python3.5/site-packages/celery/app/trace.py", line 632, in __protected_call__ return self.run(*args, **kwargs) File "/home/backend/www/hamclaasy-backend/apps/notification/tasks.py", line 68, in send_message_to_users_by_id res = FCMDevice.objects.filter(**query_context).send_message(**kwargs) File "/home/backend/www/env/lib/python3.5/site-packages/fcm_django/models.py", line 77, in send_message **kwargs File "/home/backend/www/env/lib/python3.5/site-packages/fcm_django/fcm.py", line 343, in fcm_send_bulk_message **kwargs File "/home/backend/www/env/lib/python3.5/site-packages/pyfcm/fcm.py", line 269, in notify_multiple_devices self.send_request(payloads, timeout) File "/home/backend/www/env/lib/python3.5/site-packages/pyfcm/baseapi.py", line 220, in send_request response = self.do_request(payload, timeout) File "/home/backend/www/env/lib/python3.5/site-packages/pyfcm/baseapi.py", line 210, in do_request response = self.requests_session.post(self.FCM_END_POINT, data=payload, timeout=timeout) File "/home/backend/www/env/lib/python3.5/site-packages/requests/sessions.py", line 555, in post return self.request('POST', url, data=data, json=json, **kwargs) File "/home/backend/www/env/lib/python3.5/site-packages/requests/sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "/home/backend/www/env/lib/python3.5/site-packages/requests/sessions.py", line 618, in send r = adapter.send(request, **kwargs) File "/home/backend/www/env/lib/python3.5/site-packages/requests/adapters.py", line 521, in send raise ReadTimeout(e, request=request) requests.exceptions.ReadTimeout: HTTPConnectionPool(host='https://fcm.googleapis.com/fcm/send'): Read timed out. (read timeout=5) setting.py: FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": os.environ.get('FCM_SERVER_KEY') } FCM_MAX_DEVICE_PER_USER = 15 and here how sending notification: FCMDevice.objects.filter(**query_context).send_message(**kwargs) please notice that notification working almost well but about 1% of them execute error.is it usual?how can i fixi it? fcm-django==0.2.19 , Django==2.1.1 thank you. -
How to get SSL Certificate data while using Gunicorn?
I am using Gunicorn. I have passed the certificates while running the server. But Now, I want to access certificate data in my django application. How to access this certificate data? -
Django Problem: manage.py runserver erorr message
I'm coding my first django project with python3 and when I close my server I get this error message: I'm trying to figure it out but I can't find a solution. Please help. Thanks! ^CTraceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all connection.close() File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close if not self.is_in_memory_db(): File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 230, in close_all connection.close() File "/usr/local/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 261, in close if not self.is_in_memory_db(): File "/usr/local/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db … -
How to display Django model data in HTML table?
I have two models i.e Starttime and Stoptime that store the start time and stop time respectively. Right now, each registered user will have multiple instances of the start and stop time, like so: Name Start_time Stop_time Bobby Dec. 31, 2019, 5:39 a.m Dec. 31, 2019, 5:50 a.m Jan. 01, 2020, 9:00 a.m Jan. 01, 2020, 18:00 a.m Jan. 02, 2020, 6:00 a.m Jan. 02, 2020, 19:00 a.m ... ... Tina Dec. 31, 2019, 9:00 a.m Dec. 31, 2019, 10:00 a.m Dec. 31, 2019, 12:00 p.m Dec. 31, 2019, 15:00 p.m Jan. 01, 2020, 9:00 a.m Jan. 01, 2020, 11:00 a.m Jan. 02, 2020, 5:00 a.m Jan. 02, 2020, 9:00 a.m Jan. 02, 2020, 10:00 a.m Jan. 02, 2020, 12:00 a.m ... ... I want to display my data exactly like this within the HTML table. models.py: class Starttime(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) start_time = models.DateTimeField() class Stoptime(models.Model): user_id= models.ForeignKey(User, on_delete = models.CASCADE) stop_time = models.DateTimeField() views.py: #Right now, I am accessing only the latest values from both the models. However, I want to display all of them neatly in my HTML table. def interface(request): data = User.objects.filter(pk__gt=1) #All users apart from the SuperUser admin store_data = [] for … -
Django mailbox refresh button in template
I'm using django-mailbox in my app. It work but it sync mail by "python manage.py getmail" in shell. Now my goal is refresh new incoming mail by html template. There is a way? TY -
How to dump the context in the templates?
How can I print all the keys in the context? For example I have a view like this: def home(request): return render(request, 'home.html', context={ 'first_name': 'Umut', 'last_name': 'Coşkun' }) How can I print all the context in the template? I'm searching for something like: {{ all_the_context }} And it will print: { "first_name": "Umut", "last_name": "Coşkun" } Or if its an object instead of JSON, it's also okay. -
MPESA C2B Validation and Confirmation Transaction Not Responding
I am trying to record confirmed mpesa transactions. I am running them on the safaricom sandbox. My register url function and simulate_transaction both return success from my local terminal. However, I have hosted by app on heroku and the logs on there do not show any kind of response (I have function-based views with code to print out both transactions.) My c2b.py: import keys import requests from requests.auth import HTTPBasicAuth # import lipanampesa # Getting MPESA Access Token consumer_key = keys.consumer_key consumer_secret = keys.consumer_secret api_URL = "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials" try: r = requests.get(api_URL, auth=HTTPBasicAuth( consumer_key, consumer_secret)) except: r = requests.get(api_URL, auth=HTTPBasicAuth( consumer_key, consumer_secret), verify=False) print(r.json()) json_response = r.json() my_access_token = json_response["access_token"] def register_url(): access_token = my_access_token # lipanampesa.my_access_token # my_access_token api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl" headers = {"Authorization": "Bearer %s" % access_token} request = {"ShortCode": keys.shortcode, "ResponseType": "Completed", "ConfirmationURL": "https://sheltered-river-94769.herokuapp.com/api/payments/C2B-CONFIRMATION/", "ValidationURL": "https://sheltered-river-94769.herokuapp.com/api/payments/C2B-VALIDATION/", } try: response = requests.post(api_url, json=request, headers=headers) except: response = requests.post( api_url, json=request, headers=headers, verify=False) print(response.text) register_url() def simulate_c2btransaction(): access_token = my_access_token api_url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate" headers = {"Authorization": "Bearer %s" % access_token} request = {"ShortCode": keys.shortcode, # "CustomerPayBillOnline", # CustomerBuyGoodsOnline "CommandID": "CustomerPayBillOnline", "Amount": "50", # phone_number sendng the trxn, starting with Xtrycode minus plus (+) sign "Msisdn": keys.test_msisdn, "BillRefNumber": "123456789", } try: … -
How to remove the square bracket from the python lists
While writing an Html file from a text file, square brackets like below are occurring which we want to remove. <tr><td><a href=['http://www.ubuntu.com/']></a></td></tr> <tr><td><a href=['http://wiki.ubuntu.com/']></a></td></tr> Following is the code through which writing an Html file: for lines in contents.readlines(): if lines.strip(): e.write("\t"+"<tr><td><a href=%s></a></td></tr>\n"%lines.split()) Not getting any idea to remove square brackets from the above code. Can someone help us out, please? -
django.core.exceptions.ImproperlyConfigured: Django 3.0.1 is not supported
This Django project is working before I created another Django project on my computer. But today when I run the project it shows error message like that=> Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\options.py", line 208, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 207, in __getitem__ backend = load_backend(db['ENGINE']) File "Users..\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 111, in load_backend return import_module('%s.base' … -
REQUEST certain Elements in Django POST API from User
I want to Request a dictionary like { "username": "a", "password": "b", "year": "2019-20", "start": 1, "end": 2, "reference_id": "two" } from a user so that a user can hit the API and get the desired result. My view looks like def post(self,request, *args, **kwargs): # self.http_method_names.append("post") user = request.POST.get("user") pasd = request.POST.get("pasd") year = request.POST.get("year") start = request.POST.get("start") end = request.POST.get("end") reference_id = request.POST.get("reference_id") #Passing the parameters to another function to get the result. status = main_function(user=user,pasd=pasd,year=year,start=start,end=end,reference_id=reference_id) return Response(status) Now the Problem when I'm posting something in django like I'm getting None in every field. Ideally I should get the values passed in the Dictionary. Can Someone please help here. -
How to Response a big file in python/Django with Resume/Stop/Continue
I used the following code to send large files in Python/Django But these codes cannot be resumed/stop/continue . now How can I implement resume capability? And if I don't want to use FileWrapper, how can I implement these codes from django.shortcuts import render import os, tempfile import mimetypes from django.http import StreamingHttpResponse from wsgiref.util import FileWrapper from django.conf import settings def downloadfile(request): path = path = settings.BASE_DIR + '\\files\\SkinPack.zip' filename = os.path.basename(path) chunk_size = 8192 # temp = tempfile.TemporaryFile() response = StreamingHttpResponse(FileWrapper(open(path, 'rb'), chunk_size), content_type=mimetypes.guess_type(path)[0]) response['Content-Length'] = os.path.getsize(path) response['Content-Disposition'] = "attachment; filename=%s" % filename return response -
How to send self expired 1 time email in django?
I want to send email to a user which will expire in a certain period of time after user accepts the email link which will be one time executed.Currently i am using smtp to send simple mails.Here is my email code: ``` class SendMail(object): @staticmethod def send_mail(subject, message, recipient_list): email, created = MailSettings.objects.get_or_create(id=1) email_server = email.mail_server email_port = email.mail_port email_username = email.username email_password = email.password email_ssl = email.use_ssl connection = get_connection(host=email_server, port=email_port, username=email_username, password=email_password, use_ssl=email_ssl) send = send_mail(subject=subject, message=message, from_email=email_username, recipient_list=recipient_list, connection=connection, fail_silently=True) success = 200 return success i am using above code in my emails.py and importing it in views.py and then i am calling this function something like this sendmail = SendMail.html_send_mail(subject='invite', message='Welcome', recipient_list=email) -
Openstack swift gateway time-out issue
I wanna ask about gateway time out issue in openstack-swift problem I'm using python-swiftclient 3.3.0 / mongod 2.6 I tried copying lots of files by celery-task to swift But it returns 504 Gateway Timeout issue with following logs { "_id" : ObjectId("5e0aa59ae5274a148fbb6904"), "taskid" : "c23e3f29bd598adf40a52abbc532c6f5bad0e103bf3587123a78f34ccacef04dfa8702d7fa97305f68395c3ab8621cb01b045b48d9b5748e521c43eb5a651683", "result" : { "error" : "error Object COPY failed: https://storage.local.com/v1/AUTH_sample/sample/1688_2b8ccf6b47c9401789c080fcb4a60ed5 504 Gateway Time-out [first 60 chars of response] <html><body><h1>504 Gateway Time-out</h1>\nThe server didn't " }, "created" : ISODate("2019-12-31T01:34:18.652Z"), "ended" : ISODate("2019-12-31T01:41:26.147Z") } But in swift log it returns 200 when it copying some files /etc/swift/swift.log Dec 31 10:42:57 storage1 object-server: 100.123.234.567 - - [31/Dec/2019:01:42:57 +0000] "GET /swift0/2501AUTH_sample/sample/1688_2b8ccf6b47c9401789c080fcb4a60ed5/000000160" 200 6291456 "GET https://storage.local.com/v1/AUTH_sample/sample/1688_2b8ccf6b47c9401789c080fcb4a60ed5/000000160?multipartmanifest=get" "tx77808ae515de403e83f8d-005e0aa70a" "proxy-server 5096" 0.0006 "-" 2800 0 Dec 31 10:42:57 storage1 object-server: 100.123.234.567 - - [31/Dec/2019:01:42:57 +0000] "GET /swift0/2501AUTH_sample/sample/1688_2b8ccf6b47c9401789c080fcb4a60ed5/000000160" 200 6291456 "GET https://storage.local.com/v1/AUTH_sample/sample/1688_2b8ccf6b47c9401789c080fcb4a60ed5/000000160?multipartmanifest=get" "tx77808ae515de403e83f8d-005e0aa70a" "proxy-server 5096" 0.0006 "-" 2800 0 and it was okay when copying a small number of files { "_id" : ObjectId("5e0ab911ed915d7ca9acb626"), "taskid" :"0358f4d228faaf9ec94be1908969b0f29d78fd1e8b7a64cf474a623ec4ab55808759c04130d3e74fa37e67b437a5e7d458358562e66c25f849b25c578d206323", "name" : "migrate_homefs", "params" : { "src_path" : "/home/transfers/test/okokokok", "cleanup" : true, "src_id" : 149, "dst_id" : 1688, "dst_path" : "/home/ts/sample2/okokokok" }, "result" : { "dst_path" : "/home/ts/sample2/okokokok", "dst_id" : 1688 }, "created" : ISODate("2019-12-31T02:57:21.192Z"), "ended" : ISODate("2019-12-31T02:58:19.781Z") } It is using same API but when copying … -
Django - How to edit and submit multiple forms individually then render back to the same page?
So I'm building this learning log app where users can create multiple topics. I'm trying to create a single page where users can edit/save changes/delete their topic names. My logic in the edit_topic view function is to display the original topics in forms with save and delete button, code below: views.py def edit_topics(request, topic_pk=None): '''edit existing topics mainly the names''' # modify the model data according to the request method and name if request.method == 'POST' and topic_pk != None: if 'save' in request.POST: topic_to_change = get_object_or_404(Topic, pk=topic_pk) form = TopicForm(instance=topic_to_change, data=request.POST) if form.is_valid(): form.save() elif 'delete' in request.POST: topic_to_delete = get_object_or_404(Topic, pk=topic_pk) topic_to_delete.delete() return redirect('learning_log/edit_topics.html') # get the original/modified data passing to render topics = Topic.objects.all() topic_lst = [] for topic in topics: form = TopicForm(instance=topic) topic_lst.append(form) context = {'topics': topics, 'topic_lst': topic_lst} return render(request, 'learning_logs/edit_topics.html', context) edit_topics.html {% extends 'learning_logs/base.html' %} {% block content %} <section class="container"> <h3>Topics you have created</h3> <ul class=""> {% for form in topic_lst %} <li class="mb-5"> <form class="d-flex align-items-center" action="{% url 'learning_logs:edit_topics' form.instance.pk %}" method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-primary" name="submit">save</button> <button class="btn btn-danger" name="delete">delete</button> </form> </li> {% endfor %} </ul> <a class="btn btn-info" href="{% url 'learning_logs:topics' %}">Done</a> </section> … -
What is the format for PointField in a django fixture?
Suppose I have the following django model: from django.db import models from django.contrib.gis.db import models class Location(models.Model): name = models.CharField(max_length=200) point = models.PointField() And I want to load the PointField from a fixture. What is the format of the point field for a json fixture? [ { "model": "myapp.Location", "pk": 1, "fields": { "name": "Location Number 1", "point": "???", } } ] -
Django Files and User interaction
I am doing a app for patients get their exams. Every user will have a file that only they can have access to. How can I do this link between User and File. I had created a model to represent the data of the exam class Exames(models.Model): title = models.CharField(max_length=50) patient = models.CharField(max_length=50) exame_pdf = models.FileField(upload_to='uploads/') def __str__(self): return self.title +" "+self.paciente