Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Logger in Django is somehow logging all SQL queries even though its not supposed to
So I work in a new place and I do not know everything about the project and there is no one who has answer to my question, no documentation, etc. The problem is: loggers are completely unreadable, many errors, almost everything important is logged to one file and the worst is that all SQL queries/requests to DB are logged, and I do not need them at all. Here is my logging config, I do not see anything related to SQL logging here, how can i find where in my project SQL logging is enabled? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '#######\n{asctime}\n {message}\n#######', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/django_error.log', 'formatter': 'verbose', }, 'ubki': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/ubki.log', 'formatter': 'verbose', }, 'ipay': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/ipay.log', 'formatter': 'verbose', }, 'root_file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/sites/moneycase/logs/root.log', 'formatter': 'verbose', }, }, 'loggers': { 'ubki': { 'handlers': ['ubki'], 'level': 'DEBUG', 'propagate': True, }, 'ipay': { 'handlers': ['ipay'], 'level': 'DEBUG', 'propagate': True, }, 'root': { 'handlers': ['root_file'], 'level': 'DEBUG', 'propagate': True, }, 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } logging.config.dictConfig(LOGGING) -
How to allow blank in model property field in django?
I have a property defined as the following @property def user_nr(self) -> str: x = "generated str" # some logic based on field _user_nr return x @user_nr.setter def user_nr(self, new_value) -> None: self._user_nr = new_value how can I use that property in Django serilizer given that the value can be blank sometimes? I add the property name in fields in the serializer but the blank values get removed from the validated data so when I try to access user_nr in validated data it says no key named user_nr but if I set a value and not a blank string, I can access it normally. so how can I retain the blank in that case? -
Django query sum decimal based on column
I trie to find a solution to summary fields depended on a row. In the database the SQL would be: Database: ACCOUNT | LIMIT | MARKET | LENDING | BALANCE ---------------------------------------------- 1000010 | 200.00 | 0.00 | -234.55 | 1000.00 1000010 | 300.00 | 11.00 | 0.00 | -239.00 1000010 | -200.00 | 235.00 | -134.00 | 450.00 1000011 | 30.00 | 1.00 | -10.00 | -98.00 1000011 | -200.00 | 235.00 | -134.00 | 49.00 SQL statements: SUM(LIMIT) as bond_limit, SUM(MARKET) as market_value, SUM(LENDING) as lending_value, SUM(case when BALANCE > 0 then BALANCE else 0 end) as FREE, SUM(case when BALANCE < 0 then BALANCE else 0 end) as MISS This should be the result: ACCOUNT | LIMIT | MARKET | LENDING | BOND_LIMIT | MARKET_VALUE | LENDING_VALUE | FREE | MINUS 1000010 | 200.00 | 0.00 | -234.55 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000010 | 300.00 | 11.00 | 0.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000010 | -200.00 | 235.00 | -134.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or 0 1000011 | 30.00 | 1.00 | -10.00 | Sum(LIMIT) | Sum(MARKET) | Sum(LENDING) | Sum(BALANCE) or … -
Encountering ValueError: not enough values to unpack (expected 3, got 0) with Celery in Django project on Windows 7
I have been working on a Django project on my Windows 7 machine, using VS-Code as my development environment. Recently, I decided to incorporate Celery for handling asynchronous tasks. However, I have been encountering a ValueError: not enough values to unpack (expected 3, got 0) whenever I try to retrieve the result of a task. Here's a snippet of how I am creating and calling the task: # common/test_tasks.py from celery import shared_task @shared_task def add(x, y): return x + y # In Django shell from common.test_tasks import add result = add.delay(4, 6) print(result.ready()) # Outputs: True print(result.get()) # Raises ValueError I have tried different Celery configurations and also different backends and brokers. Initially, I was using Redis as both the broker and backend, but I encountered the same error. I switched the broker to RabbitMQ (pyamqp://guest:guest@localhost//) while keeping Redis for the result backend. Still, the error persists. I also attempted to downgrade Celery to version 3.1.24 but faced installation issues on Windows. Here are my relevant settings in the settings.py file: # settings.py CELERY_BROKER_URL = 'pyamqp://guest:guest@localhost//' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' I've also checked the logs, but nothing stood out. The tasks seem to be executing successfully, but the error occurs … -
Python dateparser error, AttributeError: "safe_load()" has been removed, use
Today while I was trying to build my application without any changes made to old code just added logging and found below error by surprise. File "/app/search/parsers.py", line 9, in <module> import dateparser File "/home/python/.local/lib/python3.8/site-packages/dateparser/__init__.py", line 7, in <module> _default_parser = DateDataParser(allow_redetect_language=True) File "/home/python/.local/lib/python3.8/site-packages/dateparser/conf.py", line 84, in wrapper return f(*args, **kwargs) File "/home/python/.local/lib/python3.8/site-packages/dateparser/date.py", line 290, in __init__ available_language_map = self._get_language_loader().get_language_map() File "/home/python/.local/lib/python3.8/site-packages/dateparser/languages/loader.py", line 21, in get_language_map self._load_data() File "/home/python/.local/lib/python3.8/site-packages/dateparser/languages/loader.py", line 39, in _load_data data = SafeLoader(data).get_data() File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 108, in get_data return self.construct_document(self.composer.get_node()) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 123, in construct_document for _dummy in generator: File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 629, in construct_yaml_map value = self.construct_mapping(node) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 427, in construct_mapping return BaseConstructor.construct_mapping(self, node, deep=deep) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 242, in construct_mapping value = self.construct_object(value_node, deep=deep) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 145, in construct_object data = self.construct_non_recursive_object(node) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/constructor.py", line 179, in construct_non_recursive_object data = constructor(self, node) File "/home/python/.local/lib/python3.8/site-packages/dateparser/utils/__init__.py", line 192, in construct_yaml_include return yaml.safe_load(get_data('data', node.value)) File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/main.py", line 1105, in safe_load error_deprecation('safe_load', 'load', arg="typ='safe', pure=True") File "/home/python/.local/lib/python3.8/site-packages/ruamel/yaml/main.py", line 1037, in error_deprecation raise AttributeError(s) AttributeError: "safe_load()" has been removed, use yaml = YAML(typ='safe', pure=True) yaml.load(...) instead of file "/home/python/.local/lib/python3.8/site-packages/dateparser/utils/__init__.py", line 192 return yaml.safe_load(get_data('data', node.value)) script returned exit code 1 Can someone help what exactly changed … -
AWS issue with django backend and vue js frontend
my django backend is deployed on aws elastic beanstalk on default settings and auto scaling env type is single instance vue js frontend is hosted on aws s3, its setting is done with cloudfront and its now running on https from subdomain my backend is still on http and works fine on http and i have configured a https subdomain with ssl certificate, but when i add it to elastic beanstalk, elastic beanstalk gets severe health and stops gives this "100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health." my rds is postgresql and handled separately, by just connecting it on django settings. I want to do rest api calls from aws s3 to elastic beanstalk it would be helpful, if you also specify django cors settings and frontend axios api call settings for such stack i tried with http back and front end and its working, I want to do rest api calls from aws s3 to elastic beanstalk backend both on https it would be helpful, if you also specify django cors settings and frontend axios api call settings for such stack thanks -
How can I filter the values of a foreign key field based on another foreign key field value in Django admin?
These are my models: class ProductType(models.Model): name = models.CharField(max_length=350, verbose_name=_('name')) is_active = models.BooleanField(default=True, verbose_name=_('is active')) class ProductSpecification(models.Model): product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, related_name='specifications', verbose_name=_('product type')) name = models.CharField(max_length=255, verbose_name=_('name')) class Product(models.Model): product_type = models.ForeignKey(ProductType, related_name='products', on_delete=models.RESTRICT, null=True, blank=True, verbose_name=_('product type')) class ProductSpecificationValue(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='specs_values', verbose_name=_('product')) specification = models.ForeignKey(ProductSpecification, on_delete=models.CASCADE, related_name='specs_values', verbose_name=_('specification')) value = models.CharField(max_length=255, verbose_name=_('value')) and in admin.py: class ProductSpecificationTabu(admin.TabularInline): model = ProductSpecification fields = ('name_en', 'name_fa',) @admin.register(ProductType) class ProductTypeAdmin(admin.ModelAdmin): fields = ('name_en', 'name_fa',) inlines = (ProductSpecificationTabu,) search_fields = ('name_en', 'name_fa',) class ProductSpecificationValueTabu(admin.TabularInline): model = ProductSpecificationValue fields = ('specification', 'value_en', 'value_fa',) autocomplete_fields = ('specification',) @admin.register(Product) class ProductAdmin(admin.ModelAdmin): fields = ('product_type', ) inlines = (ProductSpecificationValueTabu, ) I want to limit the options for the 'ProductSpecificationValueTabu' based on the selected 'product_type' when choosing the product_type for a product. Should I do this using javascript? -
Large GB File upload to webserver
I have a requirement, where I want to create a web app(Either in Django or Fast API along with js in frontend), In which the user can upload large files (groups of files each file will be 3-4 GB), The collective size of these files may range 30-50 GB. How to approach this requirement. Can anyone help me navigate this requirement? -
Display Blob Image from MySQL to Django Template
I have models.py like this class p2_qc_ed(models.Model): qc_image = models.ImageField(upload_to='app_one/me/qc/ed/', null=True, blank=True) my views to upload the image like this captured_image_data = request.POST.get('capturedImageInput') format, captured_image_data = captured_image_data.split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(captured_image_data), name='temp.' + ext) qc_entry = p2_qc_ed(qc_image=data) qc_entry.save() while form submission, capturedImageInput value was like "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAHgCAYAAAA10dzkAAAAAXNSR0IArs4c6QAAIABJREFUeF7svQ2P9Lp2nSlVvec/DxBkcufGztiZTOIYGRs2gnsB/0y/XdJgk2IVq1rci8UltqTu..." the image uploaded successfully and I can see the image in 'app_one/me/qc/ed/' folder. But when i try to retrieve the image i use the following snippet `def ed_test(request):` ` image_data = p2_qc_ed.objects.get(id=444).qc_image` ` encoded_image_data = base64.b64encode(image_data).decode('utf-8') ` ` print(image_data,encoded_image_data)` ` return render(request,'qc_checksheet/qc_ed_test.html','encoded_image_data':encoded_image_data})` here the printed values are b'app_one/me/qc/ed/temp.png' 'YXBwX29uZS9tZS9xYy9lZF9zYW5kaW5nL3RlbXAucG5n' but I cannot display it in django template. can someone help me what is wrong with this ? Thanks in advance. expected to display the uploaded image but i couldn't . -
Nested model in Wagtail Orderable
In Wagtail, I'm trying to create a Page that using Orderable model of Wagtail. And in that Orderable model, I'm trying to nest the "ImageWithAltText", the reason for this is because by default, Wagtail image does not provide alt text field. So I would like to create my own class for re-use anywhere that has image. Below is the code: class ImageWithAltText(models.Model): image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) image_alt_text = models.TextField(blank=True, null=True) panels = [ FieldPanel("image"), FieldPanel("image_alt_text"), ] class FAQItem(Orderable): page = ParentalKey("get_the_facts.GetTheFactPage", related_name="faq_items") media_file = models.ForeignKey(ImageWithAltText, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=500, blank=False) panels = [ FieldPanel("media_file"), FieldPanel("title"), ] class GetTheFactPage(Page): content_panels = Page.content_panels + [ InlinePanel("faq_items", label="FAQ"), ] I have no succeed with this, at the Admin site, the UI the not showing "image" and "image_alt_text" as expected. Please take a look at the picture below: I haven't had any clue why this happened yet. Please help me with this, thank you in advanced. -
Change User Password Page - Django
I created a profile page for the user. In the "change password" section: 👇 when I click on this form, unfortunately, it goes to this link: "http://127.0.0.1:8000/8/password/", if I defined in the links that it should go into this link: "http://127.0.0.1:8000/accounts/password/". where is the problem from? name of my project is "resume", and my app is "members". resume urls.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("admin/", admin.site.urls), path("", include("main.urls", namespace="main")), path("blog/", include("blog.urls", namespace="blog")), path("accounts/", include("django.contrib.auth.urls")), path("accounts/", include("members.urls")), ] members urls.py: from django.urls import path from members.views import UserRegisterView, UserEditView, PasswordsChangeView from django.contrib.auth import views as auth_views app_name = "members" urlpatterns = [ path("register/", UserRegisterView.as_view(), name="register"), path("panel/", UserEditView.as_view(), name="panel"), path("password/", auth_views.PasswordChangeView.as_view()), ] -
Django unit test TypeError: the JSON object must be str, bytes or bytearray, not NoneType
I'm trying to write unit test and I faced this error a lot in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not NoneType and I can't tell where is the problem for example I have this simple unit test class CheckDiscountTest(TestCase): def setUp(self): self.test_order = { 'arrival_time':'12:00:00', } self.order = Order.objects.create(**self.test_order) self.test_discount = {'code': 'DISCOUNT','percentage': 10 } self.discount = Discount.objects.create(**self.test_discount) self.url = reverse('discount') def test_200(self): test_data = { 'code': 'DISCOUNT', 'id': self.order.id } response = self.client.post(self.url, data=test_data) self.assertEqual(response.status_code, status.HTTP_200_OK) for this @api_view(['POST', ]) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def check_discount(request): if ('code' in request.data and 'id' in request.data): order = Order.objects.get(id=request.data['id']) try: discount = Discount.objects.get(code=request.data['code']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost - \ (order.order_related_invoice.initial_cost * (discount.percentage/100)) order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) except Discount.DoesNotExist: if ('id' in request.data): order = Order.objects.get(id=request.data['id']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) else: if ('id' in request.data): order = Order.objects.get(id=request.data['id']) order.order_related_invoice.cost = order.order_related_invoice.initial_cost order.order_related_invoice.save() response_serializer = GetOrdersSerializer(order) return Response(response_serializer.data, status=status.HTTP_200_OK) return Response(status=status.HTTP_404_NOT_FOUND) I'm just trying to understand the error and how to fix it can anyone help me -
Remote mysql server constantly stopping and rebooting
I have made a django chatting application that allows users to talk to one anoter. I am using websockets for chatting and a MySQL server as my database. Since a few days, the MySQL database (or the server itself) has been rebooting non stop. This is happening so frequently that I am getting an error in my django application that while a message that was sent was being sent by a user was being saved in the database, the connection was lost. I am also unable to load messages in chats, meaning the previous messages being sent by the user are not visible either. The other functionalities of the database seem to be working fine for some reason such as the profile being updated, your account info being stored accurately. The site temporarily works fine if I restart the server with the "sudo shutdown -r now" command but I get the same problem not too long after that. If you want, you can check out the functionality of the site over at https://aniconnect.org Here is the output when I do the journalctl command: gamedeveloper@animechatapp:~$ sudo journalctl -u mysql Sep 20 13:18:17 animechatapp systemd[1]: Starting mysql.service - MySQL Community Server... Sep … -
Python django static files in render
I'm not Able to load static files in django in production in using Whitestone but it's not working when debug = False this is my settings.py file I've read another stack overflow post saying to use apache or something else How to use one like I've heard of nginx how to use this where to put the files and how to make it deployable in render -
How can i add a popup to an already existing button?
I have this delete button on my posts that when you click on it it deletes the post I wanted to add a html popup that I have on that button so that when someone clocks on delete it first shows the confirmation popup and then delete the post if they clicked on ok how can I achieve that? Thanks Where my delete button is <div class="container"> <div style="margin-top: 25px"></div> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">{{post.title}}</h4> </div> <div class="card-body"> {{ post.body|truncatewords_html:30 }} <hr> <p><img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" width="75" height="75"> Author: {{ post.author }}</p> <a href="{% url 'detail' post.id %}" class="btn btn-info btn-small" >Read More <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots" viewBox="0 0 16 16"> <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/> </svg></a> {% if user.is_authenticated %} <a href="{% url 'delete' post.id %}" class="btn btn-danger btn-small" >Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 16"> <path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 … -
How to Perform Unit Conversion before Aggregating Model Fields in Django?
I have a Django model as follows: class WeightUnit: KILOGRAM = "kg" TONNE = "tonne" LBS = "lbs" CHOICES = [ (KILOGRAM, _("kg")), (TONNE, _("tonne")), (LBS, _("lbs")), ] TONNE_CONVERSION_FACTOR = { TONNE: 1, KILOGRAM: 0.001, LBS: 0.000453592, } class Product(models.Model): weight = models.FloatField(verbose_name=_("total weight")) weight_unit = models.CharField( _("weight unit"), choices=WeightUnit.CHOICES, default=WeightUnit.TONNE, max_length=5, ) Each instance of the Product model can have a different weight_unit, and I need to create a query that aggregates the weight field of all products while converting all weights to a single, common unit (e.g., tonnes) for the aggregation. This is the query that I tried and got KeyError: F(weight_unit): conversion_expression = ExpressionWrapper( F('total_weight') * WeightUnit.TONNE_CONVERSION_FACTOR[F('weight_unit')], output_field=FloatField(), ) return Products.objects.annotate( converted_weight=conversion_expression, ).aggregate( weight=Sum('converted_weight', default=0.0), )["weight"] How can I achieve this using Django's queryset and database expressions? -
django with mongodb(djongo) the version of djongo does not support
i am using mongodb database with django project with djongo. while making migrations the erros prompts shows Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. and This version of djongo does not support "NULL, NOT NULL column validation check" pip freeze versions: mongodb database with djanog with djongo the error is following : error1 erro2 erro3 erro4 -
Django: getting the value of a serializer's field within the serializer itself
In my Django serializer, I have a validate() method. In it, I want to access the value of one of the serializer's fields. How would I do this? I'm using Python 3.10.2 and Django 3.2.23. Previous answers here have suggested using self.initial_data.get("field_name")) but that doesn't work for my version of Django (message: AttributeError: 'MySerializer' object has no attribute 'initial_data'). class MySerializer: models = models.MyModel class Meta: fields = "my_field" def validate(self, data): # Want to get the value of my_field here Many thanks in advance for any assistance. -
Getting error Object of type QuerySet is not JSON serializable
I am working on a Django project. Two of the many models are Story and its Part(s) Concerned serializers are as follows: class StoryPartSerializer(serializers.ModelSerializer): content_length = serializers.SerializerMethodField() class Meta: model = Part fields = ("external_id", "title", "published_on", "url", "content_length") read_only_fields = ("story",) def get_content_length(self, obj): return len(obj.content or "") class StoryPartDetailSerializer(StoryPartSerializer): story_object = serializers.SerializerMethodField() class Meta: model = Part fields = StoryPartSerializer.Meta.fields + ( "story_object", "content", ) read_only_fields = StoryPartSerializer.Meta.read_only_fields + ( "external_id", "published_on", "last_worked_on", ) def get_story_object(self, obj): story = obj.story serializer = StorySerializer(story) return serializer.data So the aim is to fetch the respective Part with Story object inside it. Simply fetching the part through /story{story_url}/parts/{part_url} works perfectly fine with the following output as example: { "external_id": "fd9136e6-93a1-4dd0-b913-32ff8ee789c9", "title": "part title", "published_on": "2023-10-28T10:53:48.430132Z", "url": "26bAE54d", "content_length": 72, "story_object": { "external_id": "98d9509e-c26d-4a95-b693-45dc658924ca", "title": "TS6", "author": { "username": "testuser1", "about": "", }, "description": "Description of TS6", "parts_order": [ "DD4b7ceE" ], "parts": [ { "external_id": "afbfd4ed-5bfb-4b0d-a812-4232010ffb09", "title": "Simple TEST", "published_on": "2023-10-09T01:32:53.015525Z", "url": "DD4b7ceE", "content_length": 5 } ], "published_on": "2023-06-20T15:49:18Z", "url": "b950c1CF", }, "content": "<img src='https://abc.test.net/9129e277-62ee-4897-b47a-492e8c6fff5c.png'>" } Problem arises in this code snippet where I am using signals to generate notification: @receiver( post_save, sender=Clap, dispatch_uid="add_notification_clap", ) def user_clapped(sender, instance: Clap, created, raw, **kwargs): … -
How to perform nested loops with Django models with multiple 1 to many relationships inside template
I am messing around in Django to understand the framework and have a database schema to model golf course data. I'm trying to put together a simple view to look at the hole information for a particular golf course. A golf course has 1 or more Tracks which contain 1 or more sets of Tees each of which have 18 holes with various attributes (hole number, par, yardage, etc). I'd like to format a simple HTML table for all sets of Tees organized by each Track contained in a particular golf course. I'm having trouble figuring out how to structure the loop in the template to format the data in this way. Here are my models: class GolfCourse(models.Model): """ This class models the Golf Course Table """ name = models.CharField(max_length=200) address = models.CharField(max_length=200) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=10) class Track(models.Model): """ This class models a Track within a golf course """ course_id = models.ForeignKey(GolfCourse, on_delete=models.CASCADE) name = models.CharField(max_length=100) class Tees(models.Model): """ This class models a set of Tee markers on a Track """ track_id = models.ForeignKey(Track, on_delete=models.CASCADE) name = models.CharField(max_length=50) rating = models.FloatField() slope = models.FloatField() class HoleInfo(models.Model): """ This class models the information for a … -
Fabric 3.2.2 asks for sudo password when executing NOPASSWD command
I have configured sudoers to let me execute two commands without password: # Allow foobar restart app_server Cmnd_Alias RESTART = /home/foobar/restart_nginx, /home/foobar/bin/restart_app_server foobar ALL = NOPASSWD : RESTART When I ssh to the server I can execute both commands without password: sudo /home/foobar/bin/restart_app_server sudo /home/foobar/bin/restart_nginx However when I do the same with Fabric I get the following error: sudo /home/foobar/bin/restart_app_server sudo /home/foobar/bin/timers_nginx sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper sudo: a password is required This is what my fabfile looks like: conn = Connection(local_settings.FABRIC_HOST, port=local_settings.FABRIC_PORT) conn.run( f"sudo /home/foobar/bin/restart_app_server && " f"sudo /home/foobar/bin/timers_nginx", echo=True) I tried shell=False, tried sudo(...) instead of run(...). No difference at all. This issue appeared after updating from Fabric 2.x.x to Fabric 3.x.x. But I can use old Fabric 2.x.x. right now. -
Why does one of these produce an error and the other does not?
I am attempting to run a simple python script to populate my Teams database for my django project under the teams app. The script is reading a list, I have included it below under the error on things i've tried and the results I expected. Mmm-anywaysss, I understand it has something to do with the "python needing to setup DJANGO_SETTINGS_MODULE" ? (.venv) root@firstfiverugbycloud:/home/django/firstfiverugby# python populate_teams.py Traceback (most recent call last): File "/home/django/firstfiverugby/populate_teams.py", line 2, in <module> from teams.models import Team, League File "/home/django/firstfiverugby/teams/models.py", line 3, in <module> class League(models.Model): File "/home/django/firstfiverugby/.venv/lib/python3.10/site-packages/django/db/models/base.py", line 129, in __new__ app_config = apps.get_containing_app_config(module) File "/home/django/firstfiverugby/.venv/lib/python3.10/site-packages/django/apps/registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "/home/django/firstfiverugby/.venv/lib/python3.10/site-packages/django/apps/registry.py", line 137, in check_apps_ready settings.INSTALLED_APPS File "/home/django/firstfiverugby/.venv/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/django/firstfiverugby/.venv/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( 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. (.venv) root@firstfiverugbycloud:/home/django/firstfiverugby# python manage.py shell < populate_teams.py (.venv) root@firstfiverugbycloud:/home/django/firstfiverugby# I am just trying to run a script to populate my database with test teams for a website I am building. The script just imports the models from my django app. # Import the Team model from your Django app from … -
is there a node.js lib/package that allows me to generate an executable python file?
So, I've got this web project in which a user inputs some info to a form and a python file is generated containing that info. What I want to do is send that file to my node.js server so that it transforms it into an executable python file, containing it's dependencies, and sends it back to the user so he can download it. With that said, is there any library/package that allows me to do that with Node.Js? ps: I am also considering using Django instead of Node.Js if it turns out to be too complicated or less efficient than Django. -
Local postgres database not syncing with Heroku postgres database
I am creating a CRM system with Django for my non-profit organisation. Have installed a local postgres database to which I created a table students and have added 2 rows via Django Admin interface. When I display these rows in a CSS table by running the app on localhost, the 2 records are correctly displayed. After migrating and pushing a git commit and then running the Heroku hosted instance of the app. The two records are not visible. localhost heroku instance I have no idea how to push my local updates to the database to the heroku postgres database. Searched around on the internet and have tried resetting the database but to no avail. -
Using Django Template inheritance, how can I have the same code at the bottom of my page?
I have been trying to add a footer to my layout.html, which is inherited by other pages in my Django project. I am looking to have a footer which is permanently at the bottom of any webpage like Stack Overflow does. I envisage this should be most efficiently done through inheritance. My suggestion from layout.html is shown below: HTML: {% block body %} {% endblock %} <div class="test_footer"> Footer Test </div> CSS .test_footer { width: 100%; background-color: var(--primary-colour); padding: 20px; box-sizing: border-box; position: absolute; bottom: 0; } The problem I have is that test_footer does not show beneath the rest of my body content. Instead it shows at the bottom of the browser covering html shown by the body and then moves up when I scroll.