Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django settings module is defined but still not working
What I am essentially trying to do is generate problems and connect those problems to a model, The generation part worked perfectly but until I tried to update the generated values to a model, I keep getting the error django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried calling settings.configure() in wsgi.py and manage.py but no luck. I already have DJANGO_SETTINGS_MODULE defined in wsgi.py and even in the script, I have it defined as well using. I also tried adding the variable using shell and used Django-admin but still had no luck os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'QuickChemistry.settings') Here is a picture of my project tree: I believe that the error is coming from the actual script itself which was working perfectly before, but when I tried to add it to a model is when this error occurred. This error happens whenever I run django_compounds.py. Here is the django_compounds.py file in a hastebin since it is fairly long https://www.toptal.com/developers/hastebin/umesotedir.py -
I have a trouble using win32com in DJango
I made a python module getting stock infomation and making DataFrame from another window Application by win32com. I can get stock infomation well at first call. but i can't get stock infomation by win32com in succession. and error code is not given. myModule.py import json import pandas as pd import win32com.client import pythoncom def getStock(code, name, startDay): pythoncom.CoInitialize() cpOhlc = win32com.client.Dispatch('CpSysDib.StockChart') today = datetime.today() _startDay = datetime.strptime(startDay, '%Y%m%d') dif = today - _startDay qcy = math.trunc(int(dif.days)) cpOhlc.SetInputVAlue(0, code) cpOhlc.SetInputVAlue(1, ord('2')) cpOhlc.SetInputVAlue(4, qcy) cpOhlc.SetInputVAlue(5, [0,5]) cpOhlc.SetInputVAlue(6, ord('D')) cpOhlc.SetInputVAlue(9, ord('1')) cpOhlc.BlockRequest() count = cpOhlc.GetHeaderValue(3) data = [] date = [] for i in reversed(range(count)): __date = str(cpOhlc.GetDataValue(0,i)) _date = pd.Timestamp( year=int(__date[0:4]), month=int(__date[4:6]), day=int(__date[6:8]) ) date.append(_date) data.append([ cpOhlc.GetDataValue(1,i) ]) df = pd.DataFrame(data, columns=[name], index=date) pythoncom.CoUninitialize() return df -
Why isn't the Google login page rendered properly?
I'm developing a Django application and I tried to implement login with Google account. It works, but I'm not sure why the CSS isn't working when I press the sign up with google button? Screenshot This is the code for the google sign up button: <a class="waves-effect light btn btn-block btn-google" href="{% provider_login_url 'google' %}" style="width: 50%; font-size: small;"> <img src="https://img.icons8.com/color/16/000000/google-logo.png"> Sign up with Google </a> -
Module installed but "ModuleNotFoundError: No module named <module_name>" which running gunicorn
I am trying to deploy this website using nginx. The site is configured correctly and this has been verified when I run python manage.py runserver. But when I run the same using gunicorn and wsgi, gunicorn --bind 0.0.0.0:8002 config.wsgi it lays out error: ModuleNotFoundError: No module named 'crispy_forms'. Crispy_forms are installed and has been verified using pip freeze. Virtual enviornment is also enabled. 'crispy-forms' is also already added in INSTALLED_APPS in settings.py. Following is my error code: root@devvm:/tmp/tmc_site# gunicorn --bind 0.0.0.0:8002 config.wsgi [2022-02-03 23:03:07 +0000] [6333] [INFO] Starting gunicorn 20.1.0 [2022-02-03 23:03:07 +0000] [6333] [INFO] Listening at: http://0.0.0.0:8002 (6333) [2022-02-03 23:03:07 +0000] [6333] [INFO] Using worker: sync [2022-02-03 23:03:07 +0000] [6335] [INFO] Booting worker with pid: 6335 [2022-02-04 04:03:07 +0500] [6335] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.8/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/local/lib/python3.8/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/local/lib/python3.8/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.8/dist-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django queryset .iterate(): not working. Only first item is taken into account, second is ignored
I have the following code. I know the queryset contains 2 items. However, Django only creates one entry. What am I overlooking? I know "OrderItem.objects.filter(order=order)" returns two objects. However, in the order_lines.iterate() it only creates one entry. Do I overlook something? order_lines = OrderItem.objects.filter(order=order) inv_ref = (str(order.order_date.year) + "-" + str(10000+order.id)) inv = Invoice.objects.create(invoice_ref=inv_ref,date=order.order_date, order=order, ship_to=order.order_ship_to, bill_to=order.order_bill_to) value = 0 vat = 0 total = 0 commission = 0 ## Looping not working properly: fix all items to be added to invoice. for item in order_lines.iterator(): exvat = (item.price/((100+item.vat)/100)) val = item.quantity * exvat ttl = (item.price*item.quantity) comm = item.commission vat_val = ttl-val InvoiceItems.objects.create(invoice=inv, order_item=item, quantity=item.quantity, price=exvat, value=val, vat=item.vat,vat_val=vat_val,total=ttl) value = value + val vat = vat + vat_val total = total + ttl commission = commission + comm print(item) -
Static File and Media Accessing issue while Deploying Django app in Production Environment
While deploying django app on production environment in openlitespeed server, static files and media files not found. App is woking fine in development environment in local, but after uploading it to server, static content and media files are not accessible. I have updated my static url as follow: STATIC_URL = '/public/static/' STATIC_ROOT = '/home/domain.com/app/public/static Where app is the project location. I am getting 404 for error for all static and media files: Failed to load resource: the server responded with a status of 404 () When I try collectstatic I am getting following error on terminal: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. I tried many options, none of the options worked. Any solution will be highly appreciated -
Should .js files be public when serving django files through AWS S3 bucket?
My django collectstatic command uploads fine to AWS S3 bucket, but runs into an 403 error when trying to access static files. From what I've seen from searching around is that my ACL is defaulting to 'private' and I need to change the settings to allow the writer to set ACL to 'public-read'. I've tried messing with the settings to set ACL to 'public-read' and it allows collectstatic and the website to run fine. However, it also allows anyone to inspect element and view my static files. Is having your static files publicly viewable common practice? It seems like it might be a security risk for anyone to be able to read my js files. If there's something I'm missing with my configuration of django please let me know. My settings file: USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') -
How to use Q, Max in Django Queryset Models?
I would like to know how it is used and the concept of Django Models aggregation -
Django-Celery Stopped Working After Switching Branches
I used cookiecutter-django to create my Django project with celery=yes and docker=yes. I spent some time modifying the Celery config/structure to match the HackSoftware Django Guidelines for Celery. It took me a while to get everything figured out but I did eventually get it all working with a sample task which just logs a few lines. This was done on a feature branch. So once I confirmed that everything was good, I committed and pushed my changed and merged the PR with my Main branch. Back in my terminal, I switched to Main and pulled the changes. At this point, there should be no diff between my main branch and my configure_celery branch. However, when I brought up all of the containers, my sample task was no longer executing. I've spent many hours now trying various things to get it working to no avail. I've brought the containers down, pruned everything with docker system prune -a, used Docker Desktop to manually clear out all of the volumes, tried a different Redis db config, switched back to my configure_celery branch and nothing has worked. I can see that the worker is successfully discovering my task: brew_dash_local_celeryworker | [2022-02-03 21:35:27,194: INFO/Process-1] Connected … -
How to limit serializing in Django Rest Framework?
I have 2 serializers that add and subtract (they are the same, with the difference being add +=1 and subtract -=1) points to an answer. I want to limit them so that a user can only use add point to an answer once. Do you have any idea how to get to it in Django Rest Framework? class Answer(models.Model): number_of_points = models.IntegerField(default=0) class SubtractPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points -= 1 instance.save() return instance -
Uncaught ReferenceError: $ is not defined in console
I am trying to append a div when a checkbox is selected in dajngo template but i keep receiving Uncaught ReferenceError: $ is not defined in the console the template: {% extends 'base_layout.html'%} {%load static%} {% block content %} <div class="inventory-content"> <div class='category'> <div>Categories</div> <div class='category-checkbox'> {%for category in categories%} <input type="checkbox" id="{{category.id}}" name="{{category.name}}" value="{{category.id}}"> <label for="{{category.name}}"> {{category.name}}</label><br> {%endfor%} </div> </div> <div class='items'></div> </div> <script> $('.category-checkbox input[type="checkbox"]').click(function (){ if ($(this).is(':checked')) { // Add the element to the div with an id identifier $('.items').append('<div id="[{{category.id}}]">123</div>'); } else { // Remove the element from the div targeted by the id identifier $('.items #[{{category.id}}]').remove(); } }); </script> {% endblock %} -
Improve Django intermediary tables
I'm working on a Django app that contains the following structure: There are Checklists consisting of one or more ChecklistItems. We want to assign however many checklists as we want to a Job, and fill these Job-Checklist's questions. An example would be to create a Checklist containing ChecklistItems: "How are you?" "What is your name?" So, each ChecklistItem is just a question in a checklist. This means now we can use this Checklist that consists of 2 ChecklistItems in any job and fill it out after assigning it. We create Job #1, and assign it this Checklist #1, create Job #2 and assign it Checklist #1 also. Same checklist to be answered in two different jobs. Whoever's working on that particular job will then fill the checklist out according to them. The way we first approached this was with Job and Checklist being connected by a JobChecklist intermediary table, and JobChecklistItemAnswers being assigned to each answered checklist item (question). class Checklist(models.Model): """A class to represent a checklist.""" name = models.CharField(_("name"), max_length=150) class ChecklistItem(models.Model): """A class to represent an item of a checklist.""" checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) question = models.CharField(_("question"), max_length=200) class Job(models.Model): """A class to represent a job.""" checklists = … -
Django_React_SQL website product searching
I am working on a project the backend is in python Django and frontend in react-js and database is MySQL. Now the problem is I need to search products from database in my project but don’t know how to get query for frontend to backend. I don’t know the code Moreover I am using rest-framework and Axios library to connect. I am very thankful to you if you help me to create search related queries in my project. Thank you -
How to use Django backands with Kivy
I would like to connect my website in Django with my mobile application in kivy but I don't know how? I know the different approaches I should use to solve the problems. I tried the APIs but I didn't succeed so help me! -
Django usage of forms everywhere
I think I have a wrong understanding of Django Forms / handling databases, especially because I'm completely new For this, let's just take YouTube comments as an example. If I write a comment on a YouTube video and press submit, the comment is published directly, everyone can see it, the page does not need to be updated by me. YouTube then stores the comment in the database. How would you implement something like this from theory in Django? According to current knowledge, I have to use the comment function put it in HTML form > submit button > refresh page Or we take another example, a website popup where the email address can be entered which will be saved. According to my current knowledge, I would have to create Form -> Submit Button -> Refresh Page which would make the user go back to the beginning of the website, which is annoying. When I read through stuff and watch tutorials it's all kind of muddled into forms. -
How to display multidimensional API response in Django?
I am new in Django and I am trying to learn this framework. I am trying to display the individual data from an API response. From my views.py, I am passing order in a context. order = response.json()['order'] return render(request, 'orders.html', {'order': order}) I need to display fulfillment_date and fulfillment_status These are the tags I have tried on my frontend. {{ order.order_date }} is working {{ order.fulfillments }} is also working But these are not working. {{ order.fulfillments.fulfillment_date }} {{ order.fulfillments[0].fulfillment_date }} {{ order.fulfillments[0][0] }} {{ order.fulfillments.['fulfillment_date'] }} Thanks! API response: "order": { "order_date": "2022-01-09T00:00:00", "order_name": null, "checkout_token": null, "payment_method": null, "total_price": null, "subtotal_price": null, "currency": null, "landing_site_url": null, "source": "orders_api_v3", "payment_status": null, "cancellation": null, "customer": { "external_id": "111222", "first_name": "First Name", "last_name": "Last Name", "email": "newnew@newnew.com", "phone_number": null, "accepts_email_marketing": null, "accepts_sms_marketing": null, "custom_properties": null }, "billing_address": null, "shipping_address": null, "custom_properties": null, "fulfillments": [ { "fulfillment_date": "2022-01-09T00:00:00", "status": "success", "shipment_info": { "shipment_status": null, "tracking_company": null, "tracking_url": null, "tracking_number": null }, "fulfilled_items": [ { "external_product_id": "223553388", "quantity": 1 } ], "external_id": "112121212" } ], "line_items": [ { "id": 5554786884, "created_at": "2022-01-10T03:59:28", "updated_at": "2022-01-10T03:59:28", "quantity": 1, "total_price": null, "subtotal_price": null, "coupon_code": null, "custom_properties": null, "product_id": 303170668, "external_product_id": "223553388" } ], "id": 2824686328, … -
Django: Hierarchy model query
Imagine there is a model: class OrgUnit(models.Model): parent = models.ForeignKey( 'self', on_delete=models.CASCADE, verbose_name=_('parent'), related_name='children', blank=True, null=True, ) name = models.CharField(_('name'), max_length=255) type = models.CharField(_('type'), max_length=55, null=True, blank=True, db_index=True) And hierarchy sample: It is easy find all stores if one knows cluster id (cluster_id=1): stores = OrgUnit.objects.filter( type='store', parent__parent_id=cluster_id ) It is also easy find cluster by sales department id (sales_department_id=5): cluster = OrgUnit.objects.select_related('parent__parent').get(pk=sales_department_id).parent.parent And finally find stores for sales department: cluster_id = OrgUnit.objects.select_related('parent').get(pk=sales_department_id).parent.parent_id stores = OrgUnit.objects.filter(type='store', parent__parent_id=cluster_id) Getting stores by sales department id will make 2 queries to database. I wonder to know whether it possible to fetch stores by sales department id in one query? If yes how? -
Is there a Windows alternative to a certain Unix command?
I'm working with a database (MySQL) and use Django, I can't seem to find an alternative to this command: python manage.py inspectdb > models.py is there a windows alternative to this? Thank you -
Django is receiving image into a React Native FormData instance as an dict
I have a React Native app, there is a screen to upload a logo (an image). When the logo gets uploaded, Django should receive the image, save into an user row and create the file into local assets folder (as usual). The problem is, i don't even know if i am sending the data from React Native in a correct way, but Django REST API is receiving the image as an Python dict. I'm following the instructions from many other people, but still not working, here's how i load the logo into a React Native FormData instance: const fd = new FormData(); fd.append('logo', { name: logo.fileName, uri: logo.uri, type: logo.type, }); The logo variable is an Asset instance, from react-native-image-picker library. And here, how Django receive the data, with pdb (Python debugger): For a better look: {'_parts': [ ['logo', { 'name': 'logo.png', 'uri': 'file:///data/user/0/com.micandidato/cache/rn_image_picker_lib_temp_9b3907e0-3f13-4ad5-9ca9-13f491473440.png', 'type': 'image/png' }] ]} I'm pretty sure Django is not going to save this object as an image. The request method from React Native is PATCH (if relevant). Thanks. -
Trying to link my HTML form to a view function in Django
I've been trying to create a user registration page and have gotten the form itself and the render for the form set up. I have also gotten the form to save user input as POST, but haven't been able to send that info to a view function I have created to save that info to a database. Here is my html/css template form:(userinfo.html) <div> {% block content %} <form action="register" method="post" name="Userinfo" id="Userinfo"> <label for="fname">First Name</label> {% csrf_token %} <input type="text" id="fname" name="firstname" placeholder="Your first name.."> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Your last name.."> <label for="DOB">Date Of Birth</label> <input type="text" id="DOB" name="DOB" placeholder="The Date you were born"> <label for="Email">Email Address</label> <input type="text" id="Email" name="Email" placeholder="Your email address"> <input type="submit" value="Submit"> </form> {% endblock %} </div> The name of my view function is register and here it is:(views.py) def register(request): if request.method == 'POST': first_name = request.POST['first_name'], last_name = request.POST['last_name'], date_of_birth = request.POST['DOB'], email = request.POST['email'] newuser= User.objects.create_user(first_name=first_name,last_name=last_name, email=email) newuser.save() print('user created') return redirect('/home') else: return render(request,'register.html') This is supposed to save the user input into django's user database table. How would I go about linking the form to the view I have set up? -
Django how to search for one Model based on multiple foreign keys?
I'm essentially trying to build a filter based on the model's name and multiple foreign keys. class Foo(models.Model): name = models.Charfield() class Bar(models.Model): name = models.ForeignKey(Foo) Foo can have the same names, but different Bars. I want to search for the specific Foo based on Bars. So far I am able to parse user input and create a list ["foo.name", "bar.name", "bar.name"] How do I filter the product based on that specific Foo? and with trailing Bars? # pseudocode process foo = foo.objects.filter(name__contains=list[0] and foo.objects.filter(bar_name__in=[list] -
Internal server error in production with https in Django when change path
I have changed the path for admin.site.urls to /admindjango, in local it works fine, but in production(https and domain) it gives error 500, I already enabled allowedhost '*' and debug=False. urlpatterns = [ path('admindjango/', admin.site.urls), path('', include(('administracion.urls', 'administracion'), namespace='administracion')), ] -
How to keep the original filename in React when fetched from Django?
I'm working with a Django-Graphene-React stack and in my frontend, the user must be able to download a file from the backend. It works perfectly. However, the filename is defined in the backend and sent through the Content-Disposition header in the HttpRequest sent from Django. But I cannot retrieve it when I fetch it in the frontend. Here is my backend Django view that generates the file: import io from django.http import HttpResponse def download_file_view(request): buffer = io.BytesIO() # Generate an Excel file and put it a buffer... ... buffer.seek(0) response = HttpResponse( buffer.read(), content_type="application/vnd.openxmlformats-officedocument" ".spreadsheetml.sheet", ) # The filename is generated in the backend (Django) and cannot be # generated from the frontend (React) response["Content-Disposition"] = "filename.xlsx" return response If I download it directly by entering the url assign to this view in my browser, I get the filename correctly when my browser prompt me to save the file. However, I want to fetch the file in the frontend in order to get a loading state during the time the file is being generated in the backend. Here is my frontend component in React: import {useState) from "react"; const DownloadButton = ({downloadUrl}) => { const [isLoading, setIsLoading] = useState(false); … -
Check if user has sent a request before Django Rest Framework
I've got these serializers for adding and subtracting points in an answer on a forum. class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points += 1 instance.save() return instance class SubtractPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points -= 1 instance.save() return instance Viewset looks like this (the same is for adding): class SubtractPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = SubtractPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) Now, every user can only upvote once and downvote once. So someone might accidentally downvote and then upvote once again a particular answer. The urls are questions/int:pk/addpoint. questions/int:pk/subtractpoint So i'd like to make a limit on the Serializer that user_limit = 0 if request.user has already clicked upvote the user_limit = 1 and if user_limit = 1 return response that its already upvoted. But i have no idea how to implement this logic in a serializer since im very new to Django Rest Framework. Or maybe you have a better idea how to limit amount of upvotes per user? -
How to display mongodb data in html table using django
i want to display mongodb data into the html table but the problem is mycode first print all the time field and then print the all the status and then all the level instead of of printing one at a time my view.py code is as follows def generate(request): a=str(request.POST.get('level')) b= request.POST.get('status') c=(request.POST.get('startdate')) g=datetime.strptime(c,"%Y-%d-%m") d=datetime.strftime(g,"%Y/%d/%m") e=request.POST.get('enddate') h=datetime.strptime(e,"%Y-%d-%m") f=datetime.strftime(h,"%Y/%d/%m") output=run([sys.executable,'C:\\Users\\siddhant\\Desktop\\intern mongo\\indicator\\work\\water.py',a,b,d,f],stdout=PIPE,text=True) client=pymongo.MongoClient("mongodb://localhost:27017") db = client["water"] colle= db["waterlevel"] data_from_db = colle.find({}) return render(request,'result.html',{'task':data_from_db}) my result.html page template which display the table is as follows <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>time</th> <th>status</th> <th>level</th> </tr> </thead> <tbody> {% for ta in task %} <tr> <td>{{ ta.time }}</td> <td>{{ ta.status }}</td> <td>{{ ta.level }}</td> </tr> {% endfor %} </tbody> </table> </div> i want to create a table which display one datetime unit then on status and level value then move to next row please suggest the possible ways it would be very helpful