How to fix Django-admin SAVE button problem? - django-admin

When I save a new entry, I get this huge error, where the last line says You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code.
When I do so, I get another error CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.
I am following a tutorial to learn Django and I think I have done as explained in the tutorial
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'products.apps.ProductsConfig'
]
snippet of settings.py
from django.contrib import admin
from .models import Product
# Register your models here.
admin.site.register(Product)
admin.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.FloatField()
stock = models.IntegerField()
image_url = models.CharField(max_length=2083)
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
models.py
This is where I give my entry
This is when I click the save button

You don't say which error the debug shows, however you'll want to read the debug and solve that error as well.
Meantime, since you've turned debug off, you still want your app to run, although it will still have the above error.
Django has to know the host that is running the app in the runserver, as a redirect protection mechanism. If ALLOWED_HOSTS is blank, it only assumes localhost, so would only work from a browser or proxy on the same server.
To enable runserver to work, set the IP address on your server in
(project directory)/settings.py
ALLOWED_HOSTS = [ '10.1.1.10', ] # Use IP address of your host, not this example IP.
Since you've turned debug off, you'll need to restart your runserver
(venv)$ python manage.py runserver 0:8080
Your port number may be different.
Now you may be able to browse to your app from another system.
A similar question is also discussed here

Related

Is any way to start go_binary before java_test?

Our project has a few GRPC servers defined as go_binary targets. We develop client SDKs for Java and Python applications and we would like to use java_test and py_test. Is any way to start a specific go_binary target before java_test or py_test?
You can create a test harness that starts the gRPC server before running the tests. For example, you could add the binary to the data attribute of the test, and then started it beforehand:
go_binary(
name = "my_grpc_server",
[...]
)
py_test(
name = "my_test",
[...]
data = [":my_grpc_server"],
)
and then inside the test file:
class ClientTestCase(unittest.TestCase):
def setUp(self):
r = runfiles.Create()
self.server = subprocess.Popen([r.Rlocation("path/to/my_grpc_server")])
def tearDown(self):
self.server.terminate()
self.server.wait()
This example is very simple, you'll probably run into issues regarding the availability of the port the server listens on, or waiting for the server to start up. You could add flags to your gRPC server to allow communication over a domain socket, or make it listen on an unused port and have the test parse the port number from the server's log output.
For details on finding the server with runfiles: https://github.com/bazelbuild/bazel/blob/a7a0d48fbeb059ee60e77580e5d05baeefdd5699/tools/python/runfiles/runfiles.py#L16-L58
If you find yourself copy-pasting this pattern a lot, or having to implement it in multiple languages, you could try using an sh_test() rule to wrap the underlying py_test or java_test, and to start the server, then start the test with an environment variable telling it how to reach the server (eg MY_GRPC_SERVER_ADDRESS=localhost:${test_port}.

Why is this route test failing?

I've been following along with the testdriven.io tutorial for setting up a FastAPI with Docker. The first test I've written using PyTest errored out with the following message:
TypeError: Settings(environment='dev', testing=True, database_url=AnyUrl('postgres://postgres:postgres#web-db:5432/web_test', scheme='postgres', user='*****', password='*****', host='web-db',host_type='int_domain', port='5432', path='/web_test')) is not a callable object.
Looking at the picture, you'll notice that the Settings object has a strange form; in particular, its database_url parameter seems to be wrapping a bunch of other parameters like password, port, and path. However, as shown below my Settings class takes a different form.
From config.py:
# ...imports
class Settings(BaseSettings):
environment: str = os.getenv("ENVIRONMENT", "dev")
testing: bool = os.getenv("TESTING", 0)
database_url: AnyUrl = os.environ.get("DATABASE_URL")
#lru_cache()
def get_settings() -> BaseSettings:
log.info("Loading config settings from the environment...")
return Settings()
Then, in the conftest.py module, I've overridden the settings above with the following:
import os
import pytest
from fastapi.testclient import TestClient
from app.main import create_application
from app.config import get_settings, Settings
def get_settings_override():
return Settings(testing=1, database_url=os.environ.get("DATABASE_TEST_URL"))
#pytest.fixture(scope="module")
def test_app():
app = create_application()
app.dependency_overrides[get_settings] = get_settings_override()
with TestClient(app) as test_client:
yield test_client
As for the offending test itself, that looks like the following:
def test_ping(test_app):
response = test_app.get("/ping")
assert response.status_code == 200
assert response.json() == {"environment": "dev", "ping": "pong", "testing": True}
The container is successfully running on my localhost without issue; this leads me to believe that the issue is wholly related to how I've set up the test and its associated config. However, the structure of the error and how database_url is wrapping up all these key-value pairs from docker-compose.yml gives me the sense that my syntax error could be elsewhere.
At this juncture, I'm not sure if the issue has something to do with how I set up test_ping.py, my construction of the settings_override, with the format of my docker-compose.yml file, or something else altogether.
So far, I've tried to fix this issue by reading up on the use of dependency overrides in FastApi, noodling with my indentation in the docker-compose, changing the TestClient from one provided by starlette to that provided by FastAPI, and manually entering testing mode.
Something I noticed when attempting to manually go into testing mode was that the container doesn't want to follow suit. I've tried setting testing to 1 in docker-compose.yml, and testing: bool = True in config.Settings.
I'm new to all of the relevant tech here and bamboozled. What is causing this discrepancy with my test? Any and all insight would be greatly appreciated. If you need to see any other files, or are interested in the package structure, just let me know. Many thanks.
Any dependency override through app.dependency_overrides should provide the function being overridden as the key and the function that should be used instead. In your case you're assigning the correct override, but you're assigning the result of the function as the override, and not the override itself:
app.dependency_overrides[get_settings] = get_settings_override()
.. this should be:
app.dependency_overrides[get_settings] = get_settings_override
The error message shows that FastAPI tried to call your dictionary as a function, something that hints to it expecting a function instead.

How do I debug Telegraf?

I'm trying to get telegraf working with influxdb and I've just hit a wall. I added the following block in my telegraf config file:
[[inputs.win_perf_counters.object]]
# Process metrics, in this case for IIS only
ObjectName = "Process"
Instances = ["W3SVC"]
Counters = ["% Processor Time","Handle Count","Private Bytes","Thread Count","Virtual Bytes","Working Set"]
Measurement = "win_proc"
However, when I search my db, I never see that measurement. I know that process is running, so it should be outputting something. The problem is that even though I have logging turned on, there's no logfile. There's also nothing in the event viewer. Short of downloading the source code and running the program in a local debugger, I have no idea how to proceed. Does anyone have any ideas?
[agent]
## Default data collection interval for all inputs
interval = "10s"
## Log at debug level.
debug = true
## Log only error level messages.
quiet = false
## Log target controls the destination for logs and can be one of "file",
## "stderr" or, on Windows, "eventlog". When set to "file", the output file
## is determined by the "logfile" setting.
# logtarget = "file"
## Name of the file to be logged to when using the "file" logtarget. If set to
## the empty string then logs are written to stderr.
# logfile = ""
You can specify debug = true in the agent config to print the debug logs. If you don't specify any log file, the logs will be printed on terminal.
You have probably solved it by now, but for further reference. You could add a file output.
[[outputs.file]]
files = ["stdout"]
In your telegraf.conf and then watch the console (stdout) for output.

How to run firefox in native app of an extension?

I'm trying simple modify an extension example to run firefox,but I get a message prompt :
Firefox is already running,but is no responding. To open a new new window, you must firest close the existing Firefox process, or restart your system.
#!/usr/bin/env python3
import sys
import json
import struct
import subprocess
try:
# Python 3.x version
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.buffer.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('#I', rawLength)[0]
message = sys.stdin.buffer.read(messageLength).decode('utf-8')
return json.loads(message)
# Encode a message for transmission,
# given its content.
def encodeMessage(messageContent):
encodedContent = json.dumps(messageContent).encode('utf-8')
encodedLength = struct.pack('#I', len(encodedContent))
return {'length': encodedLength, 'content': encodedContent}
# Send an encoded message to stdout
def sendMessage(encodedMessage):
sys.stdout.buffer.write(encodedMessage['length'])
sys.stdout.buffer.write(encodedMessage['content'])
sys.stdout.buffer.flush()
while True:
receivedMessage = getMessage()
if receivedMessage == "ping":
run_result=subprocess.run('firefox -P firefox_word ',shell=True,stdout=subprocess.PIPE)
sendMessage(encodeMessage("pong3"))
except AttributeError:
pass
My purpose is open a local html file by my extension or native app of my extension.
I had a similar issue a while ago, also when I was experimenting with WebExtensions examples. I think the problem is with your Firefox profile. The solution that worked for me was to create a new profile, then (after a day or so) reopen the previous profile. It has been fine since then. I do not know any more details about the problem.
The Mozilla page "Firefox is already running but is not responding" error message - How to fix it describes this solution as well as a number of others (which I tried, but did not have success with).
You can start the Firefox Profile Manager as per the following instructions (see here for complete details):
If Firefox is open, close Firefox:
Press Windows Key + R on the keyboard. A Run dialog will open.
In the Run dialog box, type in: firefox.exe -P Click OK. The Firefox Profile Manager (Choose User Profile) window should open.
Create a new profile, click 'Start Firefox'
To open your previous profile, launch Profile Manager again and select your default profile
For me I need work in same profile,now my solution is made a shell script as daemon to read a fifo and my native app of my extension write that fifo when I need run firefox.
Note you need run that daemon outside the native app of extension.

Rails Custom Logger Writes To Log Sporadically

I've set up a custom logger in an initializer:
# /config/initializers/logging.rb
log_file = File.open("#{Example::Application.config.root}/log/app.log", "a")
AppLogger = ActiveSupport::BufferedLogger.new(log_file)
AppLogger.level = Logger::DEBUG
AppLogger.auto_flushing = true
AppLogger.debug "App Logger Up"
Although it creates the log file when I start the application, it doesn't write to the log file. Either from AppLogger.debug "App Logger Up" in the initializer or similar code elsewhere in the running application.
However, intermittently I do find log statements in the file, though seemingly without any pattern. It would seem that it is buffering the log messages and dumping them when it feels like it. However I'm setting auto_flushing to true which should cause it to flush the buffer immediately.
What is going on and how can I get it working?
Note: Tailing the log with $ tail -f "log/app.log" also doesn't pick up changes.
I'm using POW, but I've also tried with WEBrick and get the same (lack of) results.
Found the answer in a comment to the accepted answer to on this question:
I added:
log_file.sync = true
And it now works.

Resources