Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django nginx looking at static not staticfiles
I can't work this out, nginx insists on looking in a "static" folder even though I think I have given "staticfiles" as the location. Yet the logs are constantly showing the work "static" in the file path. Here is the nginx.conf: server { listen 80; server_name 10.88.58.95; location = /favicon.ico { access_log off; log_not_found off; } root /srv/pcc_django/; location /staticfiles/ { } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/run/gunicorn.sock; } } This is what the access logs are showing: 10.184.52.12 - - [18/Oct/2019:12:58:58 +0000] "GET /static/css/microblog/style.css HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:12:58:58 +0000] "GET /static/images/microblog/platform_control.png HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET / HTTP/1.1" 200 5916 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET /static/css/microblog/style.css HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 - - [18/Oct/2019:13:03:58 +0000] "GET /static/images/microblog/platform_control.png HTTP/1.1" 404 77 "http://10.88.58.95/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:69.0) Gecko/20100101 Firefox/69.0" "-" 10.184.52.12 … -
Django - testing emails with the outbox using post_office
I'm writing tests for an application that uses django-post_office package for most of its email functionality. The default django.core.mail library contains plenty of useful tools for testing whether or not there are actually emails being sent. (Without actually sending any during the tests) class TestFunctionThatSendsEmail(Testcase): @override_settings( EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend' ) def test_function_sends_email(self): self.assertEqual(len(outbox), 0) run_function_that_calls_email() self.assertEqual(len(outbox), 1) ... # other tests However, the emails in our function are being sent with the django-post_office mail.send() function # priority now to make sure that they are being sent right away mail.send( sender=sender, recipients=to, context=context, template=template_name, priority='now', ) Which causes the test above to fail as for some reason the emails do not end up in the outbox. The strange thing is that if I change the EMAIL_BACKEND to django.core.mail.backends.console.EmailBackend the emails do show up in my terminal, so it is listening to the EMAIL_BACKEND settings. I've tried finding alternative methods / functions to test this functionality in the django-post_office github, but all I could find was the advice to check to see if the emails are saved to the database and verify their status. (Which I did and works) but the fact that django seems to be unable to detect any emails actually being … -
Django authentication JWT vs Oauth2
I am new in django authentication system. I notice most of the company and developer always prefer Oauth2 over JWT based authentication. I just read Oauth2 documentation. I am not getting what special feature in Oauth2 has and why Oauth2 is very cool Can anyone explain it please? -
django permissions: User should only see and edit "his" objects
I'm building an app to manage flats: There are different administrations. Each administration has users. Every administrations owns properties and every property has 1 to n flats. Sofar so good. That's more or less setup. No comes the tricky part. The users of administration A should only be allowed to see properties and flats that their administration owns. How would I best do this? -
How to add executable to PATH in Azure KUDU?
I need to add the gecko driver in order to run a headless browser on Azure as part of my website, but I need to add the geckodriver to PATH (apparently I can't manually input the location of the geckodriver file in Python?) I know I have to use the applicatioHhost.xdt file and add it to /home/site folder, but my Kudu page doesn't allow me to add files (I can create the file using 'touch', but I can't edit it). This is how my Kudu page looks like: https://imgur.com/a/99oHUoC This is my applicationHost.xdt: <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <system.webServer> <runtime xdt:Transform="InsertIfMissing"> <environmentVariables xdt:Transform="InsertIfMissing"> <add name="geckodriver" value="geckodriverL" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> <add name="PATH" value="%PATH%;%HOME%\site\wwwroot\cpu" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" /> </environmentVariables> </runtime> </system.webServer> </configuration> This is the error I get from Django: WebDriverException at / Message: 'geckodriverL' executable needs to be in PATH. Request Method: GET Request URL: http://magicpcscout.azurewebsites.net/ Django Version: 2.2.6 Exception Type: WebDriverException Exception Value: Message: 'geckodriverL' executable needs to be in PATH. Exception Location: /antenv/lib/python3.7/site-packages/selenium/webdriver/common/service.py in start, line 83 Python Executable: /opt/python/3.7.4/bin/python3.7 Python Version: 3.7.4 Python Path: ['/opt/python/3.7.4/bin', '/home/site/wwwroot', '/antenv/lib/python3.7/site-packages', '/opt/python/3.7.4/lib/python37.zip', '/opt/python/3.7.4/lib/python3.7', '/opt/python/3.7.4/lib/python3.7/lib-dynload', '/opt/python/3.7.4/lib/python3.7/site-packages'] Server time: Fri, 18 Oct 2019 14:39:59 +0000 -
How can I make datetime.date more dynamic rather than manually entering a year?
I would like to make my code more dynamic by having a date use something like "next time it is August 1st". if form.cleaned_data['occurrence'] == 'weekly': start_date = tutor_session_form.cleaned_data['date'] while start_date < date(2020, 8, 1): MyModel.objects.create(form.cleaned_data['name'], date=start_date,) start_date += timedelta(days=7) else: form.save() So this works for what I want it to do, but I wouldn't want to manually have to change the year in the date every year, I'd prefer it to automatically use something that says "next time it is August 1st". I could use "current year + 1" but if this is used in February 2020 then it would make the condition August 1st 2021, when I would still want it to be 2020. Any help with this would be greatly appreciated! -
How to test answers to Django questions at stackoverflow
To all Djangonauts at stackoverflow: Due to the way django works a minimal working sample is usually big (view, model, url, ...). Therefore almost no question does provide such. This results in answers that cannot be good tested because some part of the code is missing. In my case it leads to answering almost only python questions because they're often testable. What is the best way to test django answers? Do you only use your experience or is there a trick for quick testing pieces of code (eg. a single view without knowing the model and urls? -
Django+MongoDB: Variable number of fields with django Model
I'm currently working with a django+python application using a mongoDB database. The objects in the collections in that database can have a variable number of attributes. What I'm wondering is if I would have to create a model field for every attribute and just deal with the fact that a large number of attributes are blank or if there is a method by which you can have a variable number of fields in a django Model or have the fields in an object dynamically generated instead of specified in the model (or if there is a package that allows that). This question was already answered for a SQL database being used with django here, but that didn't really tell me if the same was impossible for a django application with a mongodb database. Here is an example of some of the objects with variable fields that would be included in one collection. { 'id': 1, 'name': 'time', 'hat': 'top hat', 'shirt': 'dress shirt', 'vest': 'tweed', 'pants': 'black trousers', 'stopwatch': 'yes' }, { 'id': 2, 'name': 'James' }, { 'id': 3, 'pet': 'dragon' 'name': 'Ganilon' } What I'm hoping to find is something that dynamically generates the fields (or even just … -
Django Rest Framework Post nested models
I have three related models and I need to save all instances in a single transaction. A simplified version of my models are: class Recibosventas(models.Model): idreciboventa = models.AutoField(primary_key=True) idemplea = models.ForeignKey(Empleados, models.DO_NOTHING, db_column='idemplea', blank=True, null=True) idempres = models.SmallIntegerField() categocompro = models.CharField(max_length=2) tipocompro = models.CharField(max_length=1) puntoventa = models.SmallIntegerField() numero = models.IntegerField(blank=True, null=True) class Meta: managed = True db_table = 'recibosventas' unique_together = (('idempres', 'categocompro', 'tipocompro', 'puntoventa', 'numero'),) class Fondos(models.Model): idfondo = models.AutoField(primary_key=True) idemplea = models.ForeignKey(Empleados, models.DO_NOTHING, db_column='idemplea', blank=True, null=True) idtipofondo = models.ForeignKey('Tiposfondo', models.DO_NOTHING, db_column='idtipofondo') idconcepfondo = models.ForeignKey(Conceptosfondos, models.DO_NOTHING, db_column='idconcepfondo') idreciboventa = models.ForeignKey('Recibosventas', models.DO_NOTHING, db_column='idreciboventa', related_name='fondoreciboventa', blank=True, null=True) class Meta: managed = True db_table = 'fondos' class Movimientosfondos(models.Model): idmovimifondo = models.AutoField(primary_key=True) idfondo = models.ForeignKey(Fondos, models.DO_NOTHING, db_column='idfondo', related_name='movimientosfondos', blank=True, null=True) iddispon = models.ForeignKey(Disponibilidades, models.DO_NOTHING, db_column='iddispon') class Meta: managed = True db_table = 'movimientosfondos' serializers.py: class MovimientosfondosSerializer(serializers.ModelSerializer): class Meta: model = Movimientosfondos fields='__all__' class FondosSerializer(serializers.ModelSerializer): movimientosfondos = MovimientosfondosSerializer(many=True) class Meta: model = Fondos fields='__all__' def create(self, validated_data): with transaction.atomic(): # Crear la instancia de pedidos de venta movimientosfondos_data = validated_data.pop('movimientosfondos') fondos = Fondos.objects.create(**validated_data) # crear cada instancia de movimientosfondos for movimientosfondos_data in movimientosfondos_data: movimientosfondos_data['idfondo'] = fondos Movimientosfondos.objects.create(**movimientosfondos_data) return fondos def update(self, instance, validated_data): with transaction.atomic(): # Crear la instancia de pedidos de venta movimientosfondos_data … -
How to use list of values in get method?
I have a template filter in Django that looks ugly and not very pythonic. Is there a way to combine all the get requests into a list? @register.filter(name='is_supervisor') def is_in_group(user): group = Group.objects.get(name="security supervisor") group1 = Group.objects.get(name="cage supervisor") group2 = Group.objects.get(name="casino supervisor") group3 = Group.objects.get(name="food bev supervisor") return True if group or group1 or group2 or group3 in user.groups.all() else False I tried using a Q filter for chaining them together but that did not work. -
Django: dynamically/programatically setting model fields
I am attempting to create tables with fields based on metadata declared on other classes. My current approach is a bit like this: metadata = { ... } class CustomModel(MyBaseModel): ... for key, info in metadata.items(): setattr(CustomModel, key, fieldFrom(info)) What currently happens is that the table is created and the fields declared in class included. BUT the fields included through setattr are not getting included in the migration, even tough they correctly appear in the class when inspecting with de debugger. Is there any magic that only work for fields declared “in-place”? (Ps: written on a small phone, Ill improve the question when possible) -
How to apply annotations for Sum() on multiple django models?
I have three django models: ProjectName,ProjectBudget and ProjectActualCost. ProjectName stores the project name (ie Project X). ProjectBudget stores the project_name(as a foreign key(FK)),budget_name and the total_budget and date for each budget. ie (Project X, Hotel,600),(Project X, Rental,500). '600' refers to $600. ProjectActualCost stores each cost as it is incurred(itemized costs) (ie Hotel: 100, Rental: 50, Food:100) and its date. So it stores the 'project_name'(as FK),'budget_name'(as FK),actual_used and date. ie (Project X,Hotel,100,10/03/2019),(Project X,Hotel,100,10/06/2019), (Project X,Rental,50,04/10/2019) I'm trying to render the 'Project Name', 'Budget Name','Total Budget', 'Total Used'and 'Difference' in an html table. Project Name', 'Budget Name','Total Budget', 'Total Used' are rendering correctly,but 'Difference' displays inflated amounts as shown below. Models: class ProjectName(models.Model): project_name = models.CharField('Name',max_length = 15,blank = False) def __str__(self): return self.project_name class ProjectBudget(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) budget_name = models.CharField('Budget Name'max_length = 50 total_budget = models.DecimalField('Total Budget',max_digits = 9,decimal_places=2) def __str__(self): return self.budget_name class ProjectActualCost(models.Model): project_name = models.ForeignKey(ProjectName,on_delete = models.CASCADE, null = True) cost_description = models.ForeignKey(ProjectBudget,on_delete = models.CASCADE,null=True) actual_used = models.DecimalField('Actual Used',max_digits = 15,decimal_places = 2) Views: def budgetview(request,project_id): budget_items = ProjectBudget.objects.filter(project_name_id=project_id).annotate( actual_cost=Sum('projectactualcost__actual_used'), difference=Sum('total_budget')-Sum('projectactualcost__actual_used')) budget_template = "budget_view.html" context = {"budget_items":budget_items} return render(request,budget_template,context) budget_view.html: <table> <thead> <tr> <th>Project Name</th> <th>Budget Name</th> <th>Total Budget</th> <th>Total Used</th> <th>Difference</th> … -
How to build a ModelForm edit form with a multiple select field populated with data from a different models in Django?
I have a Django application with a dabatase backend. I need to render an HTML multiple select field with a ModelForm form (select field which allow to select multiple items). Data used to populate this multiple select field is gathered from a different tables/models than the one referenced in the Meta class of my ModelForm. I don't know what would be the best strategy in that case to implement this 'edit' form. Values to populate most of my form are stored in model 'Items' Values to populate the multiple select field are stored models 'Item_Usage' and 'Usage' This form is aimed at editing existing data of those 3 Models/database tables Items can have multiple usages, for instance 'Wood' can have 'Stove combustor' and 'Boat construction' usage. How should I build my multiple select field so that user could retrive current 'usage' for an item and add or remove usage within this form so that 'item_usage' model is updated accordingly? Database tables 'items' table +----+-------------------------+-------------+ | id | name | quantity | +----+-------------------------+-------------+ | 1 | Wood | 20 | | 2 | Steel | 5 | | 3 | Asphalt concrete | 80 | 'item_usage' table +----+---------+---------------+ | id | … -
How to reference a slug from a different model in get_success_url?
Setup I have two models in my app. One is for a Journal and the other one is for entries to that journal. I wrote a CreateView class that will allow user to create a Journal entry for any Journal id currently located in. Ideally I want the class to "refresh" with the updated entry or in other words the get_success_url should lead the page we are currently located at. views.py class ToJournalEntriesList(LoginRequiredMixin, CreateView): model = to_journal_entry template_name = 'to_journals/to_journal_entries_list.html' fields = ('body',) def get_success_url(self): return reverse('to-journals', kwargs={'slug':self.object.slug}) def form_valid(self, form): current_journal = to_journal.objects.get(journal_user=self.request.user, slug=self.kwargs['slug']) form.instance.journal_user = self.request.user form.instance.journal_name = current_journal return super(ToJournalEntriesList, self).form_valid(form) def get_context_data(self, **kwargs): context = super(ToJournalEntriesList, self).get_context_data(**kwargs) context['to_journal_entries'] = to_journal_entry.objects.all() return context models.py class to_journal(models.Model): journal_name = models.CharField(max_length = 40) slug = AutoSlugField(populate_from='journal_name') date_created = models.DateTimeField(auto_now_add=True) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_user) + " " + self.journal_name def get_absolute_url(self): return reverse('to-journals') class to_journal_entry(models.Model): body = models.TextField() entry_date = models.DateTimeField(auto_now_add=True) journal_name = models.ForeignKey(to_journal, on_delete=models.CASCADE,) journal_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE,) def __str__(self): return str(self.journal_name) + " " + str(self.entry_date) def get_absolute_url(self): return reverse('to-journal-entries', args=(self.slug)) urls.py urlpatterns = [ path('', CreateToJournal.as_view(), name='to-journals'), path('<slug:slug>', ToJournalEntriesList.as_view(), name='to-journal-entries'), ] Error With the current setup that I have I get: Which makes … -
Django - Custom Login Page on index
I'm using Django and I'm creating an backend web application. I would like to ask fellow Django users if it is possible to create the urls and functions for the login page but on index. Without using default Django auth framework for authentication/login. I'm just about to write the function for this, but I have got no idea if it will work. I have also looked at other tutorials but I do tend to find these are out of date. Any information would be much appreciated. ''' path('', views.index.login_user, name='index'), ''' -
Django - How to update check-out time based on another field?
I have an app that sort of works in a check-in/check-out manner. People just enter their ID, area, and click check in and it sends the timestamp to the db with their info. There is also a "check-out" button that currently does nothing. It's supposed to work so that, once the person fills the form and submits, it'll will either do one of these things: Find the previous check in entry based on the ID and Area entered and update the check out from NULL to timestamp. If the person forgot to previously check in, then it will create a new record with just the check out timestamp and the ID/Area. I thought that trying to find the user by matching both ID AND Area would be better since the same person can check in/out of different areas several times a day so matching only by ID could generate the problem of the program updating the wrong field at one point. models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model): employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, … -
Using the command " django-admin startproject ", doesn't create anything
I am new to Django, command line and Stackoverflow. I installed python and django. On running the following commands, nothing happens. As per some tutorials, I should get a folder made inside the Django_Practice folder. When I re-run the same command, it says, the folder already exists. I am on Windows 10, version 1903. C:\Users\Arjit Raj>python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ^Z C:\Users\Arjit Raj>python -m django --version 2.2.6 C:\Users\Arjit Raj>cd desktop C:\Users\Arjit Raj\Desktop>cd Django_Practice C:\Users\Arjit Raj\Desktop\Django_Practice>django-admin startproject djangotrial C:\Users\Arjit Raj\Desktop\Django_Practice>dir Volume in drive C is Windows Volume Serial Number is E21B-45DC Directory of C:\Users\Arjit Raj\Desktop\Django_Practice 18-Oct-19 07:06 PM <DIR> . 18-Oct-19 07:06 PM <DIR> .. 0 File(s) 0 bytes 2 Dir(s) 32,418,140,160 bytes free C:\Users\Arjit Raj\Desktop\Django_Practice>django-admin startproject djangotrial CommandError: 'C:\Users\Arjit Raj\Desktop\Django_Practice\djangotrial' already exists C:\Users\Arjit Raj\Desktop\Django_Practice> -
d3.js pan zoom issue
I am working on a django project in which I use intensively d3.js. I have a javascript function that works well: function three_lines_pan_zoom_chart(id, data, options) { var plotChart = d3.select(id).classed('chart', true).append('svg') .attr('width', options.w + options.margin.left + options.margin.right) .attr('height', options.h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var plotArea = plotChart.append('g') .attr('clip-path', 'url(#plot_Area_Clip)'); plotArea.append('clipPath') .attr('id', 'plot_Area_Clip') .append('rect') .attr({ width: options.w, height: options.h }); var navChart = d3.select(id).classed('complex_chart', true).append('svg') .classed('navigator', true) .attr('width', options.nav_w + options.margin.left + options.margin.right) .attr('height', options.nav_h + options.margin.top + options.margin.bottom) .append('g') .attr('transform', 'translate(' + options.margin.left + ',' + options.margin.top + ')'); var minN = d3.min(data, function (d) { return d.date; }).getTime(), maxN = d3.max(data, function (d) { return d.date; }).getTime(); var minDate = new Date(minN - 8.64e7), maxDate = new Date(maxN + 8.64e7); var yMin = d3.min(data, function (d) { return Math.min(d.value, d.valueBchk, d.valueIdx); }), yMax = d3.max(data, function (d) { return Math.max(d.value, d.valueBchk, d.valueIdx); }); var xScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.w]), yScale = d3.scale.linear() .domain([yMin, yMax]).nice() .range([options.h, 0]); var navXScale = d3.time.scale() .domain([minDate, maxDate]) .range([0, options.nav_w]), navYScale = d3.scale.linear() .domain([yMin, yMax]) .range([options.nav_h, 0]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom") .ticks(5); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); plotChart.append('g') .attr('class', … -
How to get the IP address of a client using aiohttp
I am currently working on a django project where I use aiohttp to communicate between the backend and frontend. I wanted to get the IP address of a client when a request is made from the frontend. Looked in different docs but none seems to point to exactly how to get the IP address using aiohttp. Someone Help! from aiohttp import web async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) try: async for msg in ws: # handle incoming messages # use ws.send_str() to send data back ... finally: task.cancel() -
Display previously uploaded files or images
I have two data tables and am using Django at the back end and Vuejs at the front end. (1) Products, stores the product details and a single image. (2) Products_Images, stores the multiple images with relation to the product. The below code is called from < Product List > when Editing the product details including adding images or removing images. My problem is that in Edit mode I need the previously selected displayed instead of ( No Files Chosen ) <!-- Edit a Product (Start) --> <template id="product-edit"> <div> <h2>Product (Edit)</h2> <form method="post" enctype="multipart/form-data" ref="itemMaster"> <!-- Display Product Name --> <div class="form-group"> <input class="form-control" id="edit-name" v-model="product.itemfullhd" required/> </div> <!-- Upload Single Image --> <div class="form-group"> <!-- ### MY PROBLEM HERE ### --> <label for="edit-imagemain">Main Image </label> <input type="file" id="edit-imagemain" v-model="product.Image_file" @change="onFileChanged" required/> <img class="cart-thumbnail" v-bind:src="'/media/' + product.image_file" alt="image"/> </div> <!-- Upload Multiple Images --> <div class="form-group"> <!-- ### MY PROBLEM ALSO HERE ### --> <label for="files">Xtra Images</label> <input type="file" id="files" ref="files" multiple v-on:change="handleFilesUpload()"/> <div> <!-- Display the Multiple Images --> <table class="table table-striped "> <thead> <tr> <th>Xtra Image File/s</th> <th>Image</th> <th>Delete</th> </tr> </thead> <tbody> <tr v-for="imagerec in products_images" and v-if="( imagerec.itemfullhd == product.itemfullhd )" style="clear: both;"> <td>/media/{{imagerec.images_multiple}}</td> <td> <img … -
django heroku in deploy debug mode
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticproject') ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') server 500 Error when i add to setting.py django_heroku.settings(locals()) urlr.py urlpatterns = [ url(r'^media/(?P.)$', serve,{'document_root': settings.MEDIA_ROOT}), url(r'^static/(?P.)$', serve,{'document_root': settings.STATIC_ROOT}), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
changing javascript function name or ID of element in HTML template makes it stop working
I am developing an app in Django. I have this weird issue. on my template I have: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_toda" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_toda) </script> on the js file get_today_date.js stored at static > js > get_today_date.js I have function get_today_date(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } when I load the template, in the input slot, today's date appears. I am glad of that. But if I change the id , like this: <div class="form-group"> <input name="Data_inserimento_entry" type="date" class="form-control" id="date_to_turn_into_today" > </div> <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date(date_to_turn_into_today) </script> It does not work anymore. Why? And even if I change the function name in both scripts, like: <script type="text/javascript" src={% static "js/get_today_date.js" %}></script> <script> get_today_date_ID(date_to_turn_into_today) </script> and function get_today_date_ID(id_data) { var now = new Date(); var day = ("0" + now.getDate()).slice(-2); var month = ("0" + (now.getMonth() + 1)).slice(-2); var today = now.getFullYear()+"-"+(month)+"-"+(day); document.getElementById(id_data).value = today; } It does not work anymore. Why? Is the syntax to call javascript correct? Am I forgetting to change the … -
Convert Raw SQL to Django ORM code , possibility
Is it possible to perform something like this with only Django ORM? with connection.cursor() as cursor: cursor.execute( """SELECT word FROM ts_stat( 'SELECT to_tsvector(''simple'', description) FROM api_product');""", #[source, ] ) words_in_product_model = frozenset( more_itertools.one(word) for word in cursor.fetchall() db-Postgres 11 Thanks -
How to retrieve metrics such as CPU loading, database connections, memory with django-prometheus
Is it possible to retrieve CPU info, total database connections and memory info with django-prometheus? After installing django-prometheus to my Django project prometheus/metrics I cannot understand is there any metrics to achieve my goals. Or it there another ways to do it? -
How to integrate mockaroo with django
I would like to integrate django with mockaroo since mockaroo provides rest api to download data ,I would like to use it with django project. Any help would be appreciated