Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}) -
how to insert excel file into sql satabase of django and then read that file?
What i want to do is that i want to save an excel file into my db. I am working on python django and db is sql. Currently i have given path of my file to a variable and then reading that file. But i want to save file in database through choose file tag in html. Kindly help me in this regard -
I want to remove new line if present in a string using html django (python)
urls: path('admin/', admin.site.urls), path('',views.index,name='index'), path('analyze',views.analyze,name='analyze'), index.html <form action='/analyze' method='get'> <textarea name='text' style='margin: 0px; width: 721px; height: 93px;'></textarea><br> <input type="checkbox" name="removepunc"> Remove Punctions <br> <input type="checkbox" name="fullcaps"> Uppercaps<br> <input type="checkbox" name="newlineremove"> New line remove<br> <button type="submit">Analyse text</button> analyze.html: <body> <h1>Your analyzed text</h1> <p> <pre>{{analyzed_text}}</pre> </p> views.py: def index(request): return render(request,'index.html') def analyze(request): djtext=request.GET.get('text','default') newlineremove=request.GET.get('newlineremove','off') print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" for char in djtext: if char !="\n": analyzed=analyzed + char else: analyzed=analyzed + " " print(analyzed) params={'analyzed_text':analyzed} return render(request,'analyze.html',params) suppose newlineremove=="on" and input is: dam dam output is(for print in terminal): on dam dam dam but it was supposed to be: on dam dam dam dam but on the web (analyze.html) dam dam -
How to search a queryset by id without additional db calls in Django
Is there a way to search a Django queryset by id or a combination of fields without making additional calls to the database. Would something like this be a single db query? qs = Employee.objects.filter(restaurant='McDonalds') emp1 = qs.filter(id=1) emp2 = qs.filter(id=2) emp3 = qs.filter(id=3) Or is the only way to do something like this to map ids to the model instances beforehand? qs = Employee.objects.filter(restaurant='McDonalds') emp_map = {instance.id: instance for instance in qs} emp1 = emp_map.get(1) emp2 = emp_map.get(2) emp3 = emp_map.get(3) -
Django doesnt registrate my models from addon
I have migrated from Django 1.8 to 2.2 and I cant solve problem with database for few days. I have addon registrated in INSTALLED_APPS, then I have folder of my addon with apps.py,models.py and logic.py. Registration in INSTALLED_APPS: INSTALLED_APPS = [ ..., 'myapp.addons.pcpanalysis' ] Also tried 'myapp.addons.pcpanalysis.apps.PcpConfig'. My apps.py: from __future__ import absolute_import from django.apps import AppConfig class PcpConfig(AppConfig): name = "myapp.addons.pcpanalysis" def ready(self): from myapp.addons.pcpanalysis import logic logic.register_events() My handler of event in logic.py is working properly, but when event occur, I get this error: (1146, "Table 'project.myapp.addons.pcpanalysis_node' doesn't exist") I've tried to look into container with database and there are missing only models from my addon, all other models are in DB. I've tried to change names, check everything but seems that has no effect. I also don`t understand that my handler in logic.py and registration in apps.py works properly and there is problem only with models. I will be happy for all tips that I can try. Thank you! P.S. Everything was working properly in Django 1.8, migration to 2.2 changed it. I hadn't changed any settings variables before it occured. -
Can i deserialize a fk object using just the name field?
I have two models - one is a foreign key of the other, I have serializers for each. What I'm trying to accomplish is a way to serialize/deserialize using only the name of the foreign key field, rather than a nested object. The fk field in question is TableAction. My question is how do I define my serializer in order to accomplish this. I think maybe specifically I just need to know which serializer methods to override in order to drop that logic into. When I send a payload, I do not want to send a nested TableAction object, instead I just wanted to send the name of the TableAction. Due to business requirements I cannot change the structure of the payload being sent. models class TableEntry(models.Model): reward_table = models.ForeignKey( RewardTable, related_name="entries", on_delete=models.CASCADE ) action = models.ForeignKey( TableAction, max_length=100, related_name="entries", on_delete=models.CASCADE ) reward_item = models.ForeignKey( RewardItem, related_name="reward_table_entries", on_delete=models.CASCADE ) reward_item_amount = models.PositiveIntegerField() class Meta: unique_together = ("reward_table", "reward_item", "action") class TableActionManager(models.Manager): def get_by_natural_key(self, name, application): return self.get( name=name, application=application ) class TableAction(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) application = models.ForeignKey( Application, related_name="reward_actions", on_delete=models.CASCADE ) objects = TableActionManager() class Meta: unique_together = ("application", "name") def __str__(self): return self.name def natural_key(self): …