Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it normal to have a settings file for each staging instance/version in a Django project?
Some people use just one settings file for their project. A good alternative is writing modules, replacing the one settings file with a directory with configurations for each specific need: ... | settings | |-base.py |-local.py |-local_alex.py |-production.py |-staging.py |-test.py I guess it's normal to have one single settings file for production. But what happens if I have more staging instances/versions? Let's suppose I have a postgresql DB for each staging instance/environment. Is it ok to have more staging files? Or should I treat the differences between staging versions in another way? So I could wether have two settings file, one for each staging version or use the same settings file but specify these differences in another way. What is the recommended approach? DjangoTwoScoops recommends having more local.py settings files, but no one mentions about several staging files. Example, I have the production, local and test files. But two staging versions, each with an URL and different database. DATABASES = { 'default': { ... 'NAME': 'dbname1', 'USER': 'username1', ... } } and the second one: DATABASES = { 'default': { ... 'NAME': 'dbname2', 'USER': 'username2', ... } } -
Display list elements using index of dictionary in Jinja(Django)
I'm using Django Version 2.1.7,jinja2 and i trying to iterate list inside a dictionary using forloop.counter0 in Jinja template. MyCode Views.py : def sample(request): datas= ['value1','value2','value3'] #list data={'val1','val2','val3'} #dictionary return render(request,'index.html',{'datalist':datas,'datadic':data}) Index.html (Jinja): {% for dic in datadic %} {{ dic }} {{ datalist.forloop.counter0 }} {% endfor %} <!-- datalist.0 is only possible after research ,but is it constant for every iteration --> Expected output : val1 value1 val2 value2 val3 value3 -
"No installed app with label 'admin'" in empty Django 2.2 project
I am starting a new project in Django 2.2 using the same commands as I always do: python3 -m venv django-env . django-env/bin/activate pip install django django-admin startproject mysite cd mysite/ python3 manage.py runserver 8080 This should result in a running Django site, ready to write some code. Unfortunately, now I'm getting a strange error: LookupError: No installed app with label 'admin'. However after downgrading version of Django with pip install django==2.1.8 Everything is back to normal and works as expected. I have looked at Django 2.2 release notes and list of backward incompatible changes and deprecated features and haven't found anything. Can anyone please shed some light as to what is happening? -
How to ignore certain objects in admin view of model
How can I ignore objects of a model in an admin view, with certain attribute values? For instance: Don't list objects where model.name = "Fire" -
How to pass multiple objects as context to templates in class based generic view in django?
I need to pass two different objects to my template,I tried to pass but it showing only one. I tried to pass it as dict but i got stuck, then i choose this method which also results in getting only the data from the first object. In template tag i used views.py class ShowTable(ListView): model = TestUser def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['vechile'] = Vechile.objects.all() return context testuser_list.html {% for comment in object_list %} <tr> <td>{{ comment.name }}</td> <td>{{ comment.address }}</td> <td>{{ comment.phone }}</td> <td><a href="{% url 'myapp:edit-table' comment.id %}">edit</a></td> <td><a href="{% url 'myapp:delete-table' comment.id %}">Delete</a></td> </tr> {% endfor %} {% for comment in object_list %} <tr> <td>{{ comment.name }}</td> <td>{{ comment.bike }}</td> <td>{{ comment.car }}</td> </tr> {% endfor %} I need to display data from both the models(TestUser and Vechile), Now i'm getting data from TestUser model only. -
How to get the IP Address from the views or middleware to the model?
Since few hours ago I am facing a basic problem sod I have decided to ask a question after tried to do many many example but I still have an error. my answer is that I want to put the user's country according to his ip address for the registration or other queries. I mean the ip address will be collected from a view function with or my middleware file. I want to do like this but I want to get the ip address from my view or my middleware as I said it. This is my function to get the ip address from my view or my middleware file: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip So once I got the ip address let's say from my view how can I get this ip address to my models to do this process below? this is what I expected for: ip = '93.254.222.80' readerone = GeoIP2() readerone.country_name(ip) visitor_info = readerone.city(ip) dma_code = visitor_info['dma_code'] city = visitor_info['city'] continent_code = visitor_info['continent_code'] continent_name = visitor_info['continent_name'] country_code = visitor_info['country_code'] country = visitor_info['country_name'] latitude = visitor_info['latitude'] longitude = visitor_info['longitude'] postal_code = visitor_info['postal_code'] region = visitor_info['region'] time_zone β¦ -
pass two value to a template tag
im new in django and python . in my template i need to pass two value to a template tag . this two value come from view.py .i read Django template, send two arguments to template tag? but i can resolve my problem. view.py: def order(request): . . . return render(request, 'cart.html', { "total_price": total_price, "final_verified": profile.teacher.final_verified, "cart": the_cart, "cart_items": the_cart.cartitem_set.filter(deleted=False), "discount": discount }) template.html: {% load tags %} <div class="pull-left"> <i> {% if final_verified %} {{ total_price|rials_to_toman|intcomma:False }} {% final_price total_price discount %} <!--problem is here--> {% else %} 0 {% endif %} </i>Price </div> tag.py: from django import template register = template.Library() @register.simple_tag def final_price(num,discount): return str((int(num) * int(discount)) // 100) i trying to pass two value to a template tag so i can calculate final price with "discount" and "product.price" just in a tag with name of "final_price" . -
Any possible way to add value from one list to value to another list till the loop ends
I am creating filter query for django rest framework, which will be similar to this as sample systemDate is None and startDate is None and endDate is Not None. truth table is to be created of is None and is Not None based on the number of elements in the list. I've used itertools to create the truth table the only problem left is adding the elements systemDate, startDate and endDate to every element of the list import itertools filter_names = input("Enter the name of the filters with comma\n") filter_list = filter_names.split(",") table = list(itertools.product(["is None", "is not None"], repeat=len(filter_list))) """ Here I'm converting the list of tuples to list of lists """ listre = [list(tup) for tup in table] count = 0 for x in listre: for value in filter_list: count += 1 for d in range(len(x)): print(x[d]) """ This is trial from which I was able to create a sample result but it not correct """ # for x in table: # for initial in x: # for value in filter_list: # if value is not None: # print(value+" "+initial+" and ") so the answer will be similar to this: startDate is None and endDate is None and β¦ -
Which Python frameworks should i use/combine to build a web application with real time dashboards/graphs?
I need to build a web application with real time dashboards with data from mysql database, I dont know which frameworks should i use to achieve this. I see many frameworks in google which support dashboards. I feel dash-plotly framework has some good results for dashboards. Django/flask alone is sufficient to achieve this ? or should i combine Django/flask with plotly ? -
Travis CI not reading my .flake8 file properly
I have the following project structure in Django: β .gitignore β .travis.yml β docker-compose.yml β Dockerfile β LICENSE β README.md β requirements.txt β ββββ.idea β misc.xml β modules.xml β recipe-app-api.iml β vcs.xml β watcherTasks.xml β workspace.xml β ββββapp β manage.py β ββββapp .flake8 settings.py urls.py wsgi.py __init__.py My .flake8 file is like this: [flake8] exclude = migrations, __pycache__, manage.py, settings.py My .travis.yml is like this: language: python python: - "3.6" services: -docker before_script: pip install docker-compose script: - docker-compose run app sh -c "python manage.py test && flake8" I created the .flake8 file in PyCharm, which does not recognise flake8 files - I had to create a new type, but Travis CI should read it correctly anyway. Is docker build . not recognising PyCharm's env? Or docker-compose not doing something right? I can't get my pipeline to build in Travis coz settings.py is failing flake8! -
RxPY vs clery vs threading
I am using python and I need to do something asynchronously, How to know if I need RxPY or celery or built-in threading library ? -
Finding attributes near route (linestring)
Basically I want to know if there is a way to query all objects with a geographic field that are near a linestring in django using postgis. I am calculating a route and want to find objects that are approximately on that route (say max distance from the linestring 2m - 10m). I cannot find a way online that seems to solve this. I can ofcourse create an interval around the route of say 2m, and then create an polygon using these intervalls and check which points fall within this created surface, but i wonder if there is a more direct approach (the way i described above). This is some psu-code for my first described method (this i want) def get_objects_on_route(): Model.objects.filter(geo_location__some_lookup=all_points_in_route_route, max_distance=2m) other method which I could implement def get_objects_on_route(): points_in_surface = [] for each element in route: points_in_surface.append(two_corrected_points) poly= Polygon(all_points_on_route) Model.objects.filter(geo_location__covered_by=poly) -
No value passed to Javascript Function from HTML code
I am trying to pass a context variable to my javascript function like this in my HTML code. HTML CODE - {% for user in users %} <tr class="datarow" name='user_row' onclick='updateUser("{{ user.id }}")'> <td hidden="hidden" name='user_id' value="{{ user.id }}"> {{ user.id }} </td> ..... Till yesterday this method was working fine but now nothing is passed to this function. When i try to log the value or this user id in console It shows - undefined. The value of {{ user.id }} is shown in the below cells. But it is not being passed to the "updateUser" function. -
Pyinstaller is unable to import custom commands of Django 2.1.5
Pyinstaller is unable to import custom django commands. I am working on django 2.1.5. I tried adding my command in pyi_rth_django.py file located at Pyinstaller/loader/rthooks, but its not working for me. I have added it like 'command name': 'app name' in the dictionary. I got some solutions but that is for Django 1.8, and even the file "pyi_rth_django.py" says that it is tested with Django 1.8. Then how should i do it in Django 2.1.5 ? Thanks In Advance -
How to improve query performance n+1
I have the following: #models:py class Author(models.Model): name = models.CharField(max_length=20) class Book(models.Model): author = ForeignKey(Author) title = models.CharField(max_length=20) class Comment(models.Model): book = ForeignKey(book) title = models.CharField(max_length=20) #views.py class AuthorBookComment(ListView): model = Author paginate_by = 5 template = βtemplate.htmlβ #template.html {% for author in object_list %} <h2>{{ author.name }}</h2> {% for book in author.book_set.all %} <h3>{{book.title}}</h3> {% for comment in book.comment_set.all %} {{comment.title}}<br/> {% endfor %} {% endfor %} {% endfor %} <<pagination code>> The idea is to display all authors and their books and comments (if such exist). The challenges: 1. Performance degradation as data volumes increase (number of sql requests = n+1). 2. Pagination on Author set vs. Author + Book + Comment set. Question: How can the above be improved/optimised? -
how to protect user from editing others blog posts in django?
I am making a blog with django. The people who are the owner of the blog post can only edit the blog post. how to protect the route? should I make a custom middleware or there is an easy way -
Failing collectstatic with ManifestFilesMixin
I am using ManifestFileMixin to version my staticfiles before uploading to Google cloud storage Below is the custom storage class class CustomStorage(ManifestFilesMixin, S3Boto3Storage): pass in the settings.py STATICFILES_STORAGE = 'myapp.storage.CustomStorage' And here is the stacktrace: .venv/lib/python3.6/site-packages/storages/backends/s3boto3.py:282: UserWarning: The default behavior of S3Boto3Storage is insecure and will change in django-storages 2.0. By default files and new buckets are saved with an ACL of 'public-read' (globally publicly readable). Version 2.0 will default to using the bucket's ACL. To opt into the new behavior set AWS_DEFAULT_ACL = None, otherwise to silence this warning explicitly set AWS_DEFAULT_ACL. "The default behavior of S3Boto3Storage is insecure and will change " Traceback (most recent call last): File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 128, in collect for original_path, processed_path, processed in processor: File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 402, in post_process yield from super().post_process(*args, **kwargs) File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 236, in post_process for name, hashed_name, processed, _ in self._post_process(paths, adjustable_paths, hashed_files): File "/home/ufaz/webapps/ufaz_website/.venv/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 293, in _post_process β¦ -
Why web dev community (especially djnago/flask) don't care about OData standard?
I've been used to create REST-based web services in Django and Flask. When I come to know OData standards, it seems like an obvious route to go down. But I couldn't find any help (or anybody) to adopting it primarily or the future of such powerful protocols is really fascinating in a producer/consumer's perspective. Quite similar questions are already asked but a long time ago. Does anyone outside the MSFT community care about OData? OData Python Library available? I would like to know how to expose data as OData or consume, it specifically in Python's web frameworks? -
Getting ERROR on chrome.cookies.onChange.addListener()
I new in web developing ,in new homework i need to do something when cookie with specefic value="val" changed .but when i use chrome.cookies.onChange.addListener(function{}) error apppear: Uncaught TypeError: Cannot read property 'onChanged' of undefined at script_8.js:1462 here is javascript code : chrome.cookies.onChanged.addListener(function(changeInfo) { console.log("cookie changed!"); }); and PyCharm even get error : https://pasteboard.co/I8xuT1R.png Thank you -
How to create a windows service for Django rest api?
How do I setup Django as a windows service using sc? I tried examples online but all it does when executed is run and close immediately. When checking the services window it's not there so I assume it's not running properly or being executed properly. So far I have the following two files. a createService.cmd file: sc create DjangoExample DisplayName=DjangoExample binpath= "D:\Python\Service\DjangoExample\runService.cmd" and a runService.cmd: python restAPI/manage.py runserver 0.0.0.0:8000 and the file structure is something like -DjangoExample |- createService.cmd |- runService.cmd |- restAPI |- manage.py |- accounts |- restAPI Not sure why it won't run django as a windows service. Would really like to get this part going. -
Django Middleware plugins vs. Views
I am learning Django and came upon the concept of middleware. I having a hard time understanding the difference between middleware and logic contained in a view. My understanding is that middleware is python logic that grabs data from sources outside of a websites main db, whereas a view is python logic to grab from the main website db? Is this understanding correct? If not, can somebody help explain? If it is correct, is a middleware just an API call then? -
Can someone provide guidance regarding django app migration?
I am migrating an old django app to new django version. That app was created in django 1.0. Now i am planning to migrate it to django 1.11. This is my first attempt towards migration. If anyone can provide a guide-line or need-to-do-things to keep in mind, that will be highly appreciated. Thanks. -
How to resolve Object of type 'AttributeError' is not JSON serializable?
I'm trying to understand Django DRF and am trying to do something complicated from my knowledge. In my application, I have invite keys, but I only want to allow the user to create an invite key after 3 days or if this is their first key. How do I create the serializer and view for this in a better way? I have tried and read other questions on the web, but cannot get a good grasp on achieving what I want. All I have in mind is thin views, thick serializers. My view portion is not working correctly due to Object of type 'AttributeError' is not JSON serializable That error is coming from my view, that much I know. My Serializer: class InviteKeyCreateAllSerializer(serializers.ModelSerializer): current_user = serializers.SerializerMethodField('_user') is_take = serializers.SerializerMethodField() class Meta: model = Invite_Key exclude = [ 'user_submitter', 'user_receiver', 'uuid', 'status', 'is_taken', 'is_locked', 'claim_date', 'expire_date', ] # Use this method for the custom field def _user(self, obj): request = getattr(self.context, 'request', None) if request: return request.user def get_is_taken(self, obj): return False def get_status(self, obj): return 'valid' # end of custom fields def create(self, validated_data): key = Invite_Key( user_submitter=validated_data['request.user'], ) key.set_user_submitter(validated_data['user_submitter']) key.save() return key My View class InviteKeyAllCreateView(generics.CreateAPIView): """ POST invitekey/ β¦ -
Unable to connect to Django with oracle ebs database
I'm trying to build my first web application using Django. I'm actually referring to Using Python With Oracle Database 11g (under the section 'Using the Django Framework') however while trying to execute the command python manage.py runserver i'm getting an error Steps followed django-admin.py startproject myproj cd myproj python manage.py startapp myapp Once the above commands were executed successfully, the next step was to modify the connection settings to allow the application to connect to the database in the file myproj/settings.py. Here i updated the details with our database details DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': '<our ebs database name>', 'USER': <username>, 'PASSWORD': <password>, } } Also added the project under the INSTALLED_APPS to associate the application with the project: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myproj.myapp' ] In a terminal window when i try to execute the below command from myproj directory: python manage.py runserver I'm getting the below error message C:\Users\xxx\Desktop\Python files\myproj>python manage.py runserver Unhandled exception in thread started by .wrapper at 0x00000274CA28AEA0> Traceback (most recent call last): File "C:\Users\xxx\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 118, in create cls = getattr(mod, cls_name) AttributeError: module 'myproj' has no attribute 'myapp' During handling of the above exception, another exception β¦ -
How to add data to database in loop from multiple textfields in template?
I have to enter marks obtained my all the students in a class. So I created a template with text fields to store the marks corresponding to each roll number. The id of each text field is the roll number of the corresponding student. How do I pass these marks from each field to views.py so that they can be stored in the database? I tried using Javascript but I so not know how to access a table in database(class in models) so as to extract the roll number of each student and access the text field. models.py class MarksForm(forms.Form): exam_type = forms.CharField(label='Exam Name', widget=forms.Select(choices=EXAM_TYPES)) entered_marks = forms.FloatField(label='Marks', required=True) def clean(self): examtype = self.cleaned_data.get("exam_type") enteredmarks = self.cleaned_data.get("entered_marks") return self.cleaned_data views.py @csrf_protect @login_required def edit_marks(request, course_code): print ('Inside Views') user = request.user extrainfo = ExtraInfo.objects.get(user=user) if extrainfo.user_type == 'faculty': instructor = Curriculum_Instructor.objects.filter(instructor_id=extrainfo) for ins in instructor: if ins.curriculum_id.course_code == course_code: registered_students = Register.objects.filter(curr_id = ins.curriculum_id.curriculum_id) for reg in registered_students: identity = Register.objects.get(student_id=reg.student_id, curr_id=curriculum[0]) m_id = identity.r_id student_marks = 'enteredmarks'+identity.student_id score = request.POST.get(studentmarks) exam = request.POST.get('examtype') Marks.objects.create( mid=m_id, exam_type=exam, marks=score ) context= {'registered_students': registered_students } return render(request, 'coursemanagement/viewperformance.html', context) urls.py urlpatterns = [ url(r'^$', views.viewcourses, name='viewcourses'), url(r'^(?P<course_code>[A-z]+[0-9]+[A-z]?)/$', views.course, name='course'), url(r'^(?P<course_code>[A-z]+[0-9]+[A-z]?)/edit_marks$', views.edit_marks, name='edit_marks'), β¦