Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Different datetime in Postman and dbeaver
I have build a chatroom in Django and I record the datetime when a chatroom is created. But now that I'm testing on Postman to see if the datetime is correct, I get a datetime like 2022-03-11T14:35:55.812069Z trough Postman and on my dbeaver I have a datetime like 2022-03-11 11:35:55.812 -0300 The db that i'm using is PostgreSQL How can I check if the two datetime are equal? -
The simple django model for selectbox
Django model with models.Choices class Special(models.Choices): SPECIAL = (("welcome","My Welcome!"), ("privacy","my Privacy list"), ("happy","How happy you are"), ('',"-------------")) and I have this code in form class key_selector = forms.fields.ChoiceField( choices = Special.SPECIAL required=False, widget=forms.widgets.Select ) This error comes here TypeError: 'Special' object is not iterable How can I make the selectbox with django??? -
update JavaScript without refreshing page. Django framework
I don't know how AJAX works so coming for help guys. Simply want to update my javascript file without refreshing home page. Usually when refreshing home page then django views.py is refreshed and that's how I'm receiving data. I'm sure this is possible with AJAX as seen somewhere but not sure how that works. My javascript: <script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script> <script type="text/javascript"> /*extend leadlet - you should include the polli*/ L.RotatedMarker = L.Marker.extend({ options: { angle: 0 }, _setPos: function (pos) { L.Marker.prototype._setPos.call(this, pos); if (L.DomUtil.TRANSFORM) { // use the CSS transform rule if available console.log(this.options.angle); this._icon.style[L.DomUtil.TRANSFORM] += ' rotate(' + this.options.angle + 'deg)'; } else if(L.Browser.ie) { // fallback for IE6, IE7, IE8 var rad = this.options.angle * (Math.PI / 180), costheta = Math.cos(rad), sintheta = Math.sin(rad); this._icon.style.filter += ' progid:DXImageTransform.Microsoft.Matrix(sizingMethod=\'auto expand\', M11=' + costheta + ', M12=' + (-sintheta) + ', M21=' + sintheta + ', M22=' + costheta + ')'; } } }); L.rotatedMarker = function (pos, options) { return new L.RotatedMarker(pos, options); }; var locations = {{ data|safe }}; var PlaneIcon = L.Icon.extend({ options: { iconUrl: '{% static "media/plane.png" %}', iconSize: [25, 25], // size of the icon popupAnchor: [-3, -76] // point from which … -
Can I sort querydict in templates?
In my template I've got: {% for user in users %} <tr> <td> <div class="info"> <h4>{{ user.name }}</h4> <h5>{{ user.age }}</h5> </div> </td> </tr> {% endfor %} Usual {% for user in users|dictsort:"user.name" %} doesn't work as users is a queryset. Is there a way to display that in sorted order in the template without touching the backend? -
Send value from __init__.py to consumer.py websocket Django channels
I want to send data from the firebase stream(pyrebase) via django channels websocket. Web scoket is working fine, But I can't imagine how I can use consumer.py file send message function in init_.py. Here my django channel web socket Consumer.py file. import json from random import randint from asyncio import sleep from channels.generic.websocket import AsyncWebsocketConsumer from django.conf import settings class WSConsumer(AsyncWebsocketConsumer): group_name = settings.STREAM_SOCKET_GROUP_NAME async def connect(self): # Joining group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave group await self.channel_layer.group_discard( self.group_name, self.channel_name ) async def receive(self, text_data): print(text_data) # Send data to group await self.channel_layer.group_send( self.group_name, { 'type': 'system_load', 'data': text_data } ) async def system_load(self, event): # Receive data from group print('sending message to client') await self.send(text_data=json.dumps(event['data'])) This file works fine. This is my inti.py file. In this file, I want to send data to the WebSocket in this stream_handler function. import pyrebase from configFiles.config import config firebase = pyrebase.initialize_app(config) authe = firebase.auth() database = firebase.database() safe_temperature = 20 safe_humidity = 40 def stream_handler(message): if "Humidity" in message["path"]: if message["data"] > safe_humidity: database.child("Controller").child("Light").set(1) else: database.child("Controller").child("Light").set(0) if "Temperature" in message["path"]: if message["data"] > safe_humidity: database.child("Controller").child("Fan").set(1) else: database.child("Controller").child("Fan").set(0) # Here place I want to send … -
Problem in migrating my Django db from sqlite to mysql
I need to migrate my db from sqlite to mysql , I refered to following article which seems to be good https://www.shubhamdipt.com/blog/django-transfer-data-from-sqlite-to-another-database/ problem is data is not migrated to mysql db( but tables are created ) Can you recommend a solution -
Django selenium - StaticLiveServerTestCase - data initialized setUpClass: data available in first method called but not in the second method called
I have issue when initializing data in setUpClass with StaticLiveServerTestCase. I have define a method create_test_data() where I create all my objects (user, etc...). Then I have defined a class method with setUpClass (where create_test_data() is called) and 2 methods for 2 differents tests. My first test pass but not the second test. It seems that whereas data initialized are available for the first method/test1 there are no more available for the second/test2 method. Test pass if there run separatly. I tried using setUp method and SetUpTestData class method but neither works better. test.py def create_test_data(): # objects created class L_access_menu_creation_patient_TestCase(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(1) cls.selenium.maximize_window() cls.date_saisie = timezone.now() cls.selenium.get(cls.live_server_url) create_test_data() # test1 def test_menu_create_available_admin(self): username_input = self.selenium.find_element_by_name("username") username_input.send_keys('admin') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('admin') # click sur le bouton 'connexion' pour valider login/mdp self.selenium.find_element_by_xpath('/html/body/form/button').click() # vérifier que le menu est affiché self.assertTrue(self.selenium.find_element_by_id('createmenu').is_enabled()) # click sur le bouton 'deconnexion' self.selenium.find_element_by_id('dropdownMenuButton').click() self.selenium.find_element_by_xpath('/html/body/nav/div/div/a[3]').click() # test2 def test_menu_create_available_test1(self): # add permission to user test1 self.test1 = User.objects.get(username='test1') content_type = ContentType.objects.get_for_model(Patient) permission = Permission.objects.get( codename='add_patient', content_type=content_type, ) self.test1.user_permissions.add(permission) # same test as above for admin user error raised: django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. -
Send initial arguments from a Django view to Dash and read it outside layout
I have an scatter plot on Dash. This scatterplot takes the values from SQL depending on the input parameter id. After querying the database with id, in case it is the first time it is accessed the given id element, it saves the x,y values in a csv. Then, Dash reads the given csv and plots it. Until here, everything works except that I am not able to read the value sent from the Django view. My approach is the following one: views.py: @api_view(['GET']) def chart(request): id = request.GET.get('ID', None) if not os.path.isfile(f"{processed_path}/{id}.csv"): # Query SQL with id in case the output_variable for the given id does not exist and write the csv file context['dash_context'] = {'target_id': {'value': id}} return render(request, 'plots/chart.html', context) chart.html: {% load plotly_dash %} {%plotly_app name="Genome" ratio=1% initial_arguments=dash_context} Dash application app = DjangoDash('Genome', id='target_id') ### Get id value passed to template <---- #Layout code Therefore, my question is: how can I read in the DjangoDash app the parameter that the user introduces in the url before displaying the layouts, which will be used to determine the input csv to read the x,y values in the layouts? -
Create chart with Apexchart in a for loop - Django
I have a list in a loop and I want to graph it in a loop. But it looks like below. Overlapping graphics. But I want it to be seen one by one. The reason for this is that the sent data is constantly added to index 0. I leave my codes below. enter image description here views.py for i in devices: query = client.query("select * from table where x='"+ str(i) +"' and time > now() -7d") series = query._get_series() values = series[0]['values'] for x in values: dto = datetime.strptime(x[0], "%Y-%m-%dT%H:%M:%SZ") dto += timedelta(hours=3) trdateTime = dto.strftime("%d/%m/%Y-%H:%M:%S") milisec = dto.timestamp() * 1000 + 10800000 tempVal = int(x[5][2:5])/10 humVal = int(x[5][5:8])/10 tempList.append(tempVal) humList.append(humVal) timeList.append(trdateTime) dataTemp = [milisec, tempVal] dataHum = [milisec, humVal] tempChartDatas.append(dataTemp) humChartDatas.append(dataHum) tempChartDatas2.append(tempChartDatas[:]) tempChartDatas2.append(",") humChartDatas2.append(humChartDatas[:]) tempList2.append(tempList[::-1]) humList2.append(humList[::-1]) timeList2.append(timeList[::-1]) context['logListT'] = zip_longest(timeList2, tempList2) context['logListH'] = zip_longest(timeList2, humList2) context["all"] = zip_longest(tempList2, humList2, tempChartDatas2, humChartDatas2) return render(request, 'index.html', context ) index.html --> this is chart {% for d,v in logListT %} <div class="row" style="border-bottom: 2px #293450 solid; padding-bottom: 25px; margin-top:2em;"> <div class="col-6"> <div id="chart-area{{ forloop.counter }}"></div> </div> <div class="col-6"> <div class="row" style="justify-content:space-evenly;"> <div id="chart3{{ forloop.counter }}"></div> <div id="chart4{{ forloop.counter }}"></div> </div> <div class="row" style="justify-content:center;"> <div class="tableScroll"> <table class="table"> <thead style="background-color:#0b1827; color:#4f5d82;"> <tr> … -
django user specific authentication method
i am planning a django web application with multiple tenants (or i call it companies). This means that my web application is used by multiple companies. Every company could shall set their own authentication method. For example company 1 and company 2 would like to use active directory and company 3 and 4 use the default django authentication system. But the users can associated with more than one company. I have build a little diagram: And at this point i'm stuck. Only existing users with the specific permission can create new user accounts. The primary key of a user is the email adress. I think the companies should "register" their domain if they would like to use another authentication method. For example company 1 have the domain xyz.de and all users in my web app with the domain in their email adress must authenticate them over the active directory from company 1. I think the user could type only their email adress in the login form and django can check if a specific authentication method is configured for the domain. And in the next step the user can type the password or he is redirect to the other authentication system. … -
Python Django Format Localization
I created my formats files for my project. And I have format file for all languages to be used in my project. According to the user's language, the relevant format file is automatically called by django. Can I call the definitions here based on the user's language? If I can call my definitions, my automatic transform methods will be ready. Your opinion is very valuable to me, thank you. formats/tr/formats.py: DATE_FORMAT = 'd F Y' TIME_FORMAT = 'H:i:s' STR_DATE_FORMAT = "%d.%m.%Y" STR_DATE_SQL_FORMAT = "%Y-%m-%d" STR_DATETIME_FORMAT = "%d.%m.%Y %H:%M:%S" STR_TIME_FORMAT = "%H:%M:%S" DATE_INPUT_FORMATS = ( '%d.%m.%Y', # '25.10.2022', '25.10.06' '%d/%m/%Y', # '25/10/2022' # '%d %B %Y', '%d %b. %Y', # '25 Ekim 2022', '25 Eki. 2022' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2022 14:30:59' '%d.%m.%Y %H:%M:%S.%f', # '25.10.2022 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2022 14:30' '%d.%m.%Y', # '25.10.2022' ) converts/datetime.py: class DateTime: from formats.tr import formats as ff def __init__(self): from formats.en import formats as ff if a == "tr": from formats.tr import formats as ff else: from formats.en import formats as ff @classmethod def to_string(cls, tarih, date_format=ff.STR_DATE_FORMAT, time_format=ff.STR_TIME_FORMAT): """ :param tarih: :return: """ if isinstance(tarih, datetime.datetime): return tarih.strftime("%s %s" % (date_format, time_format)) elif isinstance(tarih, datetime.date): return tarih.strftime(date_format) elif isinstance(tarih, datetime.time): … -
Arduino to Django server (l127.0.0.1) not connect
My Arduino Code is not connected with my Django server which run on webbrowser 127.0.0.1 what change are in my arduino code so I run locally tested My Arduino program is #include <ESP8266WiFi.h> const char* ssid = "Pravesh"; const char* password = "123456789"; const char* host = "localhost"; void setup() { Serial.begin(115200); delay(10); Serial.println(); Serial.print("Connection to"); Serial.println(ssid); WiFi.begin(ssid,password); while(WiFi.status() != WL_CONNECTED){ delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFI connected"); Serial.println("Ip address:"); Serial.println(WiFi.localIP()); // put your setup code here, to run once: pinMode(LED_BUILTIN,OUTPUT); digitalWrite(LED_BUILTIN, LOW); } void loop() { // put your main code here, to run repeatedly: Serial.print("Connecting to host"); Serial.println(host); WiFiClient client; const int httpPort = 80; delay(3000); if (!client.connect(host,httpPort)){ Serial.println("Connection failed"); return; } Serial.println("***"); } In the Serial monitor is shows connection failed -
Reload all django url's files without restarting server
I need to change my urls in site without reloading server. Using: Django 4.0.2 if type == 'Name': urlpatterns.append(path('<slug:slug>/', details)) if type == 'Id': urlpatterns.append(path('<int:pk>/', details)) So if param type change, django don't see that, cause urls.py runs only on server reload Probably we can make server reload, but for sure not manualy -
ModuleNotFoundError: No module named 'django_filter'
I'm trying to use django-filter on my application but I get the error 'ModuleNotFoundError: No module named 'django_filter' Below is my code base settings.py ''' ... 'django_filter' ... ''' I have also installed django_filter in my application. -
Filter a QuerySet based on matching field in another QuerySet but restricted to an associated field in the other QuerySet
I am trying to create a filter based off two query sets of two related models (both already previously filtered). The first returns a list of IDs and concepts (names) with associated values (definitions). dqs: ID + concept + definitions + associated language (any one of four) For example: <QuerySet [<Definition: Definition (en) for #39: CBD, central business district: definition text>, <Definition: Definition (en) for #184: migration: definition text...> The second also has IDs and concepts which may or may not have matching values in the first list. tqs: ID1 + concept1 + terms (lang 1); ID1 + concept1 + terms (lang 2)...ID2 + concept1 + terms (lang 1) etc. For example: <QuerySet [<Translation: “other language term entry” (fr) for #1: abiotic component>, <Translation: “abiotic component” (en) for #1: abiotic component>, <Translation: “yet another language term entry” (es) for #1: abiotic component>...> IDs and concepts (expressed in English, the source language) are not language specific. Terms and definitions are language specific. So each concept+ID is associated with term entries and definitions in four different languages. I need to filter tqs so that it only displays entries that have matching IDs in dqs, and only in the language in which the … -
Django Form ChoiceField how to show more field name
i have a "little" problem. I want get ALL ModelChoiced field and don't know how to do that. My code parts models.py class Materials(models.Model): material = models.CharField(max_length=20,unique=True) density = models.PositiveSmallIntegerField() price = models.PositiveSmallIntegerField() def __str__(self): return self.material class Items(models.Model): article_number = models.CharField(max_length=20,blank=True,null=True) quantity = models.PositiveSmallIntegerField(blank=True,null=True) material = models.ForeignKey('Materials',on_delete=models.PROTECT,blank=True,null=True) surface =models.CharField(max_length=20,blank=True,null=True) . . . forms.py class ItemsForm(forms.ModelForm): class Meta: model = models.Items fields = "__all__" views.py def new(request): items_form = forms.ItemsForm() context = { 'items_form':items_form, } return render(request,"new.html",context) new.html {{ items_form.article_number }} {{ items_form.quantity }} {{ items_form.material }} {{ items_form.surface}} . . . So now, when open link, the generated html material code is <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> I want represent all Materials field value on each input, like this: <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> <select name="density" id="id_density"> <option value selected>---------</option> <option value="id_1">"density_1"</option> <option value="id_2">"density_2"</option> <option value="id_3">"density_3"</option> </select> <select name="price" id="id_price"> <option value selected>---------</option> <option value="id_1">"price_1"</option> <option value="id_2">"price_2"</option> <option value="id_3">"price_3"</option> </select> I tryed adding these line in ItemsForm but this method not get 'id', only just values: def __init__(self, *args, **kwargs): super(ItemsForm, self).__init__(*args, **kwargs) self.fields['density'] = forms.ModelChoiceField(queryset=models.Materials.objects.values_list('density',flat=True)) -
Displaying MySQL data on HTML page in Django - data not displaying
I am totally new to Django and I'm having a problem displaying data from a MariaDB MySQL database on a HTML page. I have a legacy database called Vision which has a table within it called SensorResult. I have added this database to the settings.py file and made a routings folder with a router_db.py file to tell the app when to use the Vision database. From this, I ran the following command: python manage.py inspectdb --database=Vision This returned a printout of each table within the database and all columns. I then used this to create a standard models.py file using this information as shown below: from django.db import models class Sensorresult(models.Model): sensorresult = models.AutoField(db_column='SensorResult', primary_key=True) # Field name made lowercase. sensorid = models.IntegerField(db_column='SensorID') # Field name made lowercase. visionid = models.IntegerField(db_column='VisionID') # Field name made lowercase. userinputid = models.IntegerField(db_column='UserInputID', blank=True, null=True) # Field name made lowercase. value = models.FloatField(db_column='Value') # Field name made lowercase. timestamp = models.DateTimeField(db_column='TimeStamp') # Field name made lowercase. class Meta: db_table = 'SensorResult' From this, I used makemigrations and migrate commands to submit this model. Now I can open the Django Shell and query the database and get a response, which makes me think that the … -
Uploading file by filefield returns Bad Request SuspiciousFileOperation
views.py if request.method == 'POST': form = MeasuringCodesForm(request.POST, request.FILES) files = request.FILES.getlist("file_field") if form.is_valid(): with transaction.atomic(): for each_file in files: new_code = MeasuringCodes(file_field=each_file) new_code.mediaplan = Mediaplan.objects.get(campaign=campaign_id) new_code.added_by = request.user new_code.save() models.py MEASURING_CODES_PARENT_PATH = 'measuring_codes/' def upload_measuring_codes_direction(instance, filename): return os.path.join(settings.MEDIA_ROOT, MEASURING_CODES_PARENT_PATH, str(instance.mediaplan.mediaplan_octi_id), filename) class MeasuringCodes(models.Model): updated = models.DateTimeField(auto_now_add=True) mediaplan = models.ForeignKey('Mediaplan', on_delete=models.CASCADE) added_by = models.ForeignKey('User', on_delete=models.PROTECT) file_field = models.FileField(upload_to=upload_measuring_codes_direction) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/files/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') And while uploading it i get bad request Detected path traversal attempt in '/x/y/files/measuring_codes/6RvVqvgp_L9cS/20220311124341089314_0' nginx.conf And on my local database everything works ok, even on wb.save(filename=os.path.join(MEDIA_ROOT, mp_file_path)) uploading works perfectly with actually same link (x/y/files/...) What should i change, something with upload_to attribute is executing badly and takes at beginning another storing route? -
How do you avoid multiple bootstrap offcanvas overriding each other?
I am coding a website using django, and want to visualize django models in my html template. I run a for loop iterating the models, and creates a offcanvas button for each. When output the model title in the different offvanvas, they overwrite each other. I have two models with titles: 628671 and 801451, but no matter which offcanvas button i click, it the same. The format {{ data.title }} is correct and i used to showcase list of models succesfully with title as in picture_1(Models with titles). So there seem to be a problem with offcanvas overriding each time i render the button in my loop. HTML code: {% for data in emotion_data %} <-- this is in the html file, it is a django-tool. <div class="offcanvas-header"> <h5 class="offcanvas-title" id="offcanvasBottomLabel">{{ data.title}}</h5> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body large"> <div id="{{ data.title }}" class="chart" style="width: 100%; min-height: 500px;"></div> </div> </div> <td><a href="#">{{ data.title }}</a></td> <td> <button type="button" id="{{ data.title }}" class="btn btn-primary" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottomLabel"> Vis graf </button> </td> Picture_1:Models with title Picture_2: Offcanvas example -
Django + Javascript : Table columns build dynamically with JSON datas. Row structure broken
I retrieve on my (Django template) page 2 sets of data : 1: warehouses 2: items. With the first I wan't to create dynamically the TD's of my table after getting an Ajax search response from my view. I want to create all TD for all warehouses available in the warehouses JSON and if a product has a stock on this warehouse PK, in the same time, I populate the QTY tableBody.innerHTML += ` [...] <td>${item.fournisseur__nom}</td>`; JSON.parse(warehouses).forEach((wh) => { tableBody.innerHTML += ` <td> `; for (let i = 0; i < item.sststock.length; i++) { if (item.sststock[i].sst_id == wh.pk) { tableBody.innerHTML += item.sststock[i].qty; } }; tableBody.innerHTML += ` </td> `; }); tableBody.innerHTML += ` <td>${item.qty}</td> [...] Alas, here the result : Also new at JS, I don't understand why I need to json.PARSE twice my warehouse datas once at the top of my script, and another time in when I foreach Warehouses for building TD's. Otherwise, a warehouses.forEach is not a function error raises. JSON Warehouses : [{"model": "warehouses.warehouse", "pk": 1, "fields": {"code": "TRE"}}, {"model": "warehouses.warehouse", "pk": 2, "fields": {"code": "BAG"}}, {"model": "warehouses.warehouse", "pk": 3, "fields": {"code": "DROP"}}, {"model": "warehouses.warehouse", "pk": 4, "fields": {"code": "RN3"}}] I pass my warehouse data in … -
How to save IP address in django and check the saved value
I have to do an exercise: save IP address of admin and print an alert if this address change. I tried a lot of times, even with middleware but it doesn't work. #models.py from django.db import models from django.utils import timezone from django.conf import settings from django.contrib.auth.models import User from smapp.utils import sendTransaction from django.shortcuts import get_object_or_404 import hashlib def random_number(): return User.objects.make_random_password(length=10,allowed_chars='123456789') # Create your models here. class Lot(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=100) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) tracking_code=models.CharField(max_length=10,default=random_number) hash=models.CharField(max_length=64,default=None,blank=True) txId=models.CharField(max_length=66,default=None,blank=True) def writeOnChain(self): self.hash = hashlib.sha256(self.text.encode('utf-8')).hexdigest() self.txId = sendTransaction(self.hash) self.save() def publish(self): self.save() def __str__(self): if not self.hash: return str(self.writeOnChain()) else: return self.title class ip(models.Model): ip_address = models.GenericIPAddressField() And then my view: from django.shortcuts import render,HttpResponse from .models import Lot from .models import ip # Create your views here. def client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') get_ip= ip() get_ip.ip_address= ipaddress get_ip.save() return ipaddress def home_page(request): return render(request, 'smapp/home_page.html', {}) def lot_details(request): if request.method == "POST": searched = request.POST['searched'] tracks=Lot.objects.filter(tracking_code__contains=searched) return render(request, 'smapp/lot_details.html', {'searched': searched,'tracks':tracks}) else: return render(request, 'smapp/lot_details.html', {}) My question is: there is a way to do it? get_ip.save() where save my ip address and where i can check it? My problem is not to find … -
how to add print button that prints all the inserted records in django admin side?
[enter image description here][1] How Can I print all the inserted records by adding the print button? [1]: https://i.stack.imgur.com/yS1A0.png -
How to debug angular frontend with django server on vscode (Unverified Breakpoint)?
I'm running a django server for the backend of my application and angular for the frontend side. Basicaly to make my application work I start my django server: python manage.py runserver And on angular I use: ng build --output-path django_static_folder/ang --watch --output-hashing none I'm trying to debug angular code using vscode. I have an issue with "Unverified Breakpoint" on vscode. I checked many thread about this issue but none of them talked about how to debug when the server is not managed by angular using ng serve Here is my actual configuration: { "version": "0.1.0", "configurations": [ { "name": "Angular debug", "type": "firefox", "request": "launch", "url": "http://127.0.0.1:8000/", "webRoot": "${workspaceFolder}", } ] } The workspaceFolder is my angular workspace folder. The url is the one from django server. So when I start the debugger, the firefox app launch and I'm in my application but I cannot put any breakpoint. I believe that the issue is coming from the fact that I'm not using angular server. Maybe I should but then I don't know how to redirect to the correct url on the django server side ? Can anyone help me on this subject ? -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'generate_payroll' with no arguments not found
this is my views.py def qualified(request, employee_id): current_date = datetime.date.today() _history = PayrollModel.objects.all() for her in _history: if(her.employee_id_id == employee_id): # mnt = her if((current_date.month != her.month_year.month and current_date.month > her.month_year.month) and current_date.year == her.month_year.year): return messages.success(request, "HAPPY BD") else: return messages.success(request, "SAD BD") def generate_payroll(request, employee_id): qualification = qualified(request, employee_id=employee_id) current_date = datetime.date.today() if (qualification == True): overTimeValue = calculate_overtime(employee_id) allowanceValue = calculate_allowance(employee_id) bonusValue = calculate_bonus(employee_id) employee = EmployeeModel.objects.get(pk=employee_id) salary = PayGradeModel.objects.get(pk=employee.basic_salary_id) ssf = calculate_ssf(salary) netValue = (float(salary.amount) + float(overTimeValue) + float(bonusValue) + float(allowanceValue)) - float(ssf) # allowanceValue payroll = PayrollModel.objects.create(employee_id_id=employee_id) payroll.month_year = current_date payroll.basicSalary = salary.amount payroll.ssf_deduction = float(ssf) payroll.over_time = float(overTimeValue) payroll.bonus = float(bonusValue) payroll.allowance = allowanceValue payroll.gross_pay = salary.amount payroll.net_salary = float(netValue) payroll.save() messages.success(request, 'payroll generated successfully') return HttpResponseRedirect('/get_payroll') else: # payrolls = PayrollModel.objects.filter(employee_id_id=employee_id) return render(request, 'payrolls/get_payroll.html', {'payrolls': payroll} models.py class PayrollModel(models.Model): month_year = models.DateField(null=True) # month_year = MonthField( # "Month value", help_text="some help...", null=True) gross_pay = models.CharField(max_length=100, null=True) bonus = models.CharField(max_length=100, null=True) allowance = models.CharField(max_length=100, null=True) ssf_deduction = models.CharField(max_length=100, null=True) over_time = models.CharField(max_length=100, null=True) net_salary = models.CharField(max_length=100, null=True) employee_id = models.ForeignKey( EmployeeModel, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class Meta: db_table = 'payrolls' ordering = ['-updated', '-date_created'] urls.py path('employees/<int:pk>/payrolls/generate_payroll', views.generate_payroll, name='generate_payroll'), … -
How to manually create a cron job to run a Django script?
I have been trying to run some code as a cron job using Django. There are a number of packages that help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up: */30 * * * * python3.8 /var/djangoproject/crons/cron.py Is this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea.