Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Stop Celery Job to get triggered at every deployment on AWS
I am usingCelery in Docker container deployed on AWS for some asynchronous jobs scheduling withRedis as the broker. Here is my config in settings.py. All is working well. My only issue is the the job is getting triggered at every deployment even though I have set specific times for it. Otherwise after the deployment it works fine. I am scratching my head to stop the first triggering. settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_BEAT_SCHEDULE = { "fill_db_daily": { "task": "agendanotification.tasks.fill_db_daily", "schedule": crontab(hour=0, minute=1), }, "articles_email_daily": { "task": "agendanotification.tasks.articles_email_daily_prod", "schedule": crontab(hour=0, minute=30), } } In tasks.py: @shared_task def fill_db_daily(): call_command("fill_db", ) @shared_task def articles_email_daily_prod(): call_command("articles_email_prod", ) -
500 error when deploying Django app to Heroku with no obvious error messages
I am trying to deploy my Django app via Heroku and keep receiving a 500 error. I'm new to Django so am not really sure what could be going wrong as I've followed a tutorial online pretty closely, but I've obviously mucked something up somewhere. I've looked at the logs and it doesn't really tell me anything... at least nothing that I can decipher. Thanks to anyone who's able to translate this into English. 2021-03-24T11:09:44.413513+00:00 heroku[web.1]: State changed from starting to up 2021-03-24T11:09:47.222339+00:00 heroku[router]: at=info method=GET path="/" host=thediamondseeker-2.herokuapp.com request_id=19a272b0-7efa-43d5-bbd1-8e28a70cb43a fwd="94.1.111.13" dyno=web.1 connect=1ms service=985ms status=500 bytes=410 protocol=https 2021-03-24T11:09:47.218908+00:00 app[web.1]: 10.29.126.3 - - [24/Mar/2021:11:09:47 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" This is my settings.py """ Django settings for diamonds project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production … -
Authorization Headers is missing using c# client
I am developing a RESTFUL API using django-rest-framework. And for Authorization I choose to use Token Authorization (not JWT). Below is what I tried: Using POSTMAN (Works) headers: Authorization: Token 329367424fd30a876ccff05dbc5a18d86fe7158c Using C# Client (no working) HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Token 329367424fd30a876ccff05dbc5a18d86fe7158c"); await client.GetAsync(<url>) // Authentication credentials were not provided. After I debug and override TokenAuthentication function, I realize that Authorization headers is being removed if requested from C# Client. I saw a lot of question are being asked related to this problem, and the solution is adding WSGIPassAuthorization On I am not sure where should I add above line wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nusames_core.settings') application = get_wsgi_application() FYI: I am planning to use gunicorn as my webserver, also I need it work locally (I am not using venv) Question: is there any workaround for my local env in order to make it works on c# client, and is there any best practice for production env? -
AttendanceRange matching query does not exist in django
Traceback (most recent call last): File "D:\Apps\Python\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Apps\Python\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-pack`enter code here`ages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1581, in _changeform_view self.save_related(request, form, formsets, not add) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1121, in save_related self.save_formset(request, form, formset, change=change) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1109, in save_formset formset.save() File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 673, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 811, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 951, in save_new return super().save_new(form, commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 650, in save_new return form.save(commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 460, in save self.instance.save() File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 801, in save_base post_save.send( File "D:\Apps\Python\lib\site-packages\django\dispatch\dispatcher.py", line 177, in … -
Embedded Google Analytics API but not showing property and views and other data
I have embedded google analytics API using https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started. I am testing it on localhost, I have successfully embedded the GA API but it is not populating any data. plz check the image -
Checking if the .csv file is formatted correctly before importing to avoid embedding wrong data into database
I am working on a django project that requires updating database with bulk data provided in an excelsheet format. So basically, a user can upload a .csv file if it is in a correct format. I know how to import a file using django-import-export, but the problem is , i don't know how to perform checks like checking if the .csv file has correct column names and information before updating database. I am new to django, please help. -
Django model formset is not saving data to backend db
I am trying to save data using modelformset_factory but i am unavle to do so, i am wondering why? Here is my views.py views.py if request.POST: try: user_info = Education.objects.filter(applicantt= applicant_info).first() formset = educationformset(request.POST, instance=user_info) if formset.is_valid(): print(formset.cleaned_data) for form in formset: obj = form.save(commit=False) obj.id = user_info obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset except: formset = educationformset(request.POST) if formset.is_valid(): for form in formset: obj = form.save(commit=False) obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset This the template i am using.... template <form method="POST" class="">{% csrf_token %} {{ education_form.management_form}} {% for form in education_form %} <table class="table table-bordered" cellspacing="0" > <thead id="head"> <tr> {% for field in form.visible_fields %} <th >{{field.label}}</th> {% endfor %} </tr> </thead> <tbody id="head"> <tr > {% for field in form.visible_fields %} <th>{{field}}</th> {% if error in field.errors %} <small id="" class="text-danger"> {{error}} </small> {% endif %} {% endfor %} </tr> </tbody> </table> {% endfor %} <div class="card-block"> <button type="submit" class="btn btn-success center-block pull-right" href="{% url 'test' %}">Finish</button> </div> </form> and finally this is my model.py which i am using for the project.... models.py class Education(models.Model): LEVEL = [ ('Matric','Matric'), ('Intermediate','Intermediate'), ('Graduation','Graduation'), ('Master','Master'), ('Doctrate','Doctrate'), ] applicantt = models.ForeignKey(Personal, on_delete=models.CASCADE, unique=False) … -
How to add data to different table using signals?
In my invoicing app, when client make payment, i create new clientpayment with date and client name and amount paid, and in clientpaymentitem i choose one or many invoices that client paid and put the amount_paid on each line and where the money is stored, in bank or cashier. i can receive cash and check for example and then i select treasury.cashier for invoice paid on cash and the other paid with check same way treasury.bank. now i want when i save the clientpayment that this transaction will be saved on treasury on same time, no need to repeate the whole things. I tried to use signals but didn't work correctly for me in case i modify the amount for ex. class ClientPayment(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total_paid = models.DecimalField(default=0, max_digits=20, blank=True, null=True, decimal_places=2) class ClientPaymentItem(models.Model): clientpayment = models.ForeignKey('ClientPayment', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.PROTECT) amount_paid = models.DecimalField(max_digits=20, decimal_places=2) treasury = models.ForeignKey('Treasury', on_delete=models.PROTECT) class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, default=0) credit = models.DecimalField(max_digits=20, decimal_places=2, default=0) -
Django: TypeError: post() missing 1 required positional argument: 'request'
I am getting below error when I pass the invalid credentials. TypeError: post() missing 1 required positional argument: 'request' I don't understand it. Here is the view. View: class LogInView(TemplateView): template_name = "login.html" @staticmethod def post(self, request, *args, **kwargs): username_or_email = request.POST['username'] password = request.POST['password'] if '@' in username_or_email: username = User.objects.get(email=username_or_email).username else: username = username_or_email if username and password: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/admin') else: messages.warning(request, 'Sorry, wrong username or password.') return render(request, self.template_name) else: messages.warning(request, 'Username and Password cannot be blank.') return render(request, self.template_name) Here is the url. Url: from django.urls import path, include from sa.views import ( LandingPageView, LogInView, LogOutView, ) urlpatterns = [ path('', LandingPageView.as_view(), name='LandingPageView'), path('login', LogInView.as_view(), name='LogInView'), path('logout', LogOutView.as_view(), name='LogOutView'), ] Please help. -
'tensorflow' has no attribute 'get_default_session'
I am currently working on a project using DJANGO KERAS and TENSORFLOW But I am really facing some issues while executing the project I even reinstalled DJANGO KERAS and TENSORFLOW but I still face these issues I have also added the screenshots of the error message Please help me to solve the issueenter image description here [Command Prompt][Webpage] default_session = tf.get_default_session() AttributeError: module 'tensorflow' has no attribute 'get_default_session' -
How to show breaklines in textarea and data fetch from JavaScript to My inner Text of textarea
I want to get data from user in <textarea> and show it on the DOM page with edit button and with breaklines if user click on edit user old data send to new <textarea> with breaklines Adding an item. <form name="add" method="POST" action="{% url 'notepad:addnote' %}">{% csrf_token %} <div class="modal-body"> Title : <input name="title" class="w-50" type="text" required><br> Note :<br> <textarea name="text" id="" cols="60" rows="10" required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> Showing an items. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li> </ul> {% endfor %} </div> But if i show an items it removes break lines. So I'll try pre tag to show that content with breaklines. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <pre><li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li></pre> </ul> {% endfor %} </div> It shows break lines, but i again want to edit and send this content to my input and textarea to edit that's content , So i … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead
When i try to post a order i get error saying 'Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead.' Any help would be great. here is my models.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) food_item = models.ForeignKey(FoodItem,on_delete=models.CASCADE) quantity = models.IntegerField(default=0,null=True,blank=True) size = models.CharField(max_length=10,choices=SIZE_CHOICES,null=True,blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.food_item}' class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) order = models.ManyToManyField(OrderItem,null=True) order_created = models.DateTimeField(auto_now_add=True) paid = models.BooleanField(default=False,null=True,blank=True) transction_id = models.CharField(max_length=30,unique=True,null=True,blank=True) def __str__(self): return self.user.username Here is my serializer.py class OrderItemListSerializer(serializers.ModelSerializer): #user = UserSerializer(many=True,read_only=False) class Meta: model = OrderItem fields = ['id','user','food_item','quantity','size'] def create(self,validated_data): return OrderItem.objects.create(**validated_data) class OrdersSerializer(serializers.ModelSerializer): order = OrderItemListSerializer(many=True,) class Meta: model = Order fields = '__all__' depth = 0 # def create(self, validated_data): def create(self,validated_data): return Order.objects.create(**validated_data) here is my views.py class OrderPost(APIView): # add permission to check if user is authenticated permission_classes = [permissions.AllowAny] # 2. Create def post(self, request, *args, **kwargs): serializer = OrdersSerializer(data=request.data) serializer.set(order) 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) error Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead. -
Payments on website: From customers to the website and vice versa
I am creating a website that needs to do this points: Receive payments to the Web site. I know that there are several payments gateways to do this. Can anyone recommend any? Make payments from the Web site to the people who are registered on the site. This people can live in any country and so they can have accounts in any bank of the world. It's possible to make bank transfers to any bank? There's another way to do it, for example with PayPal? If anyone has another idea how to do this I would be very grateful if you tell me. Without having this resolved I cannot move forward on my website. My Web site uses: HTML, CSS, Bootstrap, Jquery, Django y Python, with a SQLLite database. Thanks. -
How can i run a Django app and a Vue on the same port?
I'm building a SPA using Django for my backend and Vue to handle the entire frontend. In order to avoid some security issue and keep using the standard Django's session authentication, i'm going to run these two apps in production on the same sever and on the same port, and i will setup Nginx to route traffic, so that /account/login will be handled by Django, while /app/someURL is redirected to the Vue application. My question is: how can i do the same locally, during development? If i run manage.py runserver and npm run serve -- ---port 8000 the two apps will clash because there is no way to know where should each request be redirected. -
Django multithread database update
how do you guys handle database update when running a multithread? When I call download_image function and perform operation, it hangs after the last line to update Django ImageField for newly created thumbnail, any clue? def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: for indi_image in all_images_without_thumbnail: executor.submit(download_image, indi_image) def download_image(indi_image): image = Image.objects.get(pk = indi_image_id) image_request_result = requests.get(image.url) img_temp = PilImage.open(BytesIO(image_request_result.content)) width, height = img_temp.size max_size = [200, 200] if width > 200 or height > 200: img_temp.thumbnail(max_size) image_io = BytesIO() img_temp.save(image_io, format='JPEG') filename = image.key.split('/')[-1] file_location = os.path.join(str(image.data_set_id), filename) image.thumbnail.save(file_location, ContentFile(image_io.getvalue()), save=True) print ("here it never reach this line, only hang and no Error or Exception raised") -
Resct- Danjo REST framework: Unable to post data to a model with foreign key
I am new to Django and doing my first project. What I am unable to do is send some data to model which has a foreign key field. Here is models.py: class BasketProductMapping(models.Model): product_reference = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='%(class)s_product_name') mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) basket_product_mapping_date = models.DateField(auto_now_add=True) basket_product_mapping_modified_date = models.DateField(auto_now=True) def __str__(self): return self.mapped_basket_name Here is my serializers.py file: class BasketProductMappingSerializer(serializers.ModelSerializer): product_reference = ProductSerializer(read_only=False) class Meta: model = BasketProductMapping fields = ('id', 'mapped_basket_name', 'mapped_product_name', 'product_reference') Here is my views.py: class BasketProductViewSet(APIView): def get(self, request): if request.GET.get('id'): #print('Basket Product Mapping Details') basketProductMappingData = BasketProductMapping.get(id = request.GET.get('id')) serializer = BasketProductMappingSerializer(basketProductMappingData) else: print('Basket Product Mapping Details') basketProductMappingData = BasketProductMapping.objects.all() serializer = BasketProductMappingSerializer(basketProductMappingData, many=True) response = {'status':1, 'message':"Basket Product Mapping List", 'data':serializer.data} return JsonResponse(response, safe=False) def post(self, request): data = request.data print(data) serializerData = '' saveBasketProductMapping = BasketProductMappingSerializer(data = data) if saveBasketProductMapping.is_valid(): print('Valid data') saveBasketProductMapping.save() serializerData = saveBasketProductMapping.data satusResponse = status.HTTP_201_CREATED else: print('Invalid Data') serializerData = saveBasketProductMapping.errors statusResponse = status.HTTP_400_BAD_REQUEST response = {'status': 1, 'message': 'Basket Product Mapping created successfully', 'statusResponse':statusResponse, 'serializerData':serializerData} return JsonResponse(response, safe=False) I am receiving the data from a POST request in this format: <QueryDict: {'mapped_basket_name': ['B3'], 'mapped_product_name': ['XYZ'], 'product_reference': ['XYZ']}> However, the data is not … -
OSError: dlopen(/opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/Darwin/libepanet22_win32.dylib, 6): image not found
I updated billiard,celery,kombu,amqp : nothing worked, Please help me resolve this. I am trying to use https://wntr.readthedocs.io/ OSError Traceback (most recent call last) <ipython-input-9-6ccee6a8a438> in <module> 1 # Simulate hydraulics 2 sim = wntr.sim.EpanetSimulator(wn) ----> 3 results = sim.run_sim() /opt/anaconda3/lib/python3.8/site-packages/wntr/sim/epanet.py in run_sim(self, file_prefix, save_hyd, use_hyd, hydfile, version) 94 inpfile = file_prefix + '.inp' 95 self._wn.write_inpfile(inpfile, units=self._wn.options.hydraulic.inpfile_units, version=version) ---> 96 enData = wntr.epanet.toolkit.ENepanet(version=version) 97 rptfile = file_prefix + '.rpt' 98 outfile = file_prefix + '.bin' /opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/toolkit.py in __init__(self, inpfile, rptfile, binfile, version) 155 except Exception as E1: 156 if lib == libnames[-1]: --> 157 raise E1 158 pass 159 return /opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/toolkit.py in __init__(self, inpfile, rptfile, binfile, version) 148 elif sys.platform in ['darwin']: 149 libepanet = resource_filename(epanet_toolkit,'Darwin/lib%s.dylib' % lib) --> 150 self.ENlib = ctypes.cdll.LoadLibrary(libepanet) 151 else: 152 libepanet = resource_filename(epanet_toolkit,'Linux/lib%s.so' % lib) /opt/anaconda3/lib/python3.8/ctypes/__init__.py in LoadLibrary(self, name) 457 458 def LoadLibrary(self, name): --> 459 return self._dlltype(name) 460 461 cdll = LibraryLoader(CDLL) /opt/anaconda3/lib/python3.8/ctypes/__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error, winmode) 379 380 if handle is None: --> 381 self._handle = _dlopen(self._name, mode) 382 else: 383 self._handle = handle OSError: dlopen(/opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/Darwin/libepanet22_win32.dylib, 6): image not found Everything worked earlier. I am using MacOS Sierra 10.13.6 -
ValueError: operands could not be broadcast together with shapes (32,31) (32,29)
import numpy as np TODO: divide error by respective number of instances for normalization def costfunction(params,Y, R, num_students, num_courses, num_features, reg_param, reg_param2, OrigTheta): # X is courses*features # Theta is students*parameters X = np.reshape(params[:num_courses * num_features], (num_courses, num_features), order='F') Theta = np.reshape(params[num_courses * num_features:], (num_students, num_features), order='F') # Take dot product of theta and x transpose to compute predicted rating # Compute squared error squared_error = np.power(np.dot(Theta, X.T) - Y, 2) # Contribution to squared error will come only from those ratings which # are not missing and which have not been relocated to test data J = (1 / 2.) * np.sum(squared_error * R) #Add contribution of theta and x to objective funciton incorporating the regularization parameter J = J + (reg_param / 2.) * (np.sum(np.power(Theta, 2)) + np.sum(np.power(X, 2))) # Limit the value of new theta close to original theta J = J + (reg_param2 / 2.) * (np.sum(np.power(Theta - OrigTheta,2))) X_grad = np.dot(Theta.T, (np.dot(Theta, X.T) - Y) * R).T Theta_grad = np.dot(((np.dot(Theta, X.T) - Y) * R), X) X_grad = X_grad + reg_param * X Theta_grad = Theta_grad + reg_param * Theta + reg_param2 * (Theta - OrigTheta) grad = np.concatenate((X_grad.reshape(X_grad.size, order='F'), Theta_grad.reshape(Theta_grad.size, order='F'))) return J , … -
Why is django-cleanup deleting used media files?
I have django-cleanup installed on my project, and I've ran into a bug where anytime I upload an image with the same name as another image already in the media folder, the old image is deleted and the new image is saved, but with new string on the end of it. This means I am losing used images when an image of the same name is uploaded. For example if I have image.jpg and I upload another image called image.jpg, the original image.jpg is deleted and the new one is saved as something like image_tccwtVY.jpg. I've implemented this in previous projects the exact same way (and version) and never had an issue. Can anyone think as to why it is doing this? -
What happens if I put same SECRET_KEY for my django 3 (app.com, portal.app.com , code.app.com) different projects
I was working on a project that have 2 sub-domains. Lets Understand with example I have 3 domains http://127.0.0.1:8000/ # This project is for api.my-domain.com http://127.0.0.1:8002/ # This project is for my-domain.com http://127.0.0.1:8003/ # This project is for account.my-domain.com at the initial stage I was stuck at accessing Logged In/out user from portal project in other project. like payoneer do: => we login at http://login.payoneer.com, But the same (Logged in) account we can access in http://myaccount.payoneer.com/ I was stuck at session authentication to get logged user. Then i try on myself to change secret key. I put the same secret key for all my domains . e.g. Let's Assume this is my secret key in django SECRET_KEY = "ehs-345asf4512*$^&__SH-35asdf43" i set this secret key in settings.py for http://127.0.0.1:8000/ I also set this secret_key in settings.py for http://127.0.0.1:8002/ I also set this same secret_key in settings.py for http://127.0.0.1:8003/ Then i was able to access Logged in/Out user from my http://127.0.0.1:8000/ project to another projects MY Question is that what happens if i put same SECRET_KEY for all my sub-domains on this domain? Is there any other way to get logged in/out user from my project. i am gonna work on android … -
How can I connect my pre-existing python script to Django
I am currently working on an Automated Machine Learning App, and my pipelines are implemented in python. Now that I need to move to the platform in Django, I'm finding difficulties to use my preexisting functions for the requests. (I am still very new to Django and was only able to configure the template which is the main page) I read about its MTV architecture and do understand the logic. My ML pipelines are currently called through my 'main.py' file and I need to shift this to the web app. -
How to turn off logging for SqlAlchemy db pool only, when debugging is enabled in Python Django?
Context / environment I have a Python Django project connecting to a PostgreSQL database with a SqlAlchemy django-postgrespool2 db pool. What I'm trying to achieve In settings.py I have set DEBUG = True which will make the program log. However, I want to disable the logging coming from the SqlAlchemy db pool only, while having DEBUG set to True. In other words, when debugging, I want to see all logs except for the ones coming from the SqlAlchemy db pool. What I've tested The code below shows too different attempts I've made to disable the db pool logging: def turnOffLog(self): # --- Attempt 1, db pool logs still show --- logging.basicConfig() logging.getLogger('sqlalchemy').setLevel(logging.ERROR) # --- Attempt 2, db pool logs still show --- sqla_logger = logging.getLogger('sqlalchemy.engine.base.Engine') for hdlr in sqla_logger.handlers: sqla_logger.removeHandler(hdlr) I also pass echo=False to the QueuePool instance when I create it, which still doesn't remove the logs: dbPool = pool.QueuePool(dbConnection, max_overflow=dbConfig.poolMaxOverflow, pool_size=dbConfig.poolSize, recycle=dbConfig.poolRecycleTime, pre_ping=dbConfig.prePing, dialect=postgresql.dialect(), echo=False) My settings.py file (DEBUG is set to True from an env-config file): """ Mbrain """ import os import logging import socket import sys from decouple import Config, RepositoryEnv import time # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
DRF post method working without csrf token. Is it safe?
Before working with drf, i knew that, we need to add csrf token to submit the form data. But in django-rest-framework POST method working without csrf token. Is it safe? createGroup=()=>{ let store = JSON.parse(localStorage.getItem('login')) var url = 'http://127.0.0.1:8000/myapi/creategroup/' fetch(url,{ method:'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token, }, body:JSON.stringify({ 'name':this.state.groupName, }) }) .then((response)=>{ response.json() document.getElementById('i').value='' this.setState({groupName:''}) }) } -
How to reject login when user already has a session in django
In my django application I want to reject a user login if he has already an active session. How can I do that? I tried some attempts using user_logged_in signals. Should I do this check login form with confirm_login_allowed() before new session creation? My current setup is like that: accounts/signals.py @receiver(user_logged_in) def check_existing_session(sender, user, request, **kwargs): session_key = request.session.session_key user.set_session_key(session_key) accounts/models.py def set_session_key(self, key): self.last_session_key = key self.save() -
Enable Partial/Free/Full text search on a unique column PostgreSQL
I have a unique column inside the table of type citext (at Django model level CICharField). colName = CICharField(max_length=255, unique=True) This column has a unique constraint(index) enabled. UNIQUE CONSTRAINT, btree (colName). I have a case where I want to perform a partial/full/free text search on this column using %LIKE%. Now since this already has a unique constraint index enabled on this column, is there a way to create another index that can be used by %LIKE% query to improve the performance? I understand that only 1 index can be used at once but I was just wondering if there is any workaround to improve this a little more. I'm using Django ORM, which provides __contains attribute, that can be used to perform %LIKE% queries. Since it's a citext type column, I can't use the search attribute provided by Django. https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/search/ I guess adding db_index=True wouldn't help either.