Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: register() got an unexpected keyword argument 'base_name'
I have updated to djangorestframework==3.11.0 from older version. Now I've got this error, TypeError: register() got an unexpected keyword argument 'base_name' Traceback ... ... ... File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/abu/projects/django-example/django2x/urls.py", line 21, in <module> path('sample/', include('sample.urls')), File "/home/abu/.virtualenvs/django-example/lib/python3.6/site-packages/django/urls/conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/abu/projects/django-example/sample/urls.py", line 6, in <module> router.register(r'musician', MusicianViewset, base_name='musician') TypeError: register() got an unexpected keyword argument 'base_name' -
How to activate translation for all management commands by default?
I need translation to be activated in all of my django management commands by default. Currently I'm putting this line of code in all my management commands: translation.activate(settings.LANGUAGE_CODE) And sometimes I forget to consider it in my command. I need it to send translated notifications. Is there any way to activate translation for all of management commands by default? Any help is appreciated. -
How to manage lost connexion when updating database?
I develop a Django project with a randomization app for clinical trial. Basically, user will randomize a patient and a treatment will be assigned based on a randomization table and this table and 2 other tables will be updated based on randomization informations. My 'fear' is lost of internet connection during randomization and particularly when updating tables. Which is the good practice to manage this cases? I must be sure that all 3 tables are updated. Until now, when user is redirected to confirmation page, that means that all process has been complete. But if internet connection is lost during randomization_edit forms submission, it will not be the case... Thanks for advises. views.py @login_required @permission_required('randomization.can_randomize') def randomisation_edit(request): if request.method == "POST": form = RandomisationForm(request, data=request.POST or None) if form.is_valid(): randomisation = form.save() # randomisation rand = Randomiser(randomisation.ran_num, request.session.get('selected_site'),randomisation.ran_vih, randomisation.ran_sta) # rand = Randomiser(randomisation.ran_num, randomisation.ran_vih, randomisation.ran_sta) # Mise à jour de la base de données -> Patient code pour rendre indisponible la ligne # pour une prochaine randomisation # ListeRandomisation # 1.Récupération de la ligne dans la liste de rando bras = rand['bras'] # 2.Mise à jour de la ligne dans la liste de rando patient = ListeRandomisation.objects.get(ran_ide = bras) patient.pat … -
Library for Flask, like ViewSets in Django REST Framework
I have an Flask project with some dependencies: Flask-SQLAlchemy marshmallow-sqlalchemy flask-restplus At Django + Django REST Framework I'm usually use ViewSets for fast creation of endpoints: Point to Model Define fields list Get an CRUD-operations REST API Is it exist library for Flask which implements logic like ViewSets? -
How to restrict a child tables search field value on pre-selected parent field value using jQuery+Ajax
I am trying to implement jQuery autocomplete search for a model field based on a related model's FK field. For instance, names of a child model's values to be restricted on the preselected value of the key field of parent model (akin to Country > City scenario). What I have tried so far: A. Country field: Model: class Country(models.Model): name = models.CharField(...) The country search function is working as expected. B. City Field: Model: class City(models.Model): country = models.ForeignKey(Country, ...) name = models.CharField(...) View: def CitySearch(request): if request.is_ajax(): q = request.GET.get('term','') names = City.objects.filter(name__icontains=q).annotate(value=F('name'), label=F('name')).values('id', 'value', 'label') result = list(names) data = json.dumps(result) mimetype = 'application/json' return HttpResponse(data, mimetype) URL: path('city_search/', CitySearch, name='city_search'), Autocomplete function: Now in order to filter out the "country" values other than the one already picked up, I am trying to get the "country_id" value from the relevant html element on the page and pass it to the QuerySet for the "city" search function using ajax call for which I created a function as under: I am getting the value of country_id by calling the following function .on('change') on the country field: function fillCitySearch() { // FUNC TO GET COUNTRY SELECTION AND PASS IT TO QUERYSET … -
Why do I get the error that the 'split' attribute is missing when I run runmodwsgi?
I am in the process of moving the django page to a new server. Due to complications in the apache server configuration, I used mod_wsgi-express integrated into virtualenv python. According to the instructions found on this page: https://pypi.org/project/mod-wsgi/#description , I added mod_wsgi.server to installed Django applications and run the command python manage.py runmodwsgi. Unfortunately, in response I get an error which pastes below. I would be very grateful for any help and explanation why this problem appeared. Traceback (most recent call last): File "SAGI-B/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/g####/.venvs/sa###/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/g####/.venvs/sa###/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/g####/.venvs/sa###/local/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/g####/.venvs/sa###/local/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/g####/.venvs/sa###/local/lib/python2.7/site-packages/mod_wsgi/server/management/commands/runmodwsgi.py", line 71, in handle fields = wsgi_application.split('.') AttributeError: 'NoneType' object has no attribute 'split' -
Django test - unable to login using Selenium
I'm trying to create Selenium test for my Django project (Django 1.10). The problem is that I can't login. My code: class TicketViewTest(ArticleTestBase, LiveServerTestCase): def tearDown(self): self.driver.quit() def test_main(self): self.novice_writer = self.create_user('novice_writer', Profile.ROLE_NOVICE_WRITER) self.novice_writer.save() print(Profile.objects.all()) # result: <QuerySet [<Profile: 1 novice_writer novice_writer>]> self.driver = webdriver.Firefox('/usr/lib/geckodriver/') self.driver.implicitly_wait(3) self.driver.get('{}/login/'.format(self.live_server_url)) sleep(2) self.driver.find_element_by_id('inputLogin').send_keys('novice_writer') self.driver.find_element_by_id('inputPassword').send_keys('password') self.driver.implicitly_wait(1) self.driver.find_element_by_xpath('//button[@type="submit"]').click() sleep(2) In Selenium browser after click on submit I see the error 'Please enter a correct username and password. Note that both fields are case-sensitive.' When I tried to add print(Profile.objects.all()) to my login_view I have got '' So the server started by test just does not see my user. I added following code to test and login_view (just to be sure that server and test use the same database) from django.db import connection print(connection.settings_dict) and result is identical for view and test. So they use one database. Then why do they get different results for Profile.objects.all()? Thanks! -
Django data assignment in json serializers
My view returns JSON response as shown below. I want to assign another key, below the pk. How is it possible? device = Device.objects.all().filter(application_id=application_id) data = serializers.serialize('json', device) return HttpResponse(data, content_type='application/json') JSON response: [ { "model":"applications.device", "pk":13, "fields":{ "name":"WaterAMRK27", "category":"WaterAMR", "application_id":13, "description":"WaterAMR A27", "created_at":"2019-12-04T14:19:58.430Z", "updated_at":"2020-01-14T09:10:40.053Z" } } ] -
Django Rest Nested Relationship is not working
This is the defined models: class User(models.Model): name = models.CharField(max_length=250) status = models.IntegerField(default=1) created_at = models.DateTimeField(verbose_name='date created', auto_now_add=True) updated_at = models.DateTimeField(verbose_name='date updated', auto_now_add=True) def __str__(self): return self.name class UserInfo(models.Model): user_id = models.ForeignKey(User, on_delete = models.CASCADE, null = True) phone = models.IntegerField() status = models.IntegerField(default=1) created_at = models.DateTimeField(verbose_name='date created', auto_now_add=True) updated_at = models.DateTimeField(verbose_name='date updated', auto_now_add=True) def __str__(self): return '%d: ' % (self.user_id) These is how the serializer looks like: class UserSerializer(serializers.ModelSerializer): info = UserInfoSerializer(read_only=True, many=True) class Meta: model = User fields = ['id', 'name', 'status', 'info'] I am supposed to get info key in the response. But while id, name & status keys are returned, info key is missing. What am I missing here? -
What should I do to make my photos appear in Django?
I made my macbook disk format. After the format, I included my project. However, photos are not displayed on the project page. If I go to a specific product, (single page) this is a photo. The logo is also visible. Pictures are not displayed to me only collectively. Maybe I don't have something installed? Before, everything worked. Here photo display product.html {% extends 'base.html' %} {% load static %} {% block title %} {{ product.name }} - PVB {% endblock %} {% block content %} <main class="mt-5 pt-4"> <div class="container dark-grey-text mt-5"> <!--Grid row--> <div class="row wow fadeIn"> <!--Grid column--> <div class="col-md-6 mb-4"> <img src="{{ product.photo.url }}" class="img-fluid" alt=""> </div> <!--Grid column--> <div class="col-md-6 mb-4"> <!--Content--> <div class="p-4"> <div> <h2>{{product.product_name}}</h2><hr> <h5><p>Description</p></h5> <p class="text-justify"><h6>{{product.description}}</h6></p> <p class="text-justify"><h6>Weight: {{product.weight}}g</h6></p><hr> </div> </div> </div> </div> <hr> </div> </main> {% endblock %} here no products.html {% extends 'base.html' %} {% load static %} {% block title %} Offer - PVB {% endblock %} {% block content %} <section id="marks"> <div class="container"> <header> <h1>Our Offer</h1> </header> </div> </section> <!-- Offers --> <section class="text-center mb-4 py-4"> <div class="container"> <div class="row"> {% if products %} {% for product in products %} <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> … -
How do we set up a conda environment on MBP for django?
I posted a verbose question that was "off-topic" here. Can people comment on how they currently are setting up environments on this site? I can read python and conda documentation all day long, but wanted to see what real people were actually doing to formulate their plans for creating projects with Python 3.8 if the current machine does not have 3.8, and conda after 4.8. If this is inappropriate for this site, is there a single one stop site that one may visit that uses a MBP, conda, django, python, and vscode to find such current information? I currently have started using django with conda in an environment that has: django 2.2.5 py37_1 python 3.7.4 h359304d_1 The MBP was upgraded to Catalina from Mojave and still uses bash for the user created prior to the zsh as default change. I'm not sure that the version of VSCode is relevant for this question, but I am sure there may be people that may be using pycharm or some other IDE because of a good built in tool chain or extensikon that assists in making a current environment easy. I'm just curious if anyone has found a less complicated way than what … -
How can i call own method in django class based api views
I want to create account using phone number as a username and generate otp code . now i want to validate my phone number. I create a method is_phone_valid to validate my phone number but call it by post method but i am getting an error This is my views.py class GetPhoneNumber(CreateAPIView): queryset = TempRegistration.objects.all() serializer_class = AccountsSerializer def is_phone_valid(phone_number): if phone_number: MOBILE_REGEX = re.compile('^(?:\+?88)?01[15-9]\d{8}$') if MOBILE_REGEX.match(phone_number): return True else: return False else: return False def post(self, request, *args, **kwargs): return self.is_phone_valid(phone_number) models.py class TempRegistration(models.Model): phone_number = models.CharField(max_length=45) otp_code = models.CharField(max_length=6) def __str__(self): return self.phone_number -
Django logging is sending emails to admins only in debug mode
I opposite to what is documented in the Django Logging doc I am only getting admin emails when DEBUG = True. Here are my settings: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%Y-%m-%d %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/var/log/my.log', 'formatter': 'verbose' }, 'mail_admins': { 'level': 'ERROR', # 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', } }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level': config('LOG_LEVEL', default='INFO'), }, 'django.request': { 'handlers': ['mail_admins'], 'propagate': False, 'level': 'ERROR', }, 'FOO': { 'handlers': ['file'], 'propagate': True, 'level': 'INFO' }, } } I've been playing around with adding the RequireDebugFalse and RequireDebugTrue filters in the loggers section but that ended up in not getting any email in both debug modes. Anybody who has a clue what's wrong with my definitions? Thanks -
using specific bootstrap columns in django template based on the numbers of models
i have created a search result page which results 3 different models. For the results i need to use bootstrap columns. so what i need to do is display them with bootstrap columns.and there's a condition that if there is only one search result i need to use col-12 and if two col-6 and if three col-4 can anyone provide me a demo code? enter code here {% if jud %} <h2>Search results:</h2> <div class="row"> {% for product in products %} <div class="col-md-4"> <div class="jumbotron"> <h4>{{ product.title }}</h4> <p>{{ product.description }}</p> <h6 class="btn btn-primary btn-large">More info</h6> </div> </div> {% endfor %} </div> {% endif %} -
Djano celery shared_task delay not running
Windows 10 Python 3.7.3 django 2.2.5 Celery 4.4 I am trying to configure Celery for running a background task in a Django application and I'm having a very hard time doing it. I have added the following lines in the settings.py file: CELERY_BROKER_URL="amqp://localhost" CELERY_RESULT_BACKEND = 'rpc://' and setup celery.py and init.py as per the tutorial. My tasks.py file: # Create your tasks here from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def demotask(): with open('demotask.txt', mode='w+') as f: f.write("demo") print("Demotask running") In one of my views, I am calling demotask() inside the get_context() method and it works fine. When I use delay() (demotask.delay()), it will either not run or I don't know how to check. Also I have no clue of how to stop/restart celery workers in a windows environment. The tutorial is all about Linux. -
Fullcalendar in Django - Unique calendars with the ID
I suppose that this is a simple task, but I just can't figure it out on my own. I have a Calendar model, Events model, and CalendarGroups model, and a form, with the Event model. What I need, is an event creating, and selection for the calendar. So, the User wants to add an event and to select a calendar for that event. For now, I made two calendars from the admin panel, and I can render those two, and they have different ID's, which I can see from the page source. But when I try to add an event, and when I choose a calendar with ID = 1 for example, the event gets rendered on both calendars(needs to be rendered only on the calendar with ID=1). This is my models.py : class CalendarGroups(models.Model): GRP_CALS = ( ('Optika', 'Optika'), ('Bakar', 'Bakar'), ('DTH', 'DTH'), ('Supernova', 'Supernova'), ('Test', 'Test'), ) name = models.CharField(max_length=155, choices=GRP_CALS, blank=True, null=True) def __str__(self): return self.name class Meta: verbose_name = 'Calendar Group' verbose_name_plural = 'Calendar Groups' ##################################################################################### class Calendar(models.Model): name = models.CharField(max_length=155, blank=True, null=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True) group = models.ForeignKey(CalendarGroups, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: verbose_name = 'Calendar' verbose_name_plural = … -
How to have my template "load" for a second or two before refreshing after a POST
I'm having an issue where I have a MariaDB event combined with my Django Model. For context, here is my model code: class PartGroup(models.Model): GroupID = models.AutoField(primary_key=True, unique=True) Label = models.CharField(max_length=40, blank=True) SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True) InspectionPeriod = models.IntegerField(blank=False, null=True) LastInspected = models.DateField(blank=True, null=True) InspectionDue = models.CharField(max_length=255, blank=True) ConnectedTo = models.ManyToManyField('self', blank=True, null=True) The fields I want to highlight here are InspectionPeriod, LastInspected, and InspectionDue. I have another model which adds Inspections related to the GroupID. This contains a date of the inspection: class GroupInspection(models.Model): InspectionID = models.AutoField(primary_key=True, unique=True) GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True) class GroupReport(models.Model): ReportID = models.AutoField(primary_key=True, unique=True) InspectionID = models.ForeignKey('GroupInspection', on_delete=models.CASCADE, null=True) Date = models.DateField(auto_now=False, auto_now_add=False, null=True) Comment = models.CharField(max_length=255, blank=True) Signature = models.CharField(max_length=255, blank=True) I have a MariaDB event to update the LastInspected field, and from there some code in my view checks that date against the inspection period to see if an inspection is due. Here's where the problem occurs I have to have my MariaDB Event updating every 1 second in order to make this work reasonably well. I'm not sure if that's absolutely horrendous performance wise or not, if anyone has another solution that works smoother that's welcome. But that's not … -
Django Filter, seacrh query and pagination
I have a problem using filters and pagination, I have tried so many examples I've seen here on stack overflow but nothing seems to be working. I am using CBV(ListView). The filter works but the pagination has an issue, when i click next or page 2 it leads to a page not found (404 error), i edited the get_queryset but now includes items that are not part of the query search in the next page. I want the page to be paginated and show the remaining filtered items on the next page. views.py class SearchView(ListView): model = Job template_name = 'search.html' context_object_name = 'jobs' paginate_by = 3 # Query the database for letters similar to the search def get_queryset(self, *args, **kwargs): if self.kwargs: return self.model.objects.filter(title__contains=self.request.GET.get('title', False)).order_by('-date') else: query = Job.objects.all().order_by('-date') return query template.html {% if is_paginated %} <nav aria-label="Page navigation example"> <ul class="pagination justify-content-center pagination-sm"> {% if page_obj.has_previous %} <!-- If it ain't a search result display, don't append the search query to the URL. --> {% if not search %} <li class="page-item"> <a class="page-link" href="{% url 'search' %}?page={{ page_obj.previous_page_number }}" tabindex="-1">Previous</a> </li> {% else %} <!-- Append the searched query to the URL, so that on a search results … -
Interchanging files between web and mobile clients
I know that Stackoverflow does not address general questions, but in fact I am completely lost trying to design the architecture. I have a web app for connecting to a mobile device and rendering the files of the device on the web page. And it should be also possible to upload and download files to and from the device. Now I am trying to implement uploading from web. I do not have a direct connection from JS to the mobile device. Mobile device can only interchange data with the front-end via the backend (Django). Therefore, in order to pass a file from JS to the mobile device, I have to store the file somewhere on the backend, then tell the mobile device that the file is ready. After this mobile device asks for the file, and the backend provides the file as a response. Now, WHERE should I store that file is my biggest question right now. Should I use data-storage services like Amazon S3 ? Or should I use some sort of Django cache ? As soon as the file is transferred to the mobile device, the file can be deleted from the backend. But ideally it would still … -
Javascript sum dynamic django rest framework entries
I'm working on an app that allows a user to calculate information regarding a trade based on their entries. I've been stuck getting proper calculations on trade sums based on entries being added after the page has already retrieved any existing entries. <td scope="col">${sumTotal('amount')}</td> <script> ... mounted() { this.trade_id = window.location.pathname.split("/")[3]; // Get entries of trade axios .get('/trade/' + window.location.pathname.split("/")[3] + '/entries/') .then(response => (this.entries = response.data)); }, ... methods: { sumTotal(base) { return Math.round(this.entries.reduce((sum, cur) => sum + cur[base], 0)); } </script> When the page first loads and pulls the existing entries the first calculation (first column) is correct with 16. However, when I add a new entry the auto-calculated value is no longer true. The first column should be 26 but now is 1610 I can add much more info as needed. I wasn't sure how much would be required and I didn't want to clutter the question. -
Django User model with different types that may have same usernames?
I have a db where there are different tables for 3 different groups of accounts: parents, teachers, schools. I would like to build a User model for those 3 types of users. Usernames for all accounts will be pk of each data. The problem is that accounts are from 3 different tables, which have same pks. Is there a way to make a login with composite username (username + user_role)? My User Model: class CustomUser(AbstractUser): db = 'default' name = models.CharField(blank=True, max_length=255) TYPE_CHOICES = ( (1, 'School'), (2, 'Teacher'), (3, 'Parents'), ) user_type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, default=3) created_date = models.DateTimeField('date_created', auto_now_add = True, null=True) phoneNumber = models.CharField(default='', max_length=255) password = models.CharField(max_length=100) def __str__(self): return self.name -
Django giving SQL syntax error while creating models
I am using mysql as my database with mysql server 5.7.26 There is a model class called Tickets in app/models.py in django app: from django.db import models from django.core.validators import MinLengthValidator from django_mysql.models import JSONField from django_mysql.models import ListCharField class Tickets(models.Model): ticket_id = models.AutoField(verbose_name="Ticket ID" ,primary_key=True,null=False) title = models.CharField(verbose_name="Title", max_length=256) description = models.TextField(verbose_name="Description",) raised_by_signum = models.CharField(verbose_name="Customer Signum", max_length=7,validators=[MinLengthValidator(7)],blank=False,null=False) raised_by_email = models.EmailField(verbose_name="Customer Email",blank=True) assignee = models.CharField(verbose_name="Current Assignee", max_length=50, blank=True,null=True) priority = models.CharField(verbose_name="Priority", choices=[('Highest','Highest'),('High','High'),('Medium','Medium'),('Low','Low'),('Lowest','Lowest')],max_length=50,null=True) tags = ListCharField(base_field=models.CharField(max_length=20),size=20,verbose_name="Tags", blank=True, null=True,max_length=(20 * 21)) status = models.CharField(verbose_name="Current Status", choices=[('New','New'),('Open','Open'),('Closed','Closed'),('Inprogress','Inprogress')],max_length=50) tech = models.CharField(verbose_name="Subcategory" , choices=[('2G','2G'),('3G','3G'),('4G','4G'),('5G','5G')],max_length=50) market_ref = models.CharField(verbose_name="Market", max_length=256,blank=True) date_created = models.DateField(verbose_name="Date Raised",auto_now=True) date_resolved = models.DateField(verbose_name="Date Resolved",blank=True, null=True) is_accepted = models.BooleanField(verbose_name="Is Accepted", default=False) eric_user = models.CharField(verbose_name="Accepted By", max_length=7, validators=[MinLengthValidator(7)],null=False,blank=False,default='exxxxxx') logs = JSONField(verbose_name="Logs",null=True) attachments = models.FileField(verbose_name="File",null=True,upload_to='customer_files',blank=True) When i run migrations on these models it gives whole bunch of error regarding SQL syntax errors. Operations to perform: Apply all migrations: admin, auth, contenttypes, polls, sessions Running migrations: Applying polls.0001_initial...Traceback (most recent call last): File "C:\Users\eurnkan\Desktop\feku\myenv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql) File "C:\Users\eurnkan\Desktop\feku\myenv\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "C:\Users\eurnkan\Desktop\feku\myenv\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\eurnkan\Desktop\feku\myenv\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\eurnkan\Desktop\feku\myenv\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1064, "You have … -
Understanding nginx and configuring it for django production server: Invalid method while reading client request line
I am running a dockerized django app. I would like to add nginx in a docker container and then deploy it to an AWS EC2 instance and connect this instance to my domain that I bought. I already have my EC2 instance and domain but before deploying it there I want to try and run my production settings locally. I configured nginx according to tutorials, but I'm very much a beginner here. Right now I am getting this error: client sent invalid method while reading client request line, client: 172.18.0.1, server: localhost:8000 I up my server with docker-compose -f production.yml up Now my question is: How can I solve this error and also, is my configuration correct for a production server? this is my setting: production.yml version: '3' volumes: production_caddy: {} services: django: build: context: . dockerfile: ./compose/production/django/Dockerfile image: heatbeat_website_production_django env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start nginx: build: context: . dockerfile: ./compose/production/nginx/Dockerfile ports: - "0.0.0.0:8000:80" depends_on: - django redis: image: redis:5.0 dockerfile nginx FROM tutum/nginx RUN rm /etc/nginx/sites-enabled/default COPY ./compose/production/nginx/myconf.conf /etc/nginx/sites-enabled/default server { set $my_host $host; if ($host ~ "\d+\.\d+\.\d+\.\d+") { set $my_host "**mydomain.dev**"; } listen 80; server_name **mydomain.dev**; charset utf-8; error_log /dev/stdout info; access_log /dev/stdout; location / { … -
Python/Django: Replace different words in a string using matching array values
I'm working on a task where there is a string with text markers that need to be replaced with a given array with matching key value pairs. The key in the array must match with the markers in the string and replace it with the key's value. Ex: txt = "Hello #NAME#, Today is #DATE# and your subscription is ending in #NO_OF_DAYS# days." dict = {"#NAME#":"David", "#DATE#":"01/14/2020", "#NO_OF_DAYS#":"10"} The final text that must return after the replacement is, "Hello David, Today is 01/14/2020 and your subscription is ending in 10 days." How can I get this done in the simplest way? -
How do I deploying website by PythonAnywhere.com
I got this error message. enter image description here So I entered setting.py file and change like this ALLOWED_HOSTS = ['localhost', '127.0.0.1', '[::1]', '.pythonanywhere.com'] and Reload my site. but noting chaned. enter image description here at this time, I changed the code like this ALLOWED_HOSTS = ['heenamkang.pythonanywhere.com'] and then I got this error message. this is evidence that change is reflected. enter image description here enter image description here But I still can't enter the 'heenamkang.anywhere.com' third, fourth images are captured at exactly same time. plz help me ㅠㅜㅠㅜ