Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Template Not Formatting <pre> Tag Correctly
I am trying to display raw json data in a Django template with the <pre> tag. I have this working in several places but for some reason one of my json samples is not working correctly. To get the json I take a python dictionary with nested lists and dictionaries. I then run that through json.dumps() to get my json. It looks like this: data = {'parent_key': {'key1': 'value1', 'key2': 'value2', 'key3': ['obj1', 'obj2', 'obj3'], 'problem_key': ['problem_data1', 'problem_data2', 'problem_data3']} json_data = json.dumps(data, indent=4) With my other dictionaries this works well - The expected output is 'pretty' formatted json - ie: parent_key { "key1": "value1", "key2": "value2", "key3": [ "obj1", "obj2", "obj3", ], "problem_key": "[\n \"problem_data1\",\n \"problem_data2\",\n \"problem_data3\"\n ] In the Django template my code looks like so: {% for k, v in json_data.items %} <pre>{{ k }} {{ v }}</pre> {% endfor %} As you can see most of the data formats correctly but that last section actually prints the newline characters instead of formatting them. Any thoughts? -
Uploaded form file gets deleted after HttpResponse is returned
I am saving the CSV file to text file using the handle_uploaded_file asynchronously using multithreading but the file argument passed to the function gets closed once the home function returns an HTTP response. I don't want to save the file and use it from that location but want to use it while it is available in memory. ValueError: Seeking closed file def handle_uploaded_file(f): destination = open('name.txt', 'ab+') for chunk in f.chunks(): destination.write(chunk) destination.close() def home(request): if request.method=="POST": file = UploadForm(request.POST, request.FILES) if file.is_valid(): g = request.FILES.dict() File = g['file'] print(File) uploader_thread = Thread(target=handle_uploaded_file, args=[File]) uploader_thread.start() file.save() return HttpResponseRedirect(reverse('imageupload')) else: file=UploadForm() files=Upload.objects.all().order_by('-upload_date') return render(request,'home.html',{'form':file}) #,'files':files}) -
After restarting httpd, app is not able to establish connection with aws RDs postgress server
I have deployed a Django app in AWS elastic beanstalk. The app is running perfectly. Only I am getting error Is the server running on host “localhost” (::1) and accepting TCP/IP connections on port 5432? after stopping and restarting the apache server by the following the command service httpd stop service httpd start Django app is not able to establish a connection with AWS RDS Postgres database server. -
Validating (Django Rest Framework) Serializer Fields based on Request
I'm trying to validate a DRF serializer CharField based on the Request object. The value supplied must be checked for uniqueness against other database values, that are filtered based on the Request. I've tried setting a to_representation method, but that also runs when retrieving data. -
Maintaining multiple instance of the same object in Django models
I am creating a small app in Django where I need to maintain details of training batches of different courses. Each of these batches will have a list of topics to be covered. For e.g, A python course could be conducted by different trainers in different colleges at the same time and so they both will have their own list of topics. Following is what I have come up with but think I am wrong. I am confused about how to go about it. Kindly suggest the right approaches. My Models so far, class Course(models.Model): name = models.CharField(max_length=50, default="Enter Course Name") class Trainer(models.Model): name = models.CharField(max_length=50, default="Enter Trainer Name") class College(models.Model): name = models.CharField(max_length=50, default="Enter College Name") class CourseBatch(models.Model): startDate = models.DateField(null = True, blank = True) endDate = models.DateField(null = True, blank = True) batchName = models.CharField(max_length=50, default="Enter Batch Name") course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course") trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE, related_name="trainer") college = models.ForeignKey(College, on_delete=models.CASCADE, related_name="college") class CheckPoints(models.Model): description = models.CharField(max_length=50, default="Enter Description") chkPoint = models.BooleanField(default=False) course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course") class ChkListForBatch(models.Model): batch = models.ForeignKey(CourseBatch, on_delete=models.CASCADE, related_name="coursebatch") chkpoint = models.ForeignKey(CheckPoints, on_delete=models.CASCADE, related_name="chkpoint") Here every CourseBatch needs to have its own set of CheckPoints (topics) to be covered. How can … -
How to check validation of a formset before submitting?
I'm wondering how can I check the validation of a formset. Let me explain my case. I have a five forms which are contained in a formset. Each form represent a set of a Volleyball match (a Volleyball match is played in 5 sets). I want to be able to submit my formset if there are already three forms that represent a win, because if I have for example the first three sets won by the team one, the fourth and fifth sets are useless, the match is over when there are three winning sets. I don't know if I was very clear... You'll find my forms.py down bellow : forms.py class SetUpdateForm(forms.ModelForm): class Meta: model = Set fields = [ 'scoreTeam1', 'scoreTeam2', 'match', ] def clean(self): cleaned_data = super().clean() scoreTeam1 = cleaned_data.get("scoreTeam1") scoreTeam2 = cleaned_data.get("scoreTeam2") if cleaned_data.get("match") is not None: sport = cleaned_data.get("match").phase.tournament.sport if scoreTeam1 and scoreTeam2: if scoreTeam1 == scoreTeam2: raise forms.ValidationError("Scores can't be equal") if scoreTeam1 > sport.nbPointPerSet or scoreTeam2 > sport.nbPointPerSet or (scoreTeam1 < sport.nbPointPerSet and scoreTeam2 < sport.nbPointPerSet): raise forms.ValidationError("A set is played in " + str(sport.nbPointPerSet) + "points.") return cleaned_data MatchSetFormset = forms.inlineformset_factory(Match, Set, form=SetUpdateForm, min_num=1, extra=0, can_delete=False) I'm using Django 2.2 and Python … -
I'm having trouble displaying output on my python code for network monitoring. Not displaying result but no error
I have a project that needs to monitor all the connected devices over the network. Data must be displayed in Django. I have this code no error but not displaying anything. I don't know if I have missed something. network_tag.py import sys import logging import netifaces as ni import nmap import threading import socket import subprocess from django import template from collections import namedtuple register = template.Library() deviceTuple = namedtuple('deviceTuple', 'ip, mac') class NetworkScanner(template.Node): """docstring for NetworkScanner.""" def get_interfaces(self): #log.info('Getting local interfaces...') interfaces = [] for interface in ni.interfaces(): if not interface.startswith(('lo', 'vir')): #log.info('Found local interface {}'.format(interface)) interfaces.append(interface) return interfaces def get_local_ip(self): interfaces = self.get_interfaces() #log.info('Getting local ip address...') for interface in interfaces: try: addr = ni.ifaddresses(interface)[2][0]['addr'] #log.info('Local ip address is {}'.format(addr)) return addr except KeyError: #log.debug('Error: No local ip addresses found.') return '' def get_subnet(self): ip = self.get_local_ip() subnet = '.'.join(ip.split('.')[:3]) + '.0/24' #log.info('Subnet is {}'.format(subnet)) return subnet def render(self, context): subnet = self.get_subnet() #log.info('Getting devices on subnet {}...'.format(subnet)) nmap_args = '-sP' scanner = nmap.PortScanner() scanner.scan(hosts=subnet, arguments=nmap_args) devices = list() for ip in scanner.all_hosts(): if 'mac' in scanner[ip]['addresses']: mac = scanner[ip]['addresses']['mac'].upper() #device = {'ip': ip, 'mac':mac} #log.info('Found device {}'.format(device)) devices.append(deviceTuple( ip=ip.ip, mac=ip.mac)) #log.info('Found {} devices'.format(len(devices))) #return devices all_stats = … -
Django Admin datetime in EST
In my application I need to show some datetimes in the admin section in EST timezone. I have the following configuration in settings.py: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False In the application users chose differente timezones and works fine for users, ie; Thursday, May 16, 2019 12:00 AM EDT But I want to show datetime in EST timezone in the admin section. Currently it will show all times in UTC as expected. I tried the following: from datetime import datetime from pytz import timezone from django.contrib import admin TZ = timezone('EST') @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): list_display = ('name', 'scheduled_date') fieldsets = ( (None, {'fields': ('name', 'scheduled_date')}), ) def scheduled_date(self, obj): date = datetime(obj.scheduled_date, tzinfo=TZ) return date However the admin section is still showing time in UTC for scheduled_date -
How to maintain session in Locust?
How to pass request object while posting any URL with view consuming request.user? locustfile.py def login(self): self.__class__.user = self.__class__.user + 1 data = self.get_user_data() csrf = self.get_csrf("/admin/login/") resp = self.client.post("/admin/login/", data, headers={"X-CSRFToken": csrf}) if resp.status_code == 200: self.login_success = True else: self.login_success = False views.py def start_exam(request): try: user = request.user -
How To Parse Scripts With Beautiful Soup?
I need to parse some data within the script tag. First challenge is that there are several script tags on the page with no ids or classes. The one I need looks like this: <script> window.runParams = { data: { "priceModule":{ "minActivityAmount":{ "currency":"USD", "formatedAmount":"US $6.83", "value":6.83 }, "minAmount":{ "currency":"USD", "formatedAmount":"US $12.42", "value":12.42 }, }, }, }; var GaData = { pageType: "product", productIds: "ru32955439786", totalValue: "US $6.83" }; var PAGE_TIMING = { pageType: 'gloDetail' }; </script> I need to parse [value] within the [data] -> [priceModule] -> [minActivityAmount] & [minAmount]. Can you please help me how to do that? -
How to start Full Stack Development in Python?
I'm Newbie to this Full-Stack Development. I've built a couple of Command Line Apps using Python. But, I want to take it to the next level. I'm pretty interested in FULL-STACK DEVELOPMENT and installed Django too. But, How do I even start? What is the roadmap? I'm pretty lost. I tried a couple of google searches. Including, videos and free materials. But, Got lost even more and Confused too. What else do I need to learn? What is the correct sequence? Any Help will be Appreciated...☺ -
I want to use the redis cache in Django, but I found that python 3.7 does not support django-redis. Is there an alternative?
I want to use the redis cache in django, but I found that python3.7 does not support django-redis. Is there an alternative? Thanks -
var_dump for variable in django templates
How can I see what data and fields the variable contains in the template? Suppose I have a list of courses and I do filtering by active. How can I see what fields the courses have (start date, name, slug, etc ...) I have the variable "events" but I don’t understand how to see fields of this variable and what they contain. events.name events.slug sry for my eng -
if statement fails to evaluate to true even though condition is met in django template
I am trying to check if a dictionary key list contains an element in django template. I can see the element in the list but the if statement returns false {% if item in incart %} 1 {% else %} 0 {% endif %} when I do {{incart}} it produces dict_keys(['1', '2']) and {{item}} shows 2 However when I run the statement above {% if item in incart %} 1 {% else %} 0 {% endif %} it returns 0 instead of 1. What are my doing wrong? -
Django use model manager method after filter()
I'm using Django 2.2 I have a Video model with custom methods defined in the model manager class VideoManager(models.Manager): def completed(self): return self.get_queryset().filter(status=self.model.STATUS_POST_COMPLETE) class Video(models.Model): STATUS_UPLOADED = 'uploaded' STATUS_POST_COMPLETE = 'post_complete' STATUSES = ( (STATUS_UPLOADED, 'Uploaded'), (STATUS_POST_COMPLETE, 'Post Complete'), ) campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) title = models.CharField(max_length=250) video = models.FileField(upload_to=user_upload_directory_path) status = models.CharField(choices=STATUSES, default=STATUS_UPLOADED, blank=True, max_length=50) objects = VideoManager() In the view file, I want to get count of completed video class VideoListView(generic.ListView): template_name = 'videos/list.html' model = Video def get_queryset(self): return self.model.objects.filter(campaign__user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) stats = { 'total': self.get_queryset().count(), 'completed': self.get_queryset().completed().count() } context['stats'] = stats return context I'm using self.get_queryset() to get already filtered for user and then get all completed videos using model manager method. I followed this approach to reduce repeated variables. But this gives error AttributeError: 'QuerySet' object has no attribute 'completed' -
How can i forward declare a class argument in python?
When declaring Django models, this problem came across: class Foo(Bar): pass class Bar(): pass NameError: name 'Bar' is not defined How can i forward declare a class argument in python 3.6.7? -
How to pass value from forloop to url on modal with Django?
I have a forloop with buttons and their respective pk values. {% for obj in all_objects %} <button data-toggle="modal" data-id="{{ obj.pk }}" data-target="#myModal" class="open-my-modal"> {{ obj }} </button> {% endfor %} In myModal I have an url with pk=0 to be dynamically changed when an object is selected. <a id="doSomething" href="{% url 'myapp:do_something' pk=0 %}">Do something</a> I tried the following but I am getting the error Reverse for 'do_something' with keyword arguments '{'pk': ''}' not found. {% block jquery %} <script> $(document).on("click", ".open-my-modal", function () { // get the obj pk var objPk = $(this).data('id'); // this properly returns the pk value // pass obj pk to url document.getElementById("doSomething").setAttribute("href", "{% url 'myapp:do_something' pk=objPk %}"); </script> {% endblock jquery %} How do I dynamically set the pk inside the href to the selected obj.pk value? -
Markdown Template does not render HTML Correctly
I have created a Markdown Filter in my Django Website. I have used the library markdown2. Though the HTML does render, it does not render it entirely. The Code and Syntax Highlights, URLs and Lists do not render properly. templatetags folder filename: ttags.py from django.template import Library import markdown2 register = Library() @register.filter('markdown_to_html') def markdown_to_html(markdown_text): htmlversion=markdown2.markdown(markdown_text) return htmlversion templatefile {% extends "layout.html" %} {% load ttags %} {% load static from staticfiles %} {% block content %} <div class="content"> {{ step.description | markdown_to_html | safe }} </div> {% endblock %} The Text that was provided to be rendered was as below Usage of Variables name = "David" age = 10 In the above example name and age are variables that store Text and Numbers respectively. Always remember to use Variables in your programs to store information. The Output was as below The Code did not display in two lines and the BlockQuote also did not work -
Can localtunnel services like ngrok see your source code?
I'm using a local server for django dev and ngrok tunnel for webhooks. I've seen other localtunnel services like serveo. Can these services see your source code? Are they forwarding your local files to the ngrok server or just handling requests on a public domain and then securely fetching from your local server? I've read about how ngrok creates a proxy and handles requests, but I still don't understand what exactly tunneling involves -
Unable to run a manage.py command from app/views.py via subprocess
Python/Django newbie here! In my new project, I am able to load the django template pages and the admin section, as well as update and delete things from the admin... I've been able to collectstatic without a problem and I can also run all commands with manage.py from bash, all from inside virtualenv. Where I am stuck is trying to run a "python manage.py check" from the app's views.py via subprocess, for example: some_app/views.py from django.shortcuts import render from django.http import HttpResponse import subprocess import shlex def home(request): cmd = 'python manage.py check' subprocess.Popen(shlex.split(cmd)) return HttpResponse("<html><body>Hello World</body></html>") The HTML "Hello World" loads fine, the subprocess command results in Apache error: "python: can't open file 'manage.py': [Errno 2] No such file or directory". I am not sure I know why this is, here's the file structure I have: /var/www project (venv) bin/ include/ lib/ share/ myweb/ db.sqlite3 manage.py myweb/ static/ templates/ If enyone has any tips I would appreciate it! setup info: Ubuntu server 18.04, Apache 2.4.29, virtualenv w/python 3.6.7, Django2.2.1 -
Auto download not working for Django FileResponse
I need to let the Django auto download the generated file. Tried all different solutions online, none of them works. Views.py def validate(request): if request.method == 'POST': filename = request.POST.get('source_file') file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename) region = request.POST.get('region') product_type = request.POST.get('product_type') result = validateSource.delay(file_path, region, product_type) output_filepath, log_filepath = result.get() if os.path.exists(output_filepath) and os.path.exists(log_filepath): zip_filename = zipFiles([output_filepath, log_filepath], filename) zip_filepath = os.path.join(settings.MEDIA_ROOT, zip_filename) response = FileResponse(open(zip_filepath, 'rb'), as_attachment=True) return response raise Http404 -
Archiving, handeling related deltions
I am always stuck in the following type of situation: Say I have a model/database table Product. The product is produced in a ProductionLine. so the product has a Foreign key to the ProductionLine. The product has states such as "delivered", "produced", "recycled", "in_stock" e.t.c. And it has a date of the last change of state by which is also indexed. Assume now that I have millions of delivered products several thousand of the rest. Several months go buy and there is a need to delete a ProductionLine instance. (remember just an example) For these objects (Product) in this example, when a parent is Deleted, and the object is in a state which should not change, i.e. archived/delivered. Should I set the parent Foreign key field to null? not delete the parent and just give it a not_active state. should I have a clone of the model such as Product and ProductArchived which keeps all data (wasteful?)? What are the normal conventions today, I'm new to such as situation and couldn't find any answers. -
In Django, how can I prevent a "Save with update_fields did not affect any rows." error?
I'm using Django and Python 3.7. I have this code article = get_article(id) ... article.label = label article.save(update_fields=["label"]) Sometimes I get the following error on my "save" line ... raise DatabaseError("Save with update_fields did not affect any rows.") django.db.utils.DatabaseError: Save with update_fields did not affect any rows. Evidently, in the "..." another thread may be deleting my article. Is there another way to rewrite my "article.save(...)" statement such that if the object no longer exists I can ignore any error being thrown? -
How do I create a decorator that adds a logged in user to the function?
I am writing tests for views that require the user to be logged. I want to write a decorator to add a logged in user to each test. For example, rather than writing: def test_view_url(cls): get_user_model().objects.create_user(username='Paulian', password='yGy2pl12') cls.client.login(username='Paulian', password='yGy2pl12') response = cls.client.get(cls.home_view_url) cls.assertEqual(200, response.status_code) I want to write: @user_is_logged_in def test_view_url(cls): response = cls.client.get(cls.home_view_url) cls.assertEqual(200, response.status_code) Here is my current and faulty decorator: def user_is_logged_in(func) -> object: def wrapper(func): c = Client() if c.login(username='Paulian', password='yGy2pl12'): pass else: get_user_model().objects.create_user(username='Paulian', password='yGy2pl12') c.login(username='Paulian', password='yGy2pl12') return wrapper return wrapper -
How to pass javascript integer variable as primary key into django url with modalForm package
I am using DataTables (https://datatables.net/) and I have a button in my table. When that button is clicked I would like to check in which table row that button is, then check the column 'ID' in that column, get that value. Then I would like to pass that value into a url as a primary key to open an updateform. Everything works fine except for passing the javascript variable into the django URL. var adresid = 0 $('.dt-edit').each(function () { $(this).on('click', function(evt){ $this = $(this); adresid = parseInt($this.parents('tr')[0].cells[13].innerHTML) }) .modalForm({ formURL: "{% url 'adres-update-modal' adresid %}" }); }); I tried to use the .replace() method as formURL: "{% url 'adres-update-modal' pk %}".replace('pk', adresid), but that did not work. The error I keep getting is Reverse for 'adres-update-modal' with arguments '('',)' not found. 1 pattern(s) tried: ['adres/(?P<pk>[0-9]+)/updatemodal/$'] When I replace adresid in the url with an integer (e.g. 16) everything works perfectly fine. If someone could please help me out here it would be very much appreciated! :)