Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Datatables taking too long to load
I am trying to load 25600 rows into datatables but it's taking around 10 seconds. The request is via an ajax API call. views.py @api_view() def get_all_data(request): get_all_data_ = Data.objects.values("name","contact_number","email_address","address","age", "location_type","sector","phase","total_data","total_usage","city","district") return JsonResponse(list(get_all_data_), safe=False) template.html var table = $('#data-table').DataTable({ serverSide: true, "ajax": { "url": "/alldata/", "dataSrc": "" }, "columns": [ {"data": "name"}, {"data": "contact_number"}, {"data": "email_address"}, {"data": "address"}, {"data": "age"}, {"data": "location_type"}, {"data": "sector"}, {"data": "phase"}, {"data": "total_data"}, {"data": "total_usage"}, {"data": "city"}, {"data": "district"} ], }); How can i make it instantaneous? -
Django Template Display Context in Modal On Click
I may be completely going about this wrong, but fairly new to Django Templates and appreciate any help. I have a template that dynamically creates a table of rows of data based on context passed to the template from the view. html table rows being generated by loop <tbody> <!--Table Rows--> {% for ruleset in rulesets %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><a href="{% url 'ruleset_detail' ruleset.id %}">{{ ruleset.ruleset_name }}</a></td> <td>{{ ruleset.ruleset_description }}</td> <td>{{ ruleset.ruleset_create_date|date:'m-d-Y' }}</td> <td style="text-align:center;">10</td> <td style="text-align:center;"> <div> <!-- EDIT modal button--> <button type="button" id="editRuleset" name="{{ ruleset.id }}" value="{{ ruleset.ruleset_name }}" class="btn btn-link align-middle" data-toggle="modal" data-target="#editRuleset"> <i class="fas fa-edit fa-sm"></i> <span style="font-size:small">EDIT</span> </button> </div> </td> </tr> {% endfor %} </tbody> the result is an EDIT button created for each row of data in the table with the rows ruleset id and name stored as the button name and value. When the user clicks on the EDIT button, a modal is displayed that should take the data from that row and assign it to the value of form inputs. modal form <form action="" method="PUT"> {% csrf_token %} <div class="modal-body"> <div class="form-group"> <div class="pt-2"> <label for="edit_ruleset_name">Ruleset Name</label> <input id="edit_ruleset_name" name="edit_ruleset_name" class="form-control" type="text" value="" required> </div> <div class="pt-4"> <label for="edit_ruleset_description">Ruleset … -
Value won't get updated in Calendar form using sessionStorage
I am importing a calendar widget using django. Previously it was working fine if I changed the date and refreshed the page the date automatically save the entered date value. However, when I added a maxdate to the widget on page reload it will only refresh to the maxdate value (today's date) and never get updated. options={ "format": "YYYY-MM-DD", # moment date-time format "calendarWeeks": True, "locale": "en-gb", "maxDate": datetime.datetime.today().strftime('%Y-%m-%d') })) My Solution: I figured I can solve this problem saving the value through sessionStorage and updating the value. My code works as intended but for some reason will not update my widget. My thought is the calendar widget maxdate is overriding my entered date. You can see below my value I inputted and the max date towards the end of the code line. Has anyone encountered this problem? Seems like my max date (today) will override my inputted 2020-09-07 value on page reload. <input type="text" name="Calendar" value="2020-09-07" class="form-control" id="id_Calendar" dp_config="{"id": "dp_65", "picker_type": "DATE", "linked_to": null, "options": {"showClose": true, "showClear": true, "showTodayButton": true, "format": "YYYY-MM-DD", "calendarWeeks": true, "locale": "en-gb", "maxDate": "2020-11-03"}}" My JS to handle sessionStorage $(document).ready(function() { let current_value = document.getElementById("id_Calendar").value; let new_value = sessionStorage.setItem("id_Calendar",current_value); var getItem = sessionStorage.getItem("id_Calendar"); if … -
django render_to_string not cares about python variables that's saved in database model
i have an text email template saved in database , and it is include some python variables , for example {{ company_name }} but when i use 'render_to_string' django function , it see the '{{ company_name }}' as a string not as a python variable , and here is my codes: 1- this the text which is saved in database : "" this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank "" 2- and this is my view codes: email_info_object = Email_Auto_Reply.objects.get(EAR_department=Site_departments.objects.get(DEB_name=department)) email_body = email_info_object.EAR_body company_name = 'company name example ' render_context = { 'email_body':email_body, 'company_name':company_name, } email_body = render_to_string("staff/email_rendering/auto_reply_new_request.html", render_context) print(email_body) 3- and this is my 'staff/email_rendering/auto_reply_new_request.html' file. {% autoescape off %} {{ email_body|safe}} {% endautoescape %} 4- and this is the output of print : 00 8848 [04/Nov/2020 01:17:03] "GET /admin/jsi18n/ HTTP/1.1" 200 3187 [04/Nov/2020 01:17:08] "GET /submit_ticket/ HTTP/1.1" 200 5244 this is an email auto reply test from {{ company_name }} sales department, we will contact you as soon as possible . thank [04/Nov/2020 01:17:13] "POST /submit_ticket/ HTTP/1.1" 302 0 -
VCF file write into amazon S3 bucket django
I need to write(save) a VCard .vcf file to my amazon s3 bucket, but there has been problems. I have managed to save vcf file locally and then duplicate to s3 bucket. How I can store direclty into s3 bucket, btw just started using aws, hope you can help! I get data from my customer model database and this is my django view import ... import boto3 customer = Customer.objects.get(identifier=identifier) data = {} data['n'] = customer.first_name + ' ' + customer.last_name data['fn'] = customer.first_name + ' ' + customer.last_name data['tel'] = customer.phone data['email'] = customer.email vcard = vobject.readOne('\n'.join([f'{k}:{v}' for k, v in data.items()])) vcard.name = 'VCARD' vcard.useBegin = True vcard.prettyPrint() ############# WORKS BUT SAVES LOCALLY ############### # path = (settings.MEDIA_ROOT + 'customer.vcf') # with open(path, 'w', newline='') as f: # myfile = File(f) # myfile.write(vcard.serialize()) ############# WORKS BUT SAVES LOCALLY ############### ############# dublicates to bucket ############### s3 = boto3.resource('s3') BUCKET = "bucket" s3.Bucket(BUCKET).upload_file(path, 'customer.vcf') -
Should I host my django webapp for free if it will be used by 1000+ people
I have made a Django web app where students from my resident as a student will order food and other stuff since the shops are far from us, So probably the website will be used by 1000+ students, so it is possible for me to host it for free (Heroku etc.) or I will need a hosting plan from a company?, which company will you recommend? MY Website Screenshot -
Using Python Desktop app to use Django Authentication
I'm working on developing a Desktop App with Python 2.7, Postgres and trying to integrate Django. The app connects into a database to query data being added by an acquisiton gui.At some point i want to have a webpage also For the server side i choose Django since it have a pretty neat admin page and authentication system. I added my main django project settings on my gui project and have managed to authenticate my user, but i really want to my "client" log-in and for this I need a session. It have been hard working around this. I have tried several things Using the django log in method directly: This is a little bit hard since for doing i cant find a way to generate the request for it. I can get the user from the authentication but not the request. Using request : I created a view and url specific for the client to make a request so' that it recieve the usernaame and password and ran the log-in at the server but i recieve an error. This is maybe because i dont have a session, and dind find nothing def do_login(self, event): # import django # from … -
Problems after run: heroku run python manage.py migrate
While I was deployed my django app in heroku, I run: heroku run python3 manage.py migrate and I get this messahe in my console: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax my manage.py file is actually: #!~/.virtualenvs/djangodev/bin/python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myApp3.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() When I run python => python3, the next message is displayed: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
how to resolve 'ValidationError' object has no attribute 'strip' issue?
I want to add or raise a validation registration form but I get this error: 'ValidationError' object has no attribute 'strip' how can I skip it? I'm suffering from these issues please if you could tell me the correct way to validate the registration form after you solve this problem I'll be appreciated. Thank you in advance class SignUp(UserCreationForm): def __init__(self, *args, **kwargs): super(SignUp, self).__init__(*args, **kwargs) self.error_messages = { 'username_match': 'username is already exist', 'email_match': 'Email is already exist', 'password_mismatch': 'these two password isn\'t match try again' } email = forms.EmailField(required=True) first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) # password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) # password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password1', 'password2', 'email'] def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): return forms.ValidationError( self.error_messages['email_match'], ) return email def clean_username(self): username = self.cleaned_data.get('username') if User.objects.filter(username=username).exists(): return forms.ValidationError( self.error_messages['username_match'], ) return username def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: return forms.ValidationError( self.error_messages['password_mismatch'], ) return password2 def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user views.py def register(request): form = SignUp(None) if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() return redirect('accounts:login') … -
How to render CharField (choices) in Django Admin limiting options from one base to another?
I have two fields in my database which are shown as lists in the DJANGO administration panel # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') coordenadasb = models.DecimalField(max_digits=5, decimal_places=2, default=0.0) longitud = models.DecimalField(max_digits=8, decimal_places=3, default=0.0) latitud = models.DecimalField(max_digits=8, decimal_places=3, default=0.0) AREA = [ ('FR', 'AREA 1'), ('SO', 'AREA 2'), ('JR', 'AREA 3'), ('SR', 'AREA 4'), ] area = models.CharField(max_length=50, choices=AREA, default='unknown') GRUPO = [ ('FR', 'group 11'), ('SO', 'group 12'), ('JR', 'group 21'), ('SR', 'group 22'), ('GR', 'group 31'), ('GR', 'group 32'), ] group = models.CharField(max_length=50, choices=GRUPO, default='unknown') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) I want to make that in the administration panel when choosing the item 'AREA 1' of the field "area" in the field "group" only the elements 'group 11' and 'group 12' are shown From what I guess I think that the procedure to achieve this would be modifying the administration template by adding a JS that modifies the values of the "group" field based on an event that listens for the changes of the "area" field. Would this be correct? Is there a way to perform the desired behavior without modifying the default Django … -
ModuleNotFoundError: No module named 'products'
I'm a newbie to Django. I'm following a tutorial where I should create a model class called products. This is what I've included in my models.py document inside my APP called Products: class Products (models.Model): title = models.TextField() description = models.TextField() price = models.TextField() Then I added the APP to INSTALLED APPS in my setting.py document: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party #own 'products', However, when I tried to run the following command on my terminal I get an error: (env) dcorreavi@dcorreavi src % python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/Users/dcorreavi/Dev/trydjano/python-virtual-environments/env/lib/python3.8/site- packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'products' -
How to pass url domain into Django View
In a class based django view, how can you extract the current domain for use in the view? For example. If I was at 'http://example.com/myview/', is there a way to get 'example' in the view? Similar to how you can get kwargs passed in the url (self.kwargs['someArgument']). I've tried: class MyView(LoginRequiredMixin, UpdateView): model = Maintenance form_class = Maintenance_Perform_Form template_name = 'maintenancePerform.html' def form_valid(self, form): asset = Assets.objects.get(id = self.kwargs['assetID']) form.instance.completedBy = (self.request.user.first_name)+ " "+(self.request.user.last_name) form.instance.recordedBy = (self.request.user.first_name)+ " "+(self.request.user.last_name) form.instance.complete = True redirect_url = self.request.domain + '/maintenanceList' return redirect(redirect_url) But self.request only returns the url that is appended to the domain. I was hoping for 'example.com' Some additional context, because there may be a much easier way of accomplishing what I am trying to do... I have a Django application running on an internal corporate network only, and in the early stages of development the address to access the application was just the IP of the server 'http://10.0.0.1/myapp'. Our IT manager recently changed some settings so that you can access the server by name instead of IP, so you can now also use http://server-name.int/myapp. I added both of these to my ALLOWED_HOSTS in settings, but for some reason Django's loginrequiredmixin … -
django : create a unique ID for each modelForm submission
I have a modelForm in a template and I need to automatically create a ID for each row of the modelForm. The ID should be the same at each row, but unique per modelForm submission. Being somewhat a beginner in django, I am confused on how to achieve this. I have tried doing that: class historical_recent_data(models.Model): Description = models.CharField(max_length=200, default= ' ') Date = models.DateField() Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) id = models.AutoField(primary_key=True, serialize=True) customer_name = models.ForeignKey('Customer_base', on_delete=models.CASCADE, default="Unknown") invoice_number = models.CharField(max_length= 500, default=create_invoice_number) def __str__(self): return self.reference with this function to generate a unique value: def create_invoice_number(): last_invoice = invoice.objects.all().order_by('id').last() if not last_invoice: return 'INV001' invoice_no = last_invoice.invoice_number invoice_int = int(invoice_no.split('INV')[-1]) new_invoice_int = invoice_int + 1 new_invoice_no = 'INV' + str(new_invoice_int) return new_invoice_no and my view looks like that: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Description','Date','Quantity', 'NetAmount', 'customer_name', 'invoice_number')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #invoice_hidden_form = CreateInvoiceForm(request.POST) #blank_form = formset.empty_form if formset.is_valid(): #request.session['sale'] = formset.cleaned_data for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') … -
Testing ImageField cropping for Django
This is my models.py: from PIL import Image from places.fields import PlacesField class ResourcePost(models.Model): dropoff_location = PlacesField(blank=True, null=True)= image = models.ImageField( default="donation-pics/default.jpg", upload_to="donation-pics", blank=True ) def save(self, *args, **kwargs): if not self.dropoff_location: self.dropoff_location = self.donor.donorprofile.dropoff_location super().save(*args, **kwargs) path = self.image.path img = Image.open(path) if img.height > 300 or img.width > 300: output_size = (300, 300) img = img.crop_to_aspect(300, 300) img.thumbnail(output_size) img.save(path) and this is my test.py @override_settings(MEDIA_ROOT=tempfile.gettempdir()) def test_image_crop(self): image = Image.new('RGB', (500, 500)) image_file = NamedTemporaryFile(suffix='.jpg') image.save(image_file) create_resource_post = ResourcePost( ... image = image_file, ... ) create_resource_post.save() height = create_resource_post.image.height width = create_resource_post.image.width self.assertEqual(height, 300) self.assertEqual(width, 300) I keep getting this error when I run the test: File "C:\Users\ccjgl\Desktop\SWEdjango\urban-thrifter\donation\tests.py", line 103 image = image_file, ^ SyntaxError: invalid syntax The editor shows me that image is a tuple and image_file is a string. I think that is the problem, but I don't know how to solve it. Question: How can I solve the syntaxError? Is it correct to use create_resource_post.image.height to access the image's size? -
AttributeError: '_io.BufferedReader' object has no attribute '_committed'
I am writing tests for my application. I have searched over the internet for the same error but I can't find anything. I had this error yesterday but then my deadline is very tight. Today I face the same error. It seems this error only occurs when I try to assign the user onetoone field twice to two different models. What's happening is that I am trying to create two different profiles. One profile is a seller profile and this other is a buyer profile. The code for the tests -> from django.test import TestCase, Client from django.urls import reverse from shop.models import Category, Product from users.models import Profile, User, SellerProfile class TestViews(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user( email='johndoe@gmail.com', password='secretpass203', username='johndoe', ) # Now log in the test client password = "secretpass203" self.is_authenticated = self.client.login( username=self.user.username, password=password) # Test if a user profile can be created successfully def test_user_profile_creation(self): url = reverse("users:create-profile") # Send a post request with open("test_data/profile.jpg", 'rb') as dp: response = self.client.post(url, { 'firstname': 'John', 'lastname': 'Doe', 'profile_picture': dp }) # assert the response returned if's it is a redirect self.assertEquals(response.status_code, 302) # Check if the profile was created self.assertEquals(Profile.objects.last().firstname, 'John') def test_user_is_logged_in(self): self.assertEquals(self.is_authenticated, … -
ImportError: numpy.core.multiarray failed to import keeps coming back
I searching informations for my thesis. My goal is to make a website where I can upload pictures and algorithms sort them seperately. Like face, car, etc. I haven't reached this part yet. My current problem is the following: I'm making a simple picture upload in django's admin site where my pictures will be edited by simple algorithms using opencv, like bgr2rgb, bgr2hsv. I used django, matplotlib, opencv-python, and pillow. I made a new environmental for it. I set it up everything and when i run the code python manage.py makemigrations everything worked fine. (I use git for terminal) After I did some coding, and saved it I did run again, but I got some errors: File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\numpy\__init__.py", line 305, in <module> _win_os_check() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\numpy\__init__.py", line 302, in _win_os_check raise RuntimeError(msg.format(__file__)) from None RuntimeError: The current Numpy installation ('C:\\Users\\Krist▒f\\Desktop\\Thesis\\mywork\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: (an url i had to delete) Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\Krist▒f\Desktop\Thesis\mywork\lib\site-packages\django\__init__.py", … -
How to avoid a NonType error in template when using ForeignKey in Model?
I want to access the region of the user in my template: {% if object.seller.profile.post_code %}{{ object.seller.profile.post_code }} {% endif %}{% if object.seller.profile.city%}{{ object.seller.profile.city }}<br/>{% endif %} {% if object.seller.profile.region.name %}{{ object.seller.profile.region.name }}, {% endif %}{% if object.seller.profile.region.country.name %}{{ object.seller.profile.region.country.name }}{% endif %} This is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics', verbose_name='Profilbild') post_code = models.CharField(max_length=5, blank=True, verbose_name='Postleitzahl') region = models.ForeignKey(Region, on_delete=models.CASCADE, null=True, blank=True, verbose_name='Region', help_text='Bundesland oder Kanton') city = models.CharField(max_length=50, blank=True, verbose_name='Stadt') street = models.CharField(max_length=50, blank=True, verbose_name='Straße') class Region(models.Model): name = models.CharField(max_length=30, verbose_name='Region', help_text='Bundesland oder Kanton', default='Berlin') symbol = models.CharField(max_length=30, verbose_name='Region-Kürzel', default='BER') country = models.ForeignKey('Country', on_delete=models.CASCADE, null=True, verbose_name='Land', default=0) class Country(models.Model): name = models.CharField(max_length=30, verbose_name='Land', default='Deutschland') symbol = models.CharField(max_length=4, verbose_name='Kürzel', default='DE') But I don't want to force the user to enter their adress data. But if the ForeignKey-Fields are not filled I get 'NoneType' object has no attribute 'country' Is there a more a elegant way than checking each field if it is filled in the views.py and adding it separately to the context? -
Why won't the server.log for my PythonAnywhere server refresh?
The server.log for my PythonAnywhere server is not refershing. The last entries are dated 3 days ago. I've tried refreshing the URL for the server log, looking in the var/log directory, tailing the file, restarting the server, and emptying my browser cache. Is there something else I can try? -
Which is better: fcm-django or django-push-notifications?
I'm developing a DRF API for an angular frontend and have to implement push notifications and so, I came across two libraries: fcm-django and django-push-notifications. I read the README file for both repos to try to understand the differences and choose one. It seems to me that fcm-django is better as it provides a better abstraction (only one model: FCMDevice) for all types of devices. If I were to use django-push-notifications then I would have to make 3 queries, one for each model (GCMDevice, APNSDevice and WNSDevice), to send the same message, which seems to me utterly redundant. However, django-push-notifications appears to be more famous (1.7k stars) so obviously I'm missing something here. The only advantage that I see is that for django-push-notifications I don't need to set up a firebase project if my app is web-only (in which case I would only need WNSDevice model), but still, what if I later decide to develop an android or iOS app? Isn't fcm-django approach more flexible? -
Cannot connect to my site through apache from outside work network
I inherited an apache web server setup with another VM running apache just to act as a firewall. After some digging around I thought I understood how it worked: VM-webfirewall IP = xxx.xx.xx.xxx our outside ip address VM-web-server IP = 10.1.1.72 our inside IP address. Webfirewall seems to run apache and has an /etc/httpd/sites-enabled folder with conf files for each of our internal websites like: weather.abc.com database.abc.com which is all from our www.abc.com now it has two conf files the second one always ending in -ssl.conf So an example of two conf files: flower.conf <VirtualHost *:80> ServerName flower.abc.com ServerAlias flower Redirect "/" "https://flower.abc.com </VirtualHost> then flower-ssl.conf #xxx.xx.xxx.xxx is of course our outside IP address of this machine <VirtualHost xxx.xx.xxx.xxx:443> ServerName flower.abc.com ServerAlias flower ServerAdmin workers@abc.com #DocumentRoot /dev/null LimitRequestLine 200000 <If "%{HTTP_HOST} != 'flower.abc.com'"> Redirect "/" "https://flower.abc.com/" </If> Include extra/ssl-certs ProxyRequests Off ProxyPass / http://thedb.abc.com:8080/ ProxyPassReverse / http://thedb.abc.com:8080/ <Proxy *> AuthType Basic AuthName "Flower Protected Website" AuthBasicProvider file AuthUserFile /etc/httpd/htpasswd Require user flowerdb Order deny,allow Allow from all </Proxy> </VirtualHost> So these work great! The request comes in, it goes off to our flower database and boom right away if you are offsite asks for a user name and password. This … -
Is it possible to keep Django Admin Panel accesible in production mode? (DEBUG=False)
I am developing a webpage for my college where we will show ouur investigations, to solve that i decided to use the admin panel. The problem is that when I deply in production the webage I get a 500 Bad request I have left the deault admin path Also changed the path for admin and still having the same issue -
django-tables2: Displaying a dict
I want to display a list of dicts, that is not coming from a model. The list is produced by calling an external API(GETDATAFROMAPI()). The dict looks like this: [{"name": "testname", "value": 23}, {"name": "test2name": "value": 123}] My views.py looks like this: class Index(SingleTableView): table_class = ProductTable login_url = '/login/' def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) context['table'] = GETDATAFROMAPI() return self.render_to_response(context) any the tables.py: class ProductTable(tables.Table): PName= tables.columns.TemplateColumn(template_code=u"""{{ record.name}}""", orderable=False, verbose_name='productName') class Meta: attrs = {"class": "table table-striped table-hover table-borderless",} fields = ("PName",) sequence = fields empty_text = ("There are no shelves ") -
How to serialize 2 models fields as one form?
I have following serializers: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['profile_pic'] class UserSerializer(serializers.HyperlinkedModelSerializer): userprofile = ProfileSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'password', 'is_superuser','userprofile') extra_kwargs = {'password': {'write_only': True, 'required': True}, 'is_superuser': {'read_only': True, 'required': False}} def create(self, validated_data): user = User.objects.create_user(**validated_data) # UserProfile.objects.create(author = user) # Token.objects.create(user=user) return user And UserProfile model extended from user: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(null=True, blank=True) def __str__(self): return self.name So, currently I get following data: { "id": 11, "username": "Arman1", "email": "bsai@gmail.com", "is_superuser": false, "userprofile": { "profile_pic": null } } But now I want to API in same level with main User like this: { "id": 11, "username": "Arman1", "email": "bsai@gmail.com", "is_superuser": false, "profile_pic": null } Please help me to do this. Thanks in advance! P.S I tried to do the following: def to_representation(self, instance): data = super(UserSerializer, self).to_representation(instance) userprofile = data.pop('userprofile') for key, val in userprofile.items(): data.update({key: val}) return data However, it returns 'NoneType' object has no attribute 'items' -
Django annotated queryset - resulting SQL query duplicates
Let's imagine I have two models: User and Event: class User(models.Model): email = models.EmailField(_('Email'), max_length=255, unique=True, db_index=True) class Event(models.Model): class Type(models.IntegerChoices): ONE = 1, 'One' TWO = 2, 'Two' type = models.PositiveSmallIntegerField('Type', default=Type.ONE, choices=Type.choices, null=False, blank=False) when = models.DateTimeField(_('When?'), blank=True, null=True) Now I have a queryset that is defined like below, to filter on users whose number of events are a multiple of 5. Using the db-side function Mod(). cycle_size = 5 users = User.objects.annotate( event_count=Coalesce(Subquery( Event.objects.filter( user__pk=OuterRef('pk') ).order_by( 'user__pk' ).annotate( count=Count('pk', distinct=True) ).values( 'count' ), output_field=models.IntegerField() ), 0), event_cycle_mod=Mod(F('event_count'), Value(cycle_size )) ).filter( event_count__gt=0, event_cycle_mod=0 ) It works. But The resulting SQL query that is generated looks like the following: SELECT `user`.`id`, FROM `user_user` WHERE ( `user_user`.`id` IN ( SELECT V0.`id` FROM `user_user` V0 WHERE ( COALESCE( ( SELECT COUNT(DISTINCT U0.`id`) AS `count` FROM `event_event` U0 WHERE ( U0.`user_id` = V0.`id` ) GROUP BY U0.`user_id` ORDER BY NULL ), 0 ) > 0 AND MOD( COALESCE( ( SELECT COUNT(DISTINCT U0.`id`) AS `count` FROM `event_event` U0 WHERE ( U0.`user_id` = V0.`id` ) GROUP BY U0.`user_id` ORDER BY NULL ), 0 ), 5 ) = 0.0 ) ) ) The question is the following: is it normal that the whole COALESCE() and … -
TypeError: must be real number, not str : Django
I'm getting this Error: TypeError: must be real number, not str. when i printing the request data lat2, lon2 then it's print float types of number. when i running below code then it's throwing me error that, must be realnumber not str type. It would be great if anybody could help me out to solve this issues. thank you so much in advance. def distance(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) # Haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2 c = 2 * asin(sqrt(a)) r = 6371 # Radius of earth in kilometers return(c * r) # calculate the result class GarageShopDetailAPIView(APIView): def get(self,request,*args,**kwargs): lat2 = self.request.GET.get('lat2', None) lon2 = self.request.GET.get('lon2', None) queryset = ShopOwnerShopDetails.objects.filter(id=query_id) serializer = ShopOwnerShopDetailsSerializer(queryset, many=True, context={'request':request}) data = serializer.data km_difference = [] for record in data: lon1 = record['lon'] lat1 = record['lat'] km_differ = distance(lon1, lat1, lon2 , lat2) km_difference.append({"km_difference":km_differ})