Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle a post request in json format to own laptop in python via django or flask
I have configured an http webhook on thethingsstack webpage cloud.thethings.network that performs a post request to a configured endpoint (my laptop) as follows: http://xxx.ngrok.io -> http://localhost:80 For uplink message: http://localhost:80/uplink-message For join ack: http://localhost:80/join-accept Using ngrok.exe http 80 I can also see that I receive the post requests in my command line: POST /uplink-enabled 502 Bad Gateway POST /uplink-enabled 502 Bad Gateway POST /uplink-enabled 502 Bad Gateway However, I'm not able to receive the data in json format following the online tutorials: enter link description here enter link description here Is there a code example that listens continuously to the http port and handles post requests? -
Django db block for migration with no schema change
When updating the helptext of field of a Django model, it produces a migration to track this change. This operation doesn't perform any sql query (checked with manage.py sqlmigrate myapp). However, does it still lock the table like normal schema change migration? -
How to Issue and Return a book in Library Managament System
1st Problem - What I want is that when a user issue a book the quantity must be decreased by 1 and once there is no book user should not be able to issue the book and this should be handled by bookIssueView(first view) 2nd Problem - I want to return(remove from issued book list) issued books by clicking return and once the book returned the quantity must be increased by 1(I could not handle this also) now when button clicked it is showing - ConnectionDoesNotExist at /book-return/1/ The connection 'Django For Pro' doesn't exist - Here is the code written Related Views def bookIssueView(request, id): book = get_object_or_404(Book, id=id) issue_date = timezone.now() quantity = 0 book_issue = BookIssue.objects.create( issue_date=issue_date, book=book, reader=request.user.reader, quantity=quantity ) book = book_issue messages.info(request, "Book has been issued.") return redirect("book_issue_list" def bookIssueView(request, id): book = get_object_or_404(Book, id=id) issue_date = timezone.now() quantity = 0 book_issue = BookIssue.objects.create( issue_date=issue_date, book=book, reader=request.user.reader, quantity=quantity ) book = book_issue messages.info(request, "Book has been issued.") return redirect("book_issue_list") Related Models class Book(models.Model): book_name = models.CharField(max_length=50) author_name = models.CharField(max_length=50) isbn = models.CharField(max_length=50, unique=True) category = models.CharField(choices=CATEGORY, max_length=30) description = models.TextField() cover = models.ImageField(upload_to="book_cover/") status = models.CharField(choices=BOOK_STATUS, default="Available", max_length=50) quantity = models.IntegerField(default=0) class BookIssue(models.Model): reader … -
Login not working in django when using rewrites from firebase hosting to cloud run
Current Setup: I've got a Django application behind gunicorn running on Cloud Run. Since the region it is deployed in does not support Custom Domains, I have a firebase hosting setup with the following code: { "hosting": { "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [{ "source": "/**", "run": { "serviceId": "website", "region": "ap-south1" } }] } } The relevant settings in settings.py: CSRF_TRUSTED_ORIGINS = ['.<domain>.com'] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True The problem: However, the login form on /admin does not work if I access the site using my domain name https://doman.com/admin even though it works fine if I use the Cloud Run endpoint https://endpoint-uw.a.run.app. Faulty behaviour: When accessing it from my domain, the login page shows up, I enter my credentials and log in, it adds the relevant cookies to my browser but then it redirects me back to the login page. Could it be that since the URL is being rewritten by firebase django is expecting a cookie from uw.a.run.app? I tried adding the setting SESSION_COOKIE_DOMAIN = '.<domain>.com' but that did not fix it either, it just made the Cloud Run endpoint stop working as well. Any advice on how to fix this or how to diagnose … -
How to display python variable to Django UI
I'm trying to subscribe to a MQTT topic called Wind. After that I want to show the value in my Django chart. But whenever I return the result of my MQTT value with test it showed me name 'test' is not defined. My Idea: Globalize the msg.topic with test and then use test in showdata class. But unfortunately it don't work, Does anyone have any idea on this issue? Thanks My code (views.py): from django.shortcuts import render from paho.mqtt import client as mqtt_client import random broker = 'localhost' port = 1883 topic = "Wind" # generate client ID with pub prefix randomly client_id = f'python-mqtt-{random.randint(0, 100)}' # username = 'emqx' # password = 'public' def showdata(request): context = test return render(request, 'index.html', {'data': context}) def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg, request): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") global test test = msg.topic client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ == '__main__': run() -
How to save one table value to another table in django?
I have two models mentioned in below Robot - class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot jenkinsHistory - class jenkinsHistory(models.Model): robotName = models.ForeignKey(Robot, on_delete=models.CASCADE, blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100) jenkinsBuildStatus = models.CharField(max_length=200) errorMsg = models.CharField(max_length=500) Param = models.CharField(max_length=500,blank=True, null=True) my robot table has some data . now i want to assign some Robot table data in my jenkinsHistory table. so that i have written view like this def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) name = pi.robot print("name", name) hist = jenkinsHistory(robotName= name,jenkinsBuildStatus='Jenkins-Running') hist.save() but when i try to run that . it is giving me error like this How to solve that issue and assign data in jenkinsHistory table from Robot table? -
Django unable to persisted cached array
Django cannot persist my cached data even if I set timeout to none. My settings.py contains this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'django_cache', #'/var/tmp/django_cache', 'TIMEOUT': None, } } I save data with this line of code: cache.set('array', array, timeout=None) I fetch data like this: array = cache.get('array') try: iterator = iter(array) except TypeError: # Array not iterable: my app gets here when cache data is lost else: # I go through the array and get needed info I don't think it's a MAX_ENTRIES issue because I only have one array with 39 elements. When the data is lost, the array becomes not iterable (because empty). I also tried using file cache cause I suspected that restarting the Django app may clear the RAM cache but had the same issue. I've tried file caching with the following configuration in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'filecache'), 'TIMEOUT': None, } } The "filecache" directory is created and contains a non-empty cache file but I still loose my cached array somehow. -
How to send MQTT topic value to Django UI
I'm trying to subscribe to a MQTT topic called Wind. After that I want to show the value in my Django chart. But whenever I return the result of my MQTT value with test it showed me name 'test' is not defined. My Idea: Globalize the msg.topic and then use in my showdata class. But unfortunately it don't work, Does anyone have any idea on this issue? Thanks My code (views.py): from django.shortcuts import render from paho.mqtt import client as mqtt_client import random broker = 'localhost' port = 1883 topic = "Wind" # generate client ID with pub prefix randomly client_id = f'python-mqtt-{random.randint(0, 100)}' # username = 'emqx' # password = 'public' def showdata(request): context = test return render(request, 'index.html', {'data': context}) def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg, request): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") global test test = msg.topic client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ == '__main__': run() -
Use context variable to compare with forloop.revcounter in Django
I can not use context variable to compare with forloop.counter or forloop.revcounter. No error returning. But, every time if statement become false. here is my view func- def view_single_server(request, pk): server = PhysicalServer.objects.get(pk=pk) context = { 'server' : server, 'n':range(42) } return render(request,'server/view_single_server.html', context ) And Here is my templete- {% for i in n %} {% if forloop.revcounter == server.loc_in_rack %} <li>{{server.loc_in_rack}}</li> {% else %} <li>No Server</li> {% endif %} {% endfor %} What wrong am I doing? -
How can i get to filter talent , talent2 both using django filter
views.py def get_ajax(self, request, *args, **kwargs): talent= request.GET.get('talent', None) users = User.objects.all().order_by('last_name') if talent: user = users.filter(user_talent=talent) and users.filter(user_talent2=talent) models.py def get_talent(self): talent = f'' if self.user_talent: talent = f'{self.user_talent}' if self.user_talent2: talent = f'{self.user_talent}, {self.user_talent2}' return talent -
Not able to connect to websocket using Nginx and Uvicorn
I built a docker container with Django, Uvicorn, Nginx and Redis, and am using django-channels but when I run this it says it cannot connect to the websocket and this is seen in the browser console: WebSocket connection to 'ws://127.0.0.1:8080/ws/notifications/' failed It is working fine when I use Django's runserver command for development but when I include Nginx and Uvicorn it breaks. Entrypoint.sh: gunicorn roomway.asgi:application --forwarded-allow-ips='*' --bind 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker Nginx config: upstream django { server app:8000; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 8080; location /static { alias /vol/static; } location /ws/ { proxy_pass http://0.0.0.0:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } location / { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_redirect off; proxy_buffering off; } } settings.py: CHANNEL_LAYERS={ 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('redis', 6379)], #Redis port } } } The JS file which handles the socket: var wsStart = "ws://" var webSocketEndpoint = wsStart + window.location.host + '/ws/notifications/' const notificationSocket = new WebSocket(webSocketEndpoint) asgi.py: application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter([ url(r'^ws/notifications/', NotificationConsumer.as_asgi()), path("ws/<str:room_name>/", ChatConsumer.as_asgi()) ]) ) }) -
How to make datetime already saved in database timezone aware in a Django project
We had a couple of timezone unaware datetime in model definition which resulted in saving a number of entries that were naive datetimes. The default was set to be utcnow like this time_sent = models.DateTimeField(default=datetime.utcnow, blank=True) And we got a lot of these RuntimeWarning: DateTimeField ModelName.time_sent received a naive datetime (2021-08-18 06:43:04.448875) while time zone support is active. We now have set the default as timezone.now so going forward we should not have this problem. However, what should we do to change the data already in database? Any ideas? -
Django||Python :: ValueError: bad marshal data (unknown type code)
I have tried creating a login/register Template that I can use to skip the login/register setup phase every time I need to create a new Django project. However, when I copy the code over and rename the file (and change all the "old file name" dependencies" ... It gives the above mentioned error with the below error message > C:\Users\KylePOG\Documents\GMA Programming\accConnect>python manage.py > runserver Traceback (most recent call last): File > "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", > line 22, in <module> > main() File "C:\Users\KylePOG\Documents\GMA Programming\accConnect\manage.py", line 18, in main > execute_from_command_line(sys.argv) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", > line 419, in execute_from_command_line > utility.execute() File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", > line 363, in execute > settings.INSTALLED_APPS File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 82, in __getattr__ > self._setup(name) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 69, in _setup > self._wrapped = Settings(settings_module) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\site-packages\django\conf\__init__.py", > line 170, in __init__ > mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\KylePOG\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", > line 127, in import_module > return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File > "<frozen importlib._bootstrap>", line 1007, in _find_and_load File > "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked > File "<frozen importlib._bootstrap>", line 228, in > _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line > 1007, in _find_and_load File "<frozen importlib._bootstrap>", … -
Saving django parent and child form
I have a page where users enter details that relate to two models - that representing a patient, and another representing medications taken by that patient. I have designed the interface so that multiple medications can be added dynamically by the user. However, I am not sure how to save both the entries for the meds and the patient when the user submits. In the current setup below I am not successfully saving the Patient data as I receive the error “save() prohibited to prevent data loss due to unsaved related object 'patient’.” models.py class Patient(TimeStampedModel): patient_id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField("Patient Name", max_length=255) class Med(TimeStampedModel): med_name = models.CharField("MedName", max_length=20) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) forms.py from django.forms import inlineformset_factory, ModelForm from .models import Med, Patient MedFormSet = inlineformset_factory(Patient, Med, fields=("med_name",), extra=1) class PatientForm(ModelForm): class Meta: model = Patient fields = ['name', 'sex'] views.py from .forms import MedFormSet, PatientForm from .models import Patient, Med class MedAddView(TemplateView): model = Patient template_name = "../templates/patient/med_add.html" def get(self, *args, **kwargs): # Create an instance of the formset patient_form = PatientForm formset = MedFormSet(queryset=Med.objects.none()) return self.render_to_response({'med_formset': formset, 'patient_form':patient_form}) def post(self, *args, **kwargs): form = PatientForm(data=self.request.POST) formset = MedFormSet(data=self.request.POST) if form.is_valid() and formset.is_valid(): form.save() … -
Django error after install Bootstrap4 with pip
I just installed bootstrap4 using pip and then I execute runserver and this is what I got. I've been looking for solutions and now I´m here asking for your help please Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\python\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\python\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\python\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\python\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\python\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\python\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\python\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\python\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 846, in exec_module File "<frozen importlib._bootstrap_external>", line 983, in get_code File "<frozen importlib._bootstrap_external>", line 913, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed ValueError: … -
Routing access to custom user model through database router in django
Consider following situation: You have multiple python/django applications, which share a common user database. You implemented the custom user model in a separate django-app called 'benutzer', which is imported into every applications project directory. Now simply routing access to the custom user model by a custom database-router is apparantly not enough. You probably will get erros similar to the following one: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration benutzer.0001_initial is applied before its dependency auth.0012_alter_user_first_name_max_length on database 'benutzer_extern'. Which models/app-names handled internally by django are needed to be routed additionally to the custom user model ? Adding app_label 'auth' to the router definition does not work. class ExternUsermodelRouter: """ A router to control all database operations on models in an extern user application. """ app_benutzerverwaltung = {'benutzer', 'auth'} def db_for_read(self, model, **hints): """ Attempts to read benutzer models go to db_benutzer. """ if model._meta.app_label in self.app_benutzerverwaltung: return 'db_benutzer' return None def db_for_read(self, model, **hints): """ Attempts to write benutzer models go to db_benutzer. """ if model._meta.app_label in self.app_benutzerverwaltung: return 'db_benutzer' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the benutzer apps only appear in the 'db_benutzer' database. """ if app_label in self.app_benutzerverwaltung: return db == … -
How to perform conditional aggregation on a Django model's one to many related field?
Given the following model schemas: class Transaction(models.Model): wallet = models.ForeignKey(related_name="transactions") amount = models.DecimalField() # must be positive value type = models.CharField(choices=[("deposit", "deposit"), ("withdrawal", "withdrawal")] class Wallet(models.Model): pass What is the most efficient Django ORM query to obtain the balances of every wallet record in the database? current_balance = sum of "amounts", where type="deposits" - sum of "amounts", where type="withdrawal" It is possible to change the Transaction model's type field to store 1 & -1 integer values in the database, and perform the following query: Wallet.objects.all().annotate(current_balance=Sum(F("transactions__amount") * F("transactions__type"))) Let's assume we cannot change the columns or fields of the given tables / records. Thoughts? -
Django - How to handle unmanaged models during tests
In my Django project I am using 3 different databases, of which 2 are pre-populated with data (legacy databases), thus many of my models are not managed by Django managed = False. When I run tests Django throws django.db.utils.OperationalError: no such table: x. I've been dealing with this problem for days now and already explored few stackoverflow threads and blog articles (i.e https://medium.com/an-idea/testing-with-the-legacy-database-in-django-3be84786daba, https://hannylicious.com/blog/testing-django/, https://dev.to/vergeev/testing-against-unmanaged-models-in-django). Sadly nothing seems to help, some tables just don't want to be migrated to test databases (I am also using 3 test sqlite3 dbs). Many stackoverflow threads and blog posts are old and don't apply to current Django version (3.2). I would greatly appreciate any help if anyone has experienced similar problem. Cheers guys :) -
Field 'id' expected a number but got (something with Id)
Django 3.2.6 class FeedbackForm(CreatedMixin, CommentMixin, FlagMixin, models.Model): name = models.CharField(blank=False, default="", null=False, unique=False, max_length=500, verbose_name=gettext("Name:")) email = models.EmailField(blank=True, default="", null=False, unique=False, verbose_name=gettext("Email:")) phone = PhoneField(blank=True, default="", null=False, unique=False, verbose_name=gettext("Phone:")) message = models.TextField(blank=False, default="", null=False, verbose_name=gettext("Message:")) def __str__(self): return f"{self.name}_{self.email}_{self.phone}" class FeedbackForm(ModelForm): class Meta: exclude = [OmnibusNames.COMMENT.value, OmnibusNames.FLAG.value, OmnibusNames.CREATED.value,] model = FeedbackForm class FeedbackFormView(FormView): template_name = 'feedback_forms/feedback_form.html' form_class = FeedbackForm class FeedbackFormResult(View): def post(self, request, *args, **kwargs): feedback_form_model = apps.get_model(app_label="feedback_forms", model_name="FeedbackForm") new_feedback = feedback_form_model(request.POST) new_feedback.save() return render(request, template_name="feedback_forms/feedback_form.html") <form id="subscription-form" onsubmit="return false"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form> The problem: {TypeError}Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['W8wfxQvsmQyElPtsdmJFiDJmzbyKZXRYfZS9TAbFGpNZDo22jWaLotUrllHYsDWi'], 'name': ['John'], 'email': ['tad@gmail.com'], 'phone_0': ['+19617828635'], 'phone_1': [''], 'message': ['ddd']}>. Hm. Something with id. But I though that Id is auto incrementdd. Could you help me? [![enter image description here][1]][1] ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [1]: https://i.stack.imgur.com/GYFL7.png -
is Django 3 compatible with MySQL 5.7?
I'm running a django app in Ubuntu, and the MySQL version is : mysql Ver 14.14 Distrib 5.7.34, for Linux (x86_64) using EditLine wrapper The Django version is 3.2.5 But it raised an Error: File "/opt/anaconda3/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/opt/anaconda3/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/opt/anaconda3/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) Exception Type: ProgrammingError at /category/python.html Exception Value: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION (SELECT `blog_article`.`id`, `blog_article`.`created_time`, `blog_article`' at line 1") Is it a compatible issue between Django 3 and MySQL 5.7? -
how to create a django app that performs a google search
I want to make a Django app that searches on google a string and then saves the html page. so far I managed to create this <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container text-center"> <h1>my search engine</h1> <h3>Pressing search will run a google search for 'lallero search', then the code will scrape the first 5 links in that google search and store the corresponding html.</h3> <a href="{% url 'about' %}">About page</a> <br> <br> <form action="{% url 'search' %}"> <input type='submit' value='search' class="btn btn-primary"> </form> </div> that searches on google a very specific string and it is just a press button. I would like to add a form where I can write the string I want to search and then pass it as input to my "search" function so far I came out with this <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <div class="container text-center"> <h1>my search engine</h1> <a href="{% url 'about' %}">About page</a> <br> <br> <form action="{% url 'search' %}"> <input type="search" value='lallero search' class="form-control rounded" placeholder="Search" aria-label="Search" aria-describedby="search-addon" /> <button type="button" class="btn btn-outline-primary">search</button> </div> but I do not know how to pass the string I write as input to the function. any advice? -
Django simple search with Class based views and forms.py
I have been trying to do a variation of what Williams Vincent did on this page: https://learndjango.com/tutorials/django-search-tutorial . I am using Django 3.2 so if there are modifications, I need to make I have not identified them. I am having some troubles. This what I made which worked just fine. my_search.html: {% extends "base.html" %} {% block body %} {% for city in object_list %} <li> {{city.name}} &emsp; {{city.city_no}} </li> {% endfor %} {% endblock %} views.py: from django.views.generic import ListView from .models import City class SearchResutlsView(ListView): # test version model = City template_name = "search_results.html" def get_queryset(self): return City.objects.filter(name__icontains='Boston') Now it is time to add forms.py, but when I made the below changes to the code it does not work. What am I missing? There are no errors displayed. I get a blank html. {% extends "base.html" %} {% block body %} <form class="d-flex" method='get' action="{% url 'city:search_results' %}"> {{ form }} <button class="btn btn-outline-success" type="submit" value="qu">Search Name</button> </form> {% for city in city_list %} <li> {{city.name}} &emsp; {{city.city_no}} </li> {% endfor %} {% endblock %} forms.py from django import forms class SearchForm(forms.Form): q = forms.CharField(label='Search label', max_length=50, strip=True) views.py from django.views.generic import FormView, ListView from .models import City … -
How and where to calculate field in Django?
Let's say we have such models. class Product(models.Model): name = models.CharField(max_length=100) # ... main_photo = models.ImageField(upload_to='photos/') class ProductPhoto(models.Model): product = models.ForeignKey(Product, related_name='photos', on_delete=models.CASCADE) photo = models.ImageField(upload_to='photos/') I have two views: ProductsView. It provides list of products with general information about each one, including name, ..., main_photo only. ProductDetailsView. It provides more detailed info, including all photos. I want detailed view to provide all photos in flat array photos, like this [main_photo, ...rest_photos]. How can I do this with django rest framework? On which level should this logic be implemented? Model, View, Serializer? -
How to prefetch_related on Django MPTT model sub-category?
I'm using Django MPTT model for category and sub-category. I'm unable to filter subcategories by their active state. I wanted subcategory data with is_active=True. models.py class TrnCategory(MPTTModel): name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, related_name='subcategories', null=True, blank=True, db_index=True) is_subject = models.BooleanField(default=False) institute = models.ForeignKey(Institute, on_delete=models.CASCADE, related_name='catrgories') sequence = models.IntegerField(default=1) is_active = models.BooleanField(default=True) My query: views.py class CategoryDetailView(generics.RetrieveUpdateDestroyAPIView): serializer_class = CategorySerializer permission_classes = [IsAuthenticated, InstituteAdminRequired] def get_serializer_class(self): if self.request.method != 'GET': return CategorySerializer return CategoryDetailSerializer def get_queryset(self): return TrnCategory.objects.filter(institute=self.request.user.institute, is_active=True).prefetch_related(Prefetch('subcategories', queryset=TrnCategory.objects.filter(is_active=True).order_by('sequence') )).order_by('sequence') def perform_destroy(self, instance): instance.is_active = False for material in instance.materials.filter(is_active=True): material.is_active = False material.save(update_fields=['is_active']) instance.save() My output in postman { "id": 54, "name": "Python", "is_subject": false, "is_active": true, "parent": null, "subcategories": [ { "id": 106, "name": "File Handling", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 5 }, { "id": 107, "name": "Modules and String Formatting", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 6 }, { "id": 118, "name": "Assessment - 1", "is_subject": false, "is_active": true, "subcategories": [], "sequence": 7 }, { "id": 119, "name": "Assessment - 2", "is_subject": false, "is_active": false, "subcategories": [], "sequence": 8 } ], "sequence": 0 }, { "id": 108, "name": "Python Advanced", "is_subject": false, "is_active": true, "subcategories": [ { "id": 150, "name": "Testing", "is_subject": false, … -
Django - Is it better practice to just create REST endpoints with url parameters or APIViews with serializers?
So I have 2 examples below of what I mean. The DELETE uses Django REST framework and it takes a user id as url parameters to delete a FollowUser entity. Then the second expects the information to create a FollowUser object in the "data" of the request. I prefer the first method, because I don't have to create a APIView where all requests require the same data body and I don't need to create new serializers for different requests. For example, if DELETE only requires 2 table attributes, but POST requires all of them. Which one of these practices is safer(less prone to getting hacked)? Can I require JWT token authentication for both these styles of end-point creation? @api_view(['DELETE']) def delete(self, request, follower_id, followee_id): FollowUser.objects.get(follower_id=follower_id, followee_id=followee_id).delete() return HttpResponse(status=status.HTTP_200_OK) class FollowGoalView(APIView): def post(self, request): serializer = FollowUserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)