Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django POST Question for Hangman Game - Cant Update More Than One Letter
I'm working on a Hangman game using Django and trying to update the correct letters guessed in the word on the page. It seems I can get one letter at a time but not more than one to update the word as the game progresses. Its almost like a new list is initializing each time the function is called. Any suggestions? Here is my code, the 'else' is defaulted off a post request. Any buttons clicked from the keyboard are sent to a function where I handle the POST request, one button at a time. I'm a little unfamiliar working with HTTP requests/responses so any help would be appreciated. else: game_id = int(request.POST['game_id']) letter_guess = request.POST['letter'] game = Game.objects.get(game_id=game_id) game.guess = letter_guess split_answer = game.answer.split() answer1 = split_answer[0] len1 = int(len(game.display1) / 2) word1 = list(range(len1)) for x in range(len1): if answer1[x] == letter_guess: word1[x] = answer1[x] + " " else: word1[x] = "_ " word1 = "".join(word1) game.display1 = word1 game.save() -
Why am i getting "No Such Table" when running SQL query with cursor.execute()?
I am trying to run a simple sql query but i keep getting "Operational Error: No Such Table customers" The code in question is: cursor = connection.cursor() cursor.execute("SELECT * FROM customers") # cursor.festchone() or cursor.fetchall() r = cursor.fetchone() print(r) Whats weird is running a raw SQL query using the code below works and i'm able to iterate through the rows and display in HTML: sql = "SELECT * FROM customers" customer = Customer.objects.raw(sql)[:10] print(customer) print(connection.queries) Also whats weird is the django docs says to add the app name so when adding the app_name network into the 2nd code, i get an error saying no such table: network.customers but the code works if i remember the app name: sql = "SELECT * FROM network.customers" customer = Customer.objects.raw(sql)[:10] print(customer) print(connection.queries) Databases in settings.py: DATABASES = { 'default':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'network_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Network.sqlite3', }, 'simulation_db':{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'Simulation.sqlite3', } } Network apps.py: from django.apps import AppConfig class NetworkConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'network' So i'm wondering why is the 2nd code working but the 1st code is not? I've checked the debug_toolbar which shows the BaseDir is where the database … -
Import feed into Django template
I'm trying to import some feed from a website into my blog builded with Django. Into context_processors.py I've created the function belowe: import feedparser def pygisblog_feed(request): url = "https://pygisblog.massimilianomoraca.me/feed.xml" feeder = feedparser.parse(url) for entry in feeder['entries']: title = entry['title'] link = entry['link'] description = entry['summary'] published_at = entry['published'] context = { 'title': title, 'link': link, 'description': description, 'published_at': published_at, } return context In settings I've added the function into context processors list. Now I would like to see the feeds in a template, so: {% for post in pygisblog_feed %} <p>title: {post.title}</p> {% endfor %} But I see a blank page. Probably it happen becouse I can use the for loop template tag only with a queryset. Is possible to convert a list or a dictionary to a queryset? If yes, how? -
How django models datetime field handles default time in migration?
I have many entries already in the event table with these columns class Event(models.Model): name = models.CharField(max_length=100, unique=True) event_date = models.DateField(null=True, blank=True) Now I want to change event_date to datetime. class Event(models.Model): name = models.CharField(max_length=100, unique=True) event_date = models.DateTimeField(null=True, blank=True) Now: python manage.py makemigrations python manage.py migrate After the migrations how the DateTimeField will handle the time with the already created date values ? -
Django TestCase DB missing columns that are in the DB when I runserver
When I start my app it works perfectly, but when I try to run a testcase it creates the test DB from my local copy and errors for a missing column that I can see in my local DB and was part of an older migrations. Any suggestions (venv) PS C:\Users\mtmcd\Azure Devops\Blindspot> python manage.py runserver 127.0.0.1:8888 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 19, 2022 - 11:02:25 Django version 3.0.8, using settings 'blindspot.settings' Starting development server at http://127.0.0.1:8888/ Quit the server with CTRL-BREAK. [19/May/2022 11:02:48] "GET /endpoints/list HTTP/1.1" 200 82572 But when I run python manage.py test I get (venv) PS C:\Users\mtmcd\Azure Devops\Blindspot> python manage.py test Creating test database for alias 'default'... Traceback (most recent call last): File "C:\Users\mtmcd\Azure Devops\Blindspot\venv\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column agents_simulationaction.alert_test_name does not exist LINE 1: ...d", "agents_simulationaction"."security_tool_id", "agents_si... -
Django CBV ModelForm hx-post not working with HTMX
I have a partial form rendered with HTMX rendered in my page upload.html: {% extends 'base.html' %} <p>Veuillez choisir ci-dessous entre l'upload d'un fichier de commandes ou l'upload d'un fichier fournisseur :</p> <h2>Upload fichier <u>transporteur</u></h2> <button hx-get="{% url 'tool:upload-form' %}" hx-swap="afterend" hxtarget="#transporterforms">Add transporter</button> <div class="transporterforms"> </div> {% block content %} And my upload-form.html: <div hx-target="this" hx-swap="outerHTML"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit" hx-post=".">Submit</button> </form> </form> </div> Here is how I manage my form in views.py: class TransporterFileFormPartialView(FormView): form_class = TransporterFileForm template_name = 'tool/upload-form.html' success_url = '.' def form_valid(self, form): transporter_file = TransporterFile.objects.create( file=form.cleaned_data['file'], transporter=form.cleaned_data['transporter'] ) transporter_file_pk = transporter_file.pk return super().form_valid(form) class CompareFormView(CustomLoginRequiredMixin, RequestFormMixin, TemplateView): """ View to show results of comparison between two files. """ template_name = 'tool/upload.html' # success_url = '.' def post(self, *args, **kwargs): form = TransporterFileForm(self.request.POST) if form.is_valid(): obj = form.save(commit=False) # transporter_file = get_object_or_404(TransporterFile, pk=form.pk) obj.save() transporter_file = TransporterFile.objects.get(pk=obj.pk) transporter_file_pk = transporter_file.pk return redirect(reverse_lazy('tool:upload')) And in my forms.py: class TransporterFileForm(forms.ModelForm): class Meta: model = TransporterFile fields = ('file', 'transporter') My urls.py are as follows: urlpatterns = [ path('', TemplateView.as_view(template_name="tool/home.html"), name="home"), path('upload-form/', TransporterFileFormPartialView.as_view(), name="upload-form"), path('upload-detail/<int:pk>', TransporterFileFormDetailView.as_view(), name="upload-detail"), path('upload-detail/<int:pk>/delete/', TransporterFileFormDeleteView.as_view(), name="upload-delete"), path('report/add-report', UserAddReportView.as_view(), name='add-report'), path('report/add-report/2', CompareFormView.as_view(), name='upload'), path('reports/', UserReportsView.as_view(), name='reports'), ] My main … -
1045, "Access denied for user 'root'@'localhost' (using password: NO)")
i'm using xampp and vagrant to run my project but whenever i try to makemigration or run the server i got this error django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: NO)") here's my connection data and i'm using vagrant to run my project full error: so what's the error? -
How do I pass string from url and use it to query the list?
class PatientDetailView(TemplateView): template_name = 'detail_view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) vitals_list = DailyVitals.objects.get(patient = ) context['vitals_list'] = vitals_list return context What query should I pass to filter queryset with the patient's username? urls.py: urlpatterns = [ path('home/', HomeView.as_view(), name='home'), path('', HomeView.as_view(), name='home'), path('addRecord/', VitalCreateView.as_view(), name='create_record'), path('detail/<str:username>', PatientDetailView.as_view(), name='detail'), path('doctor', DoctorView.as_view(), name='doctor'), path('patient', PatientView.as_view(), name='patient'), ] models.py class User(AbstractUser): is_doctor = models.BooleanField('doctor status', default=False) is_patient = models.BooleanField('patient status', default=False) class Doctor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Patient(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username class DailyVitals(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE, null=True, blank=True) date = models.DateField(auto_now_add=True) blood_pressure = models.IntegerField() sugar_level = models.IntegerField() temperature = models.IntegerField() weight = models.IntegerField() def __str__(self): return str(self.date) def get_absolute_url(self): return reverse("patient") I tried to pass <a href= {% url 'detail' i.patient.user.username %}> from the template but I get this error " Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['detail/(?P[^/]+)\Z']: Thanks -
twilio api sms notifications with python django
Good evening everyone I had to implement the twilio module in my django project and it works well, the problem is that it does not allow you to send sms to phone numbers other than mine -
I'm getting an datetime error while making an car renting django web application
I'm creating an car renting web based application using django. And I'm getting following error even though I have removed datetime attribute or function from my code python manage.py migrate Operations to perform: Apply all migrations: admin, app, auth, contenttypes, sessions Running migrations: Applying app.0006_cart_car_cart_quantity_cart_renting_date_and_more...Traceback (most recent call last): File "D:\Rushikesh\Code\car_rent\quickrents\manage.py", line 22, in <module> main() File "D:\Rushikesh\Code\car_rent\quickrents\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\core\management\commands\migrate.py", line 290, in handle post_migrate_state = executor.migrate( File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\migrations\executor.py", line 131, in migrate state = self._migrate_all_forwards( File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\migrations\executor.py", line 163, in _migrate_all_forwards state = self.apply_migration( File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\migrations\executor.py", line 248, in apply_migration state = migration.apply(state, schema_editor) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\migrations\migration.py", line 131, in apply operation.database_forwards( File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\migrations\operations\fields.py", line 108, in database_forwards schema_editor.add_field( File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\backends\sqlite3\schema.py", line 381, in add_field self._remake_table(model, create_field=field) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\backends\sqlite3\schema.py", line 230, in _remake_table self.effective_default(create_field) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\backends\base\schema.py", line 410, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "D:\Rushikesh\Code\car_rent\ecp\lib\site-packages\django\db\models\fields\__init__.py", line 1546, in get_db_prep_value value = self.get_prep_value(value) File … -
how can i make django password with no Hash algorithm?
i have made a custom user model in django, and it's OK, working but the problem is that i want to make the password field and auth function with no hash algorithm, i know about security problems of that, but that's OK because i won't expose my app in public. because i am working with very old and legacy database data. custom user model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.contrib.auth import get_user_model from django.utils import timezone class AccountManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, name, phone, password, **extra_fields): values = [email, name, phone] field_value_map = dict(zip(self.model.REQUIRED_FIELDS, values)) for field_name, value in field_value_map.items(): if not value: raise ValueError('The {} value must be set'.format(field_name)) email = self.normalize_email(email) user = self.model( email=email, name=name, phone=phone, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, name, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, name, phone, password, **extra_fields) def create_superuser(self, email, name, phone, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, name, phone, password, **extra_fields) class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) name = models.CharField(max_length=150) phone = models.CharField(max_length=50) date_of_birth … -
Not able to connect with server websocket it showing me status -502 Bad Gateway in django
I have configure Django Channels successfully in my local it is working fine in my local, also I'm able to chat one to one using websocket. when I try to deploy it to server and try to connect with websocket it shows status 502 Bad Gateway. I try so many thing but i'm stucked now anyone of you guys can help me to overcome this problem thanx in advance. This is the nginx configuration of my project.. upstream websocket { server www.domain_name.com:8000; #SERVER endpoint that handle ws:// connections } server { server_name www.domain_name.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/django/app; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; } location /v1 { include proxy_params; client_max_body_size 100M; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_http_version 1.1; proxy_pass http://websocket; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.domain_name.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/www.domain_name.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domain_name.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.domain_name.com; return 404; # managed by … -
Django model's __str__ with seperate fields
I have a model that return's a financial year and a description. Currently the attributes are combined into one value as one field. As you can see, the year 2021 and description test. I can click on the field which brings me to the details page. My code: class Meta: ordering = ['description', 'accounting_year', 'swift_code'] verbose_name_plural = "Extractions" def __str__(self): return f'{self.accounting_year} {self.description}' What I would like to achieve, but can't figure out nor find it online is to split the two fields into separate columns. Thus, 2021 as a column and test as a column. Furthermore, I would like to be able to sort or even filter, because one of the fields is extraction date. Would be great that an admin user could changed the order from newest to oldest and vice versa of just filter on name or date. Any documentation on that? -
Django test unit logged in user
I need some unit tests to check if a user after successful login can open profile editing page, how am I supposed to do this? I tried this code, but it shows an error. Do I have to use my own view to register a user then to log in or there are some unit test modules for that? class UserProfilePage(TestCase): def setUp(self): self.credentials = { 'username': 'test_user', 'password': 'secret'} user = User.objects.create_user(**self.credentials) self.user_profile = { 'user': user, 'first_name': 'Test_1', 'surname': 'test_surname', 'about_me': 'some_info', 'email': 'test@anymail.com', } UserProfile.objects.create(**self.user_profile).save() self.user_id = UserProfile.objects.get(user=user) def test_profile_page_and_current_template(self): response = self.client.get('/blog/user/profile/', self.user_id) self.assertEqual(response.status_code, 200) ValueError: Cannot query "Test_1": Must be "User" instance. -
How can i save subcategory to my database in django
I am having trouble in saving subcategory data as it is dependent dropdown so in value i need to add category id but if i add category_id the subcategory having id of that category_id is being saved to my database for eg:- if my category id is 4 my subcategory having id 4 is being saved to my database.I think you will get clearance what i mean to say through my code... please check it once and help me resolve my issue... <form method="POST" action="" id="productForm" enctype='multipart/form-data'> {% csrf_token %} {{form.media}} {{form.media}} <p>Title:</p> {{form.title}} <p>Details:</p> {{form.details}} <p>Image:</p> {{form.image}} <p>Sp:</p> {{form.sp}} <p>Dp:</p> {{form.dp}} <p>Download Link:</p> {{form.download_link}} <p>Preview Link:</p> {{form.preview_link}} <p>Category:</p> <div class="col-xs-6"> <select class="form-control" for="category" name="category" id="category"> {% for c in cat2 %} <option value="{{c.id}}" for="category">{{c.name}}</option> {% endfor %} </select> </div> <p>SubCategory:</p> <div class="col-xs-6"> <select class="form-control" for="subcategory" name="subcategory" id="subcategory"> {% for i in adminsubcategory %} <option value="{{i.category.id}}" for="subcategory">{{i.category_id}} {{i.id}} {{i.name}} {{i.category.name}}</option> {% endfor %} </select> </div> <p>Tags:</p> {{form.tags}} <br> <input name="submit" id="submit" class="btn btn-danger" type="submit" value="Upload"> </form> </div> </div> </div> <br> <br> <script> //Reference: https://jsfiddle.net/fwv18zo1/ var $category = $( '#category' ), $subcategory = $( '#subcategory' ), $options = $subcategory.find( 'option' ); $category.on( 'change', function() { $subcategory.html( $options.filter( '[value="' + this.value + … -
Django Formset - each form with different initial value from M2M-through relationship
I have to models which are connected by a M2M-Field realized by another Class ComponentInModule, so that I can add there the extra information, how often a component is in the module. class Module(models.Model): ... component = models.ManyToManyField(Component, through="ComponentInModule") class Component(models.Model): ... class ComponentInModule(models.Model): module = models.ForeignKey(InfrastructureModule, on_delete=models.CASCADE) component = models.ForeignKey(InfrastructureComponent, on_delete=models.CASCADE) amount = models.IntegerField(default=1) Now I am trying to load a Module as a form with its corresponding Components as a formset. class ComponentForm(ModelForm): amount = IntegerField() module = InfrastructureModule.objects.get(id=x) ComponentFormSet = modelformset_factory(Component, form=ComponentForm, extra=0) component_formset = ComponentFormSet(queryset=module.get_components()) As you can see my ComponentForm has the extra field for the amount. The question now is, how can I pass the value of amount to the Formset on creation, so that all forms are initialized with the right value? With a single Form it's no problem, because I can just pass the value to the __init__ function of the form and put it into the amount field self.fields["amount"].initial = amount. I tried passing a list of values to the formset with form_kwargs, but then I got the problem, that in the __init__function I dont know which of the values in the list is the right one right now. Is there … -
Django DRF + Allauth: OAuth2Error: Error retrieving access token on production build
We are integrating DRF (dj_rest_auth) and allauth with the frontend application based on React. Recently, the social login was added to handle login through LinkedIn, Facebook, Google and GitHub. Everything was working good on localhost with each of the providers. After the staging deployment, I updated the secrets and social applications for a new domain. Generating the URL for social login works fine, the user gets redirected to the provider login page and allowed access to login to our application, but after being redirected back to the frontend page responsible for logging in - it results in an error: (example for LinkedIn, happens for all of the providers) allauth.socialaccount.providers.oauth2.client.OAuth2Error: Error retrieving access token: b'{"error":"invalid_redirect_uri","error_description":"Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists"}' Our flow is: go to frontend page -> click on provider's icon -> redirect to {BACKEND_URL}/rest-auth/linkedin/url/ to make it a POST request (user submits the form) -> login on provider's page -> go back to our frontend page {frontend}/social-auth?source=linkedin&code={the code we are sending to rest-auth/$provider$ endpoint}&state={state}-> confirm the code & show the profile completion page The adapter definition (same for every provider): class LinkedInLogin(SocialLoginView): adapter_class … -
AttributeError: 'str' object has no attribute 'build_absolute_uri'
I get the following error when I use the function get_creds_url to construct the URL. I want to append credentials\ to the URL. return request.build_absolute_uri(url) AttributeError: 'str' object has no attribute 'build_absolute_uri' get_creds_url function: def get_creds_url(self, request=None): return reverse('api:workflow_job_template_detail', kwargs={'pk': self.pk}, request=request) Here is the reverse function which is imported from another file. I'm not sure if I can modify the reverse function to append credentials/ string. If it can be done please suggest. class URLPathVersioning(BaseVersioning): def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): if request.version is not None: kwargs = {} if (kwargs is None) else kwargs kwargs[self.version_param] = request.version request = None return super(BaseVersioning, self).reverse( viewname, args, kwargs, request, format, **extra ) Here is an example of how the function is invoked. if obj.workflow_job_template: res['credentials'] = obj.workflow_job_template.get_creds_url(self.context.get('request').path + "credentials/") -
Modify filter horizontal search field django
I'm using filter_horizontal in django admin. There is a vineyard called Château Monlot. When I try to type Château on the search box, it will appear. But when I type Chateau (without foreign char) on the search box, it doesn't appear. I want to make it appear when I type both Château and Chateau. How can I do that? -
How to set Django constraints to allow one enabled (BooleanField) object per item?
How to set Django constraints (or unique_together) to allow one enabled object per item? class Subscription(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) enabled = models.BooleanField(default=False) Should not allow to: item1 = Item.objects.get(...) sub1 = Subscription(item=item1, enabled=True) sub2 = Subscription(item=item1, enabled=True) but this should be allowed: item1 = Item.objects.get(...) sub1 = Subscription(item=item1, enabled=True) sub2 = Subscription(item=item1, enabled=False) -
To pass a value from js(HTML) to Django backend
I have done a project on building a QR Code scanner using Javascript , the value of qr was returned in a js variable. Now i cannot pass the value to django backend for futher operations My JS code <h4>SCAN RESULT</h4> <div id="result">Result Here</div> function onScanSuccess(qrCodeMessage) { document.getElementById('result').innerHTML = ''+qrCodeMessage+''; } I tried using Buttons instead of div so that clicking the button passes the button value to backend <button type="submit" id="result" name="xyz">QR VALUE</button> and in views.py def qrscanner(request): obj=request.POST.get("xyz") print(obj) return render(request,"qr_scanner.html") and this didn't succeed either, is there any way i could pass the qr value to django views -
Docker ignores middleware.py in Django Rest Project?
I have made a project where it uses blockchain service from a folder within the root of the project and middleware.py file uses the service. I have dockerized the application but when I run docker-compose it completely ignores the middleware file and just runs the Django rest framework app, but when I run the app using manage.py it uses the middleware? This is what happens when I run Docker-compose Starting ssa2_webrun_1 ... done Attaching to ssa2_webrun_1 webrun_1 | Watching for file changes with StatReloader webrun_1 | Performing system checks... webrun_1 | webrun_1 | System check identified no issues (0 silenced). webrun_1 | May 19, 2022 - 11:47:58 webrun_1 | Django version 4.0.2, using settings 'ssfa.settings' webrun_1 | Starting development server at http://0.0.0.0:8000/ webrun_1 | Quit the server with CONTROL-C. webrun_1 | RBV1sF8ExF9UhpLHZKaf27JC1Ee87pg3hL webrun_1 | [19/May/2022 11:48:03] "GET / HTTP/1.1" 200 5264 webrun_1 | RBV1sF8ExF9UhpLHZKaf27JC1Ee87pg3hL webrun_1 | Not Found: /favicon.ico webrun_1 | [19/May/2022 11:48:04] "GET /favicon.ico HTTP/1.1" 404 3295 This is what happens when I run from manage.py runserver (Correct) Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). May 19, 2022 - 11:49:19 Django version 4.0.2, using settings 'ssfa.settings' Starting development server at … -
Invalid HTTP_HOST header: Amazon ec2 Django
I am getting this error in my email Invalid HTTP_HOST header: ip'xx.xxxx.xxx.xx'. You may need to add ip'xx.xxxx.xxx.xx' to ALLOWED_HOSTS. I have seen many similar questions but all are giving fixes to either add this to the Allowed host or don't send this error to email. But I want to know the cause of this. Why is the ec2 instance sending a request to the Django server? -
Django admin - how to get a parameter from the url
I'm trying to make a default value in my table via the URL. I try to use the function get_year, but it returns me the first value in Year. For example, I have 2 tables: model.py class Year (models.Model): year = models.IntegerField(primary_key=True, verbose_name='Year') def __str__(self): return str(self.year) class Meta: ordering = ['year'] class RFCSTForm (models.Model): id = models.AutoField(primary_key=True) def get_year(self): selection = Year.objects.values_list('year')[0] return selection year = models.ForeignKey(Year, verbose_name='Year', null=True, blank=True, on_delete=models.CASCADE, default=get_year(Year)) budget_q1 = models.IntegerField(verbose_name='Budget Q1', null=True, blank=True) budget_q2 = models.IntegerField(verbose_name='Budget Q2', null=True, blank=True) budget_q3 = models.IntegerField(verbose_name='Budget Q3', null=True, blank=True) budget_q4 = models.IntegerField(verbose_name='Budget Q4', null=True, blank=True) avi = models.CharField(verbose_name='avi', max_length=200, null=True, blank=True) def __str__(self): return str(self.id) def total_budget(self): return self.budget_q1 + self.budget_q2 + self.budget_q3 + self.budget_q4 class Meta: ordering = ['id'] # unique_together = ('year', 'scenario') verbose_name = "RFCST Form" #Title on the maint page for this table verbose_name_plural = "RFCST Form" #Title for the navbar navigation The url: (if to be more precise, I want part of the URL, '2022') TNX -
Passing Data into Forms Django
Hypothetically; I have a simple system that has a list of choices on a screen. Each item has a button so you can add multiple supplementary items/information alongside the item selected but not change the item selected. Each item has a unique id which I want to pass into the form so that the comment is always associated with the item. I have a model that contains a foreign key that links the comment to the item and the Modelform works but I have to select the item from a drop down and I would like this information to be pre-populated in the form. This seems so simple but I have been going round in circles for days. Any pointers would be greatly appreciated