Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send text by template via url in Django?
I want to send text to a view via template. I have two different types of clients that will be processed differently, to take advantage of code I put it in a single view and the specific part treated it with an if else. In the template: <a href="{% url 'client' 'prime' %}"> Client prime </a> <a href="{% url 'client' 'free' %}"> Client </a> In the urls.py .... path('client/<str:typeclient>', Client, name='client'), ..... In the view: def Client(request, typeclient): ... if typeclient == "prime": ... else: .... However I get the following error: NoReverseMatch at / Reverse for 'client' with no arguments not found. 1 pattern(s) tried: ['client\\/(?P<typeclient>[^/]+)$'] Apparently the text is not passing as a parameter that I inserted in the url. In this sense, how can I pass a text from the template via url? -
How to filter in django by greater than or less than dates?
I'm a little confused with the documentation on Django Rest Framework. I have read it several times but I cannot makes sense of it. Maybe I'm not smart enough, I do not know, but I'm trying to create a filter in an Endpoint that let me consult information according to dates, like GET /my-endpoint/?created_at__lte=2020-01-01 // get items created in a date less than 2020-01-01 GET /my-endpoint/?created_at__gte=2020-01-01 // get items created in a date greater than 2020-01-01 I created a filter class class MyEndpointFilter(django_filters.rest_framework.FilterSet): created_at_gte = IsoDateTimeFilter(name="created_at", lookup_expr='gte') created_at_lte = IsoDateTimeFilter(name='created_at', lookup_expr='lte') updated_at_gte = IsoDateTimeFilter(name='updated_at', lookup_expr='gte') updated_at_lte = IsoDateTimeFilter(name='updated_at', lookup_expr='lte') class Meta: model = MyEndpointModel fields = ( 'created_at', 'updated_at', ) And a class view class MyEndpointViewSet(viewsets.ReadOnlyModelViewSet): filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, OrderingFilter ) filterset_class = MyEndpointFilter filterset_fields = {'created_at': ['gte', 'lte'], 'updated_at': ['gte', 'lte']} # I also tried without this line queryset = LogClaimAction.objects.all() serializer_class = MyEndPointSerializer But still, the filter doesn't work. Can someone point me to the mistake I am making? -
ValueError: Dimensions must be equal, with input shapes
I have written this code. My input shape is (100 x100 X3). I am new to deep learning. I have spent so much time on this, but couldn't resolve the issue. Any help is highly appreciated. init = tf.random_normal_initializer(mean=0.0, stddev=0.05, seed=None) input_image=Input(shape=image_shape) # input: 100x100 images with 3 channels -> (3, 100, 100) tensors. # this applies 32 convolution filters of size 3x3 each. model=Sequential() model.add(Conv2D(filters=16, kernel_size=(3, 3),kernel_initializer=init, padding='same', input_shape=(3,100,100))) model.add(Activation('relu')) model.add(Conv2D(filters=32,kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2),padding="same")) model.add(Dropout(0.25)) model.add(Conv2D(filters=32,kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(Conv2D(filters=32, kernel_size=(3, 3),padding="same")) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2),padding="same")) model.add(Dropout(0.25)) model.add(Flatten()) # Note: Keras does automatic shape inference. model.add(Dense(256)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(10)) model.add(Activation('softmax')) model.summary() sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) len(model.weights) model.compile(optimizer="Adam", loss="mse", metrics=["mae", "acc"]) Error : In [15]: runfile('/user/Project/SM/src/ann_algo_keras.py', wdir='/user/Project/SM/src') Random starting synaptic weights: Model: "sequential_3" Layer (type) Output Shape Param # conv2d_12 (Conv2D) (None, 3, 100, 16) 14416 activation_18 (Activation) (None, 3, 100, 16) 0 conv2d_13 (Conv2D) (None, 3, 100, 32) 4640 activation_19 (Activation) (None, 3, 100, 32) 0 max_pooling2d_6 (MaxPooling2 (None, 2, 50, 32) 0 dropout_9 (Dropout) (None, 2, 50, 32) 0 conv2d_14 (Conv2D) (None, 2, 50, 32) 9248 activation_20 (Activation) (None, 2, 50, 32) 0 conv2d_15 (Conv2D) (None, 2, 50, 32) 9248 activation_21 (Activation) (None, 2, 50, 32) 0 … -
Django form to save several records for a given model. bulk_create() buffer
Say I have the following: models.py class Project(models.Model): project_name = models.CharField(primary_key=True, max_length=100) # ... other fields ... comments = models.CharField(max_length=150) class Milestone(models.Model): milestone = models.CharField(primary_key=True) class ProjectMilestone(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) project_name = models.ForeignKey(Project) milestone = models.ForeignKey(Milestone) date = models.DateField() My purpose is to create a forms.py, and the corresponding views.py and .html files, so the user could enter one project and several milestones for that project at the same time. The ideal interface would allow the user to write the project and its fields, and then select a milestone and a date, buffer this data, and select as many other milestones more as wanted. Then, submit all to both models. I have been checking the "bulk_create()" approach, which I think it could work if several milestones are introduced in an auxiliary table via JavaScript to buffer their data, but there are some caveats in the documentation I am not confident about. Any guideline please? -
Upload file Vue 3 and Django REST
I dont get if i work with request correctly, after upload all files is 1 KB and i cant open them. How to create correct file? If i save file as .doc i can see: ------WebKitFormBoundaryt3UjlK5SVq8hgppA Content-Disposition: form-data; name="file" [object FileList] ------WebKitFormBoundaryt3UjlK5SVq8hgppA-- So my functions to submit in js file: async submitFiles() { let formData = new FormData(); formData.append('file', this.file); console.log(this.file) axios.put(`/api/v1/myapp/upload/${this.file[0].name}`, formData, { headers: { 'Content-Disposition': 'attachment', 'X-CSRFToken': await this.getCsrfToken(), }, } ).then(function () { console.log('SUCCESS!!'); }) .catch(function () { console.log('FAILURE!!'); }); }, To handle change of file in form fileChanged(file) { this.file = file.target.files }, And finally my view.py class FileUploadView(APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] handle_uploaded_file(file_obj) return Response({'received data': request}) Where def handle_uploaded_file(f): with open('path/to/my/folder/' + str(f.name), 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) -
My django objects get affected when I commit changes in heroku with git
My django admin panel objects get affected when I commit changes in git for my heroku website. I commit changes to my heroku website from following command in terminal - git add . git commit -am "make it better" git push heroku master before committing when I add new model - This is the image of the newly added object in django admin panel after committing changes it disappeared - image after committing changes Is there any solution for that committing changes does not affect these objects in django admin panel ? -
django autocomplete light can't input string
i've tried using django-autocomplete-light with following the docs guide, and in the end i cannot input string to search the data, here the picture I can't input string to search data. heres my code: views.py from django.shortcuts import render from .models import * from .forms import PendaftaranForm from dal import autocomplete # Create your views here. class DesaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! #if not self.request.user.is_authenticated: #return Country.objects.none() qs = Desa.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs models.py class Desa(models.Model): nama = models.CharField(max_length=30) kecamatan = models.ForeignKey(Kecamatan, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.nama urls.py from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path('', views.index, name='index'), url( r'^desa-autocomplete/$', views.DesaAutocomplete.as_view(), name='desa-autocomplete', ), ] forms.py from django import forms from .models import * from tempus_dominus.widgets import DatePicker from dal import autocomplete class PendaftaranForm(forms.ModelForm): class Meta: model=Pendaftaran fields= ( 'tanggal_pendaftaran', 'nama', 'desa', 'kecamatan', 'mutasi', 'jumlah', 'keterangan', 'tanggal_selesai', ) widgets = { 'tanggal_pendaftaran':DatePicker( attrs={ 'append': 'fa fa-calendar', 'icon_toggle': True, } ), 'nama':forms.TextInput( attrs={ 'class':'form-control', } ), 'desa':autocomplete.ModelSelect2( url='desa-autocomplete', attrs={ 'class':'form-control', } ), ... how can i input the string to search? is there anything wrong with my code? … -
Django Failed to load css
I have installed Geonode ( geospatial content management system), which is available on URL armsis.cas.am. It worked fine, but now there is a problem with CSS. I get an error GET http://armsis.cas.am/static/geonode/css/base.css net::ERR_ABORTED 403 (Forbidden) I thought the problem was in the path to static folder, but I get images from the same folder. Any ideas? ('m not a programmer, but I have some skills in Python/Web) -
Django verbose_name of reverse relation
I have a model like: class Question(models.Model): ... class Answer(models.Model): question = models.ForeignKey( Question, null=False, blank=False, on_delete=models.CASCADE, related_name='answers', verbose_name='translated name' ) I would now like to use the verbose_name in a template (as it is translated) over the reverse relation like {{ question.answers.verbose_name }}. Unfortunately this does not work. On the other hand {{ question.answers.related_name }} works. So it seems that in the reverse_relation only the related_name is available. Is there any way to get the verbose_name from the reverse relation? -
.mp4 file is not playing in Django template and FireFox or Chrome
I can save live RTSP video stream in .mp4 but when I run saved .mp4 video in Django template or Firefox or Chrome browser or VLC, video is not playing in ubuntu. I think I have a compatible issue problem in .mp4. Furthermore, I want to show and play .mp4 saved file in Django. I have a two IP camera which provides a live RTSP video stream. self.input_stream---> rtsp://admin:Admin123@192.168.1.208/user=admin_password=Admin123_channel=0channel_number_stream=0.sdp self.input_stream---> rtsp://Admin:@192.168.1.209/user=Admin_password=_channel=0channel_number_stream=0.sdp Python 3.8.5 (default, Jul 28 2020, 12:59:40) [GCC 9.3.0] on linux, Django==3.1.2 I am implementing this code in difference Ubuntu PCs Ubuntu = 18.04 and 20.04 opencv-contrib-python==4.4.0.46 opencv-python==4.4.0.46 ffmpeg version 4.2.4-1ubuntu0.1 Copyright (c) 2000-2020 the FFmpeg developers built with gcc 9 (Ubuntu 9.3.0-10ubuntu2) I had tried different fourcc to save .mp4 but below fourcc work perfectly in Ubuntu. fourcc = cv2.VideoWriter_fourcc(*'mp4v') class ffmpegStratStreaming(threading.Thread): def __init__(self, input_stream=None, output_stream=None, camera=None, *args, **kwargs): self.input_stream = input_stream self.output_stream = output_stream self.camera = camera super().__init__(*args, **kwargs) def run(self): try:vs = cv2.VideoCapture(self.input_stream) fps_rate = int(vs.get(cv2.CAP_PROP_FPS)) ############################## ############################## # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id)) # ~ vs.set(cv2.CAP_PROP_POS_FRAMES,50) #Set the frame number to be obtained # ~ print('fps rate-->', fps_rate,'camera id-->' ,str(self.camera.id),' ####### ') # initialize the video writer (we'll instantiate later if need be) writer … -
Different CMDs - difference for Python
I am a Windows10 user learning Django. And I am trying to run a server on my local device. While using the PyCharm command prompt, I constanly got some errors. A previous one, for example, was caused by SSLError (error was fixed thanks to Stackoverflow answers). Currently while doing the "runserver" command I am getting a new error: ImportError: DLL load failed while importing _sqlite3: module not found. At the same time there were and there still are absolutely no errors shown while using same django commands, but in Anaconda prompt. Why is that so? What's the difference between prompts? How to make the PyCharm command prompt work normally? "Anaconda3", "Anaconda3\scripts" and "Anaconda3\Library\bin" have been added to my PATH already. (According to answers found among Stakoveerflow, adding them is the number one solution / advice). Thank you! -
how to handle multiple keyword parameters in Django RestFramework URL
this my current url url("sample/userid",views.sample) I can query the data by userid or postid or x, or y parameters. how to handle this efficiently in a single url In the views, I will use kwargs to get the keywords, but not sure how to handle it in the url. -
Django ORM update field to NOW() returning 0 error
I am trying to loop through a list of results, process them, then update their "updated_details" field. users_to_update = TiktokUser.objects.filter(Q(updated_details__lt=datetime.utcnow() - timedelta(weeks=1)) | Q(updated_details__isnull=True))[0:1] for user_to_update in users_to_update: print(datetime.now()) user_to_update.updated_details = datetime.now() user_to_update.save() The idea being that on each loop, i set the updated_details to the current timestamp. My print() statement here correctly prints out the current date and time, however when I update the record itself and save, I get the following error: ['“0000-00-00 00:00:00.000000” value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) but it is an invalid date/time.'] Which implies to me it is attempting to set it to 0. My model definition is: class User(models.Model): ... updated_details = models.DateTimeField(blank=True, null=True) ... How do I get Django to set the field to the current DateTime? -
Djnago background task function not excecuting
I am using Django background task in my project. pip install django-background-task and Django background task is started by cron-jobs But background task function is not executing all the time.. in the database entry is automatically generating in background_task and background_task_completedtask table. but my functionality is not executing. could any one check ? I am stuck here and not able to do other data. my code is showing below views.py @api_view(['DELETE']) @permission_classes([IsAuthenticated]) def remove_finger(request): try: validation_msg = '' employee = Employee.objects.get(pk=request.query_params.get("EmployeeId")) finger_data = FingerPrintInfo.objects.filter(Activation=request.query_params.get("FingerId"), Employee=request.query_params.get("EmployeeId")) if not finger_data: validation_msg = validation["FDP7"] if validation_msg != '': return Response({msg: validation_msg}, status=status.HTTP_400_BAD_REQUEST) else: fing = finger_data.order_by('FingerPrintId') fingerId = fing[3].FingerPrintId finger_data.delete() FingerPrintActivation.objects.filter(pk=request.query_params.get("FingerId")).update( ActivationStatus=progress_msg["removed"], ActivationMessage=validation["FDP31"], ModifiedDate=date.today(), ModifiedUser=request.user.id ) remove_fingerprint(request.query_params.get("EmployeeId"), fingerId) return Response({msg: successMsg}, status=status.HTTP_200_OK) my tasks.py @background(schedule=django.utils.timezone.now()) def remove_fingerprint(empId, fingerId): """ Remove FingerPrint data from all Device Parameters: EmployeeId: FingerPrint Data Returns: Background Process Execute """ try: json_input = { "EmployeeID": empId, "FingerPrintID": fingerId } employee = Employee.objects.get(EmployeeId=empId) if employee.Security == static_values["const1"]: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"])) else: emp_device = Device.objects.filter(~Q(DeviceStatus=static_values["const0"]), DefaultAccess=True) for div in emp_device: try: url = "http://"+ div.DeviceCode + "/DeleteFingerprint" resp = requests.post(url, json=json_input) if not resp.text.__contains__('200'): logging.getLogger("info_logger").info("Fingerprint not removed from in " + div.DeviceCode) except Exception as ex: logging.getLogger("info_logger").info("Fingerprint not removed from in … -
Update specific ORM object with self object attribute from filtered queryset
I'm wondering is there any option to update current ORM object from filtered queryset with a new value which comes from current object? Seems bit complicated so maybe I show you an example: Model looks like: class Car(models.Model): car_id = models.CharField(max_length=100) initial_value = models.IntegerField(null=True) end_value = models.IntegerField(null=True) And some cars in my DB have initial_value but doesn't have an end value, and I want to copy/update the initial_value from specific object to end_value, where end_value is None: And I know that there exists an ORM formula which update my object with given value in queryset: Car.objects.filter(end_value__isnull=True).update(end_value=100000) But I cannot pass object initial_value to end_value in update method Car.objects.filter(end_value__isnull=True).update(end_value=initial_value) <-- Error Please help, how can I pass object attribute to update attribute? Maybe there is different approach? -
django admin sort calculated fields in listview
I have two models, one (Device) which has a foreign key to the other (Storage). In the admin overview of Storage I wanna be able to add a count of how many Device has pointed to each Storage. Using the code below I'm able to correctly count the number of Devices pointing to each Storage. However, when trying to sort by the number in storage it crashes with the following error. Cannot resolve keyword '_get_device_number' into field. Choices are: ... #List of fields So my question is, how do I add my calculated field into the list allowed searches. class Device(models.Model): ... storage_id = models.ForeignKey(Storage, on_delete=models.PROTECT, blank=True,null=True) #Allowed to be null since a Device may not be in storage. class Storage(models.Model): ... def _get_device_number(self,): return Device.objects.filter(storage_id=self.storage_id).count() class StorageAdmin(admin.ModelAdmin): ... list_display = ['str', 'get_device_number',] def get_device_number(self, obj): return obj._get_device_number() get_device_number.admin_order_field = '_get_device_number' -
Change default port for django swagger-ui
I want to change the default port of swagger-ui to 8080 but my main Django API should listen on a different port. I have tried this in setting.py : SWAGGER_SETTINGS = { "base_path": 'localhost:8080/', } But still, the port of swagger-ui is not changed. I have also added this schema in urls.py of my project. # schema for swagger view schema_view = get_schema_view( openapi.Info( title="XMeme API", default_version='v1', description="Meme Stream", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="sonirudrakshi99@gmail.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_api.urls')), path('swagger-ui/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # Included another URLconf of swagger api ] -
Use Django REST framework serializer to save JSON requests to database
I'm absolutely new to Django and for some reason, I had to jump right to Django REST framework. I want to save JSON objects sent as POST requests in my database. The JSON object looks like this: [{ "title": "Bitcoin Price Likely to Reach $50K Soon According to This Indicator", "description": "", "date": "2021-02-09T09:08:58Z", "link": "https://cryptopotato.com/bitcoin-price-likely-to-reach-50k-soon-according-to-this-indicator/", "keywords": [{ "name": "bitcoin" }], "source": "https://cryptocompare.com" }, { "title": "Post-Tesla News FOMO Helps Bitcoin Price to Surge Above $48,000", "description": "", "date": "2021-02-09T09:08:58Z", "link": "https://www.cryptoglobe.com/latest/2021/02/post-tesla-news-fomo-helps-bitcoin-price-to-surge-above-48000/", "keywords": [{ "name": "bitcoin" }], "source": "https://cryptocompare.com" }] I created my models like this: class Keywords(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class News(models.Model): title = models.CharField(max_length=100) description = models.TextField() date = models.DateTimeField() link = models.URLField() keywords = models.ManyToManyField(Keywords) source = models.CharField(max_length=30) class Meta: db_table = "News" # ordering = "-date" def __str__(self): return self.title serializers: class KeywordSerializer(serializers.ModelSerializer): class Meta: model = Keywords fields = ["name"] class NewsSerializer(serializers.ModelSerializer): keywords = KeywordSerializer(read_only=True, many=True) class Meta: model = News fields = ["title", "description", "date", "link", "keywords", "source"] and finally my view: class NewsView(APIView): def post(self, request): news_serializer = NewsSerializer(data=request.data, many=True) try: if news_serializer.is_valid(): news_serializer.save() return Response("Created successfully", status=status.HTTP_201_CREATED) except Exception as e: print(e) return Response("Error, Don't know what", status=status.HTTP_400_BAD_REQUEST) … -
making a top navigation bar along with a side navigation bar in html(django)
Here's the body of my layout html page: <body> <!-- navbar --> <header> <nav class="navbar navbar-expand-lg navbar-light fixed-top navbar-custom trans"> <div class="container-fluid"> <a href="#" class="navbar-brand"> <!-- <img src="static/events/iiitu.png" alt="logo" class="d-inline-block align-middle mr-2 py-3"> --> <img src="" alt="logo" class="d-inline-block align-middle mr-2 py-3"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse myNav" id="navbarNavDropdown"> <ul class="navbar-nav ms-auto"> <li class="nav-item"> <a style="color: black;" class="nav-link" aria-current="page" href="{% url 'events:home' %}">Home </a> </li> <li class="nav-item"> <a style="color: black;"class="nav-link active" href="#"> About Us </a> </li> <li class="nav-item dropdown"> <a style="color: black;" class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> User </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if not user.is_authenticated %} <li><a class="dropdown-item" href="{% url 'events:register' %}">Register</a></li> <li><a class="dropdown-item" href="{% url 'events:login' %}">Login</a></li> {% endif %} <!-- <li><hr class="dropdown-divider"></li> --> {% if user.is_authenticated %} <li><a class="dropdown-item" href="{% url 'events:post_create' %}">Share Something</a></li> <li><a class="dropdown-item" href="{% url 'events:logout' %}">Logout</a></li> {% endif %} </ul> </li> <li class="nav-item"> <a style="color: black;" class="nav-link" href="#"> Contact Us </a> </li> </ul> </div> </div> </nav> </header> {% block content %} {% endblock %} {% block body %} {% endblock %} {% block script %} {% endblock %} Now, what i am unable to understand is: Where should i keep the … -
Django ORM: Order by dates and weekdays
I have a table that stores courses and one that stores their dates and weekdays: Course: ID, CourseDates (M2M) CourseDate: ID, Date (Date), Weekday (0-6), Full (Boolean) If its a date, weekday is NULL If its a weekday, date is NULL Only dates can be set to full (full=True) Use case: I want to order by the next occurence (date or weekday) that is not full. Challenge: Weekdays should only be considered if there is no date that is full for that day. Example: Course 1 1, Date=2021-02-12, Weekday=NULL, Full=True 2, Date=NULL, Weekday=4 (Friday), Full=False Course 2 3, Date=2021-02-13, Weekday=NULL, Full=False Expected Result: Course 2 Course 1 Explanation: Next date for Course 2: 2021-02-13 Next date for Course 1: 2021-02-19 (because 2021-02-12 is full) Question: Can this be done using SQL/Django ORM only? Does it even make sense? My current attempt (this wont work in the above example): """ The subquery annotates all CourseDates with the difference to today, orders them by days left, and in the main query we only use the first entry, which is the closest CourseDate for this course """ subquery = ( CourseDate .objects .exclude(full=True) .filter(course=OuterRef('id')) .filter(Q(date__gt=today_date) | Q(date__isnull=True)) .annotate(today=Value(today_date, output_field=DateField())) .annotate( days_until_next=Case( When(weekday__lt=today_weekday, then=6 … -
how to copy the tables of influx db ( free versione ) into postgres
project-schema As you see in the pictures I have this kind of schema, I'll have many "measurements" (tables) into influxdb, that I need to copy into Postgresdb, so my django app will query the local copy instead of influxdb. i really don't know how to start, I found a lot of mirroring setup for sql-sql db , but I don't find nothing for "timeserie db" and "relational db" -
Only allow a certain domain to access my Django backend
I'm currently developing an application which consists of a React frontend, which makes frequent requests to a Django backend. Both the React and Django applications are running on the same server. My problem is I wish to hide my Django backend from the world, so it only accepts requests from my React application. To do so, I've been trying several configurations of ALLOWED_HOSTS in my Django settings.py, but so far none of them seem to be successful. An example route that I wish to hide is the following: https://api.jobot.es/auth/user/1 At first I tried the following configuration: ALLOWED_HOSTS=['jobot.es'] but while this hid the Django backend from the world, it also blocked the petitions coming from the React app (at jobot.es). Changing the configuration to: ALLOWED_HOSTS=['127.0.0.1'] enabled my React app to access the backend but so could do the rest of the world. When the Django backend is inaccessible from the outside world, a get request from https://api.jobot.es/auth/user/1 should return a 400 "Bad Request" status. The error I get when the React app fails to request data from the Django backend is the following: Access to XMLHttpRequest at 'https://api.jobot.es/auth/login' from origin 'https://jobot.es' has been blocked by CORS policy: Response to preflight request … -
What is Causing Encrypted Nginx Log Lines and ERR_SSL_PROTOCOL_ERROR in Docker Compose?
I am running three docker containers in a django production environment on a google cloud VM with firewall settings open to https traffic. I am using a chained cert that I obtained from godaddy and concatenated the certs as per nginx docs. My containers are a django app, postgres, and nginx acting as a proxy in order to serve static files. I am orchestrating them using docker-compose. I also have a public URL pointing to the public IP of the google vm. When going to the endpoint in a browser I get an "ERR_SSL_PROTOCOL_ERROR" If I tail the nginx logs on the vm I get encoded log lines, like: nginx_1 | 93.173.8.110 - - [09/Feb/2021:09:02:12 +0000] "\x16\x03\x01\x02\x00\x01\x00\x01\xFC\x03\x03C\x08!\xB3d\xC76P\xE5\x I confirmed that the nginx container is up and running and started with no errors. Is there something obvious I am doing wrong? And specifically a reason my nginx log entries are encrypted and non-readable? Here is the Dockerfile: ########### # BUILDER # # First build step in order to make final image smaller. # This is referenced in second build step. ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory #WORKDIR /usr/src/app WORKDIR /code # set environment … -
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Django
I'm getting this error whenever I'm trying to run python manage.py runserver in Django. The error: django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Why can that be? I think it is because my settings.py it is called base.py instead of settings.py and that's why Django doesn't detect that file as my settings file. If that's the case, how can I assign the settigns file to that base.py fiile? this is the base.py file: import os from pathlib import Path from django.urls import reverse_lazy # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ######################################## # APPS ######################################## INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.humanize', 'allauth', 'allauth.account', 'djstripe', 'captcha', 'users', ] ######################################## # MIDDLEWARE ######################################## MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ######################################## # SECURITY ######################################## SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = bool(os.getenv("DJANGO_DEBUG", "False").lower() in ["true", "1"]) ALLOWED_HOSTS = [] ######################################## # OTHER ######################################## ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' SITE_ID = 1 ######################################## # TEMPLATES ######################################## TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates", ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': … -
Insert database table name in raw sql in Django
I'm trying to pass the database table name into my raw sql query in Django like this: instance = Nutrient.objects.raw( ''' select * from %(table)s # <-- error here for system_time as of timestamp %(time)s where id=%(id)s; ''', params={'table': self.dbTable, 'time': timestamp, 'id': instance.id})[0] It works fine when I insert the timestamp or the instance id but it gives me an error on the table name: Error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/usr/local/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/usr/local/lib/python3.9/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) The above exception ((1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' 'foods_nutrient'\n for system_time as of timestamp '2021-0...' at line 1")) was the direct cause of the following exception: File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view return self.dispatch(request, *args, …