Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django_migrations table not update
After modifying a model, I run: python manage.py makemigrations MYAPP and then I apply the migration: python manage.py migrate MYAPP I get Applying MYAPP.0010_auto_20180406_1453... OK and if I look to the table with MySQL commands, the modification is applied. However I get: python manage.py showmigrations --list ... MYAPP ... [ ] 0010_auto_20180406_1453 ... It seems that the table django_migrations was not updated. Why? -
Django migrate multiple databases
Environment: Django 2, Python 3.6, PostgreSQL (optional) I am writing an application with multiple models, some of them might be stored in different databases. Example: models.py (might be in different apps) # this used to allow field 'database' to be processed in 'Meta' models.options.DEFAULT_NAMES = models.options.DEFAULT_NAMES + ('database', ) class MyModel01(models.Model): ... # this goes to default database class MyModel02(models.Model): ... class Meta: database = 'mydb02' class MyModel03(models.Model): ... class Meta: database = 'mydb03' routers.py: class MyRouter(object): def db_for_read(self, model, **hints): return getattr(model._meta, 'database', None) def db_for_write(self, model, **hints): return getattr(model._meta, 'database', None) def allow_migrate(self, db, app_label, model_name=None, **hints): model = hints.get('model') if not model: return None if db != 'default': modelname = model_name or model._meta.model_name usedb = getattr(model._meta, 'database', None) if not usedb: return False if modelname and usedb: return usedb == db return False else: usedb = getattr(model._meta, 'database', 'default') return usedb == db return None settings: DATABASES: { 'default': { # some db settings }, 'mydb02': { # db settings }, 'mydb03': { # the SAME db settings as for mydb02 } } The issue is that in settings there might be the same database set for all database aliases. When I run migrate the migration get … -
Random URLs return error code 500 instead of 404
In my urls.py file, I've got the following : def error_404(request): return render(request, 'shop/errors/404.html') def error_500(request): return render(request, 'shop/errors/500.html') handler404 = error_404 handler500 = error_500 However, when I enter random urls, like "mysite.com/lhazeglazd", a 500 error page is returned. What is causing 500 errors from overriding my 404 errors ? -
Django Rest Framework how to disable authentication and authorization
I am trying to build a system in Django without using any of django's batteries -- auth, admin etc. The system uses django rest framework for the API. However, when I try to request to an API, I keep getting this error: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I do not want to use django.contrib.auth at all. I did the following inside my DRF API View class: class NewsPostView(APIView): permission_classes = None def get(self, request, format=None): posts = NewsPost.objects.all() serializer = NewsPostSerializer(posts, many=True) return Response([]) However, I am still getting the same error. How can I disable auth from DRF? -
how to get all coordinates under a city in Google Maps
I'm building an App and I want people to lets say search for New York and get all the posts from Brooklyn and Queens etc etc. I'm new to google maps api and saw that it gives coordinates for a city how am i suppose to get all the locations / coordinates under a given location/city/town etc Thank You -
Django problems with saving files to s3
I am trying to save files to default storage which is S3. But I get the status of 400 when I try to save files. Here is how I'm doing this: path = default_storage.save(settings.TEMP_DIR + f'/{self.zip_file.name}', ContentFile(self.zip_file.read())) Here is my storages file where I' m setting my S3 storage: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Here is my settings.py: STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'config.storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'config.storages.MediaStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') TEMP_DIR = MEDIA_ROOT + '/temp' -
Django continuous tasks for small local app
All it needs to do is run a script that talks to the source data website API every minute and update the context dictionary and inject it into the index page... (This will only ever be ran locally by one person. Ever) How can I run continuous tasks in python without a solution that requires a lot of outside dependencies and installations. Is there an easy self contained solution as long as my app remains simple? Celery requires a broker, and the installation of another program.(This will be tough to pack into a nice little selfcontained .exe later for my boss who will use this) Creating a new django-admin command is simple but does not seem to work because I want to run runserver and keep my app going at the same time. I know there are likely ways to do this but they seem complicated or need a lot of outside dependencies. What I want to do: I am creating a dashboard that reads Key Performance Indicators from the API of a website that we use. The task needs to run every minute and update my index page with the new values found in the API. -
add postfix info to url django
I realize stackoverflow does a trick with the url for making it more human readable It has the following pattern stackoverflow.com/questions/id_question/title_question for example we have stackoverflow.com/questions/36676286/counter-with-lambda-over-map-java8 And if you delete part of the title question and you go to the url left Example : stackoverflow.com/questions/36676286/counter-with-la You are still redirect to the correct url. Looks it only reads until the id, and then it adds the title info to the url , how I could add this information to the url? Thanks in advance -
Django allauth with email as username and multiple sites
Is it possible to use Django allauth with the authentication method set to 'email' when using it on multiple sites? I'm aiming to allow a user with the email address bob@example.com to create an account at site1.com and a separate account at site2.com. In order to use email authentication, I need to leave UNIQUE_EMAIL set to True in the settings but this prevents users who already have accounts in one site from creating accounts in the other site. -
How to duplicate inline objects to live in django cms?
I am new to django cms. I created a plugin with inlines. When I save the plugin and when I publish the page the model gets duplicated but the inline objects are not getting duplicated. Is there any way to do this? I want my inline objects also to save in live objects when I publish the page. Thanks is advance! -
Connect tableau to bitnami django stack postgres database
I am trying to connect the tableau to bitnami django stack which is being hosted on GCP instance with postgres database(included in bitnami django stack). Am trying to connect the tableau to my postgres for better analytics. I have already tried connecting to the local development system and that works fine for me, but when I try the server it is giving me the following error could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "xxx.xxx.xxx.xx" and accepting TCP/IP connections on port xxxx? Would like to open mydatabase for the specific connection. -
don't know how to fix this issue with django/mysql
How do I solve this problem? Whenever I try to do the command: python manage.py runserver, I am greeted with an error message like this. I don't know what to edit in order to fix it. Unhandled exception in thread started by <function wrapper at 0x10b774ed8> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Python/2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Python/2.7/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Python/2.7/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/Zach/A/podcast/podcast/AApodcast/podcast1a/podcast1a/urls.py", line 18, in <module> from The_Podcast import views File "/Users/Zach/A/podcast/podcast/AApodcast/podcast1a/The_Podcast/views.py", line 7, in <module> from The_Podcast.models import posts File "/Users/Zach/A/podcast/podcast/AApodcast/podcast1a/The_Podcast/models.py", line 8, in <module> class posts(models.Model): File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 118, in __new__ "INSTALLED_APPS." % … -
Display queried API results on a html page using python django
I'm currently creating a python app using the django webframework, that allows users to query an external API to get information about food nutrition (e.g calories, fats). Currently, when the user inputs their food in a search bar on the webpage, the API is queried and displayed in the terminal. I'm trying to display the information on the webpage but am having trouble rendering the data. form.py class NutritionForm(forms.Form): food = forms.CharField(max_length=100000) def search(self): # result = {} food = self.cleaned_data['food'] headers = { 'x-app-id': "ff0ccea8", 'x-app-key': "605660a17994344157a78f518a111eda", 'x-remote-user-id': "7a43c5ba-50e7-44fb-b2b4-bbd1b7d22632", 'Content-Type': "application/x-www-form-urlencoded", } url = 'https://trackapi.nutritionix.com/v2/natural/nutrients' body = { 'query': food, 'timezone': 'US/Eastern', } response = requests.request("POST", url, data=body, headers=headers) data = response.json() print ('food name: ', data['foods'][0]['food_name']) print ('food calories: ', data['foods'][0]['nf_calories']) print ('food protein: ', data['foods'][0]['nf_protein']) print ('food fats: ', data['foods'][0]['nf_total_fat']) views.py def nutritionix(request): search_result = {} if 'food' in request.POST: form = NutritionForm(request.POST) if form.is_valid(): search_result = form.search() else: form = NutritionForm() return render(request, 'nutrition/nutrition.html', {'form': form, 'search_results': search_result}) This is my html page that I am using to try and display the information. However, when I run the search, the API is queried, displayed in the terminal but, doesn't show up on the webpage. html {% … -
Django & modelChoiceFields : populate my model choice field with one of two models
I have a modelChoiceField field1, when I Choose one of its choices, another modelChoiceField field2 is updated with data. My problem is, this data can be a model1 type data or model2 type data. and since I have this : field2=forms.ModelChoiceField(queryset=model1.objects) the field2 can't be validated if it receives model2 , it's only valid if it receives model1. Any help please to make my field valid in both cases ? Thank You for your help -
while updating/editing my post,previously uploaded images are not showing in my update_post.html template
I want to update the posts i posted,they contain title,city etc fields and 10 image fields(image,image1,image2....etc),whenever i click update, the update form comes with all the text fields filled with previously saved data but image fields are not getting previously submitted images(they're showing empty)..i want them there and let the user change them or delete them etc...can anybody help me? here's my views for update_post def update_post(request, post_id): post_form = Posts.objects.get(pk=post_id) if request.method == "POST": form = AddFile(request.POST, request.FILES, instance=post_form) if form.is_valid(): form.title = request.POST.get('title') form.city = request.POST.get('city') form.price = request.POST.get('price') form.brand = request.POST.get('brand') form.modelyear = request.POST.get('modelyear') form.condition = request.POST.get('condition') form.mileage = request.POST.get('mileage') form.details = request.POST.get('details') form.image = request.POST.get('image') form.image1 = request.POST.get('image1') form.image2 = request.POST.get('image2') form.image3 = request.POST.get('image3') form.image4 = request.POST.get('image4') form.image5 = request.POST.get('image5') form.image6 = request.POST.get('image6') form.image7 = request.POST.get('image7') form.image8 = request.POST.get('image8') form.image9 = request.POST.get('image9') form.user = request.user form.save() messages.success(request, 'Post updated Successfully!') return render(request, 'vehicles_app/addfile.html', { 'form': form, 'post_form': post_form, 'post_id': post_id, }) else: messages.success(request, 'Post not updated Successfully!') print(form.errors) else: form = AddFile(instance=post_form) return render(request, 'vehicles_app/update_post.html', {'form': form, 'post_form':post_form, 'post_id': post_id}) here's the post_update.html <form id="post_form" method="post" action="{% url 'vehicles_app:update_post' post_id %}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="form-group"> <div style="float: left; width: 50%"> <label for="title">Ad … -
Using Django for existing html pages, and using my own login form
I have a pretty simple website, which consists of some online courses. All I need on the backend is a login system, and to use it to restrict access to courses. I've already done the frontend work, the html pages are all done. I want to try using Django, but when I was looking at tutorials to set up a login system, they all used the default login view, which is very plain.. I have a modal login form on my website (the login appears on index.html itself, not a separate login.html page). How can I use the looks of my login form with Django, to create a secure login? Would using Django be too much of a hassle, should I just use PHP instead? Note- I'm new to both PHP and Django (although I know Python). -
Django MPTT fetch children recursively
I got this code inside models.py class Member(MPTTModel): parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) name = models.CharField(max_length=120) I'm using Django with DRF. When I access http://localhost:8000/api/members/1/, I get something like this: { "name": "Test Parent", "parent": null } which is good. But I want something that when I access http://localhost:8000/api/members/1/children, I should get something like { "name": "Test Parent", "parent": null, "children": [ { "name": "Child 1" }, { "name": "Child 2", "children": [ { "name": "Child 2.1", "children": [ { "name": "Child 2.1.1" } ..... ] } ] } ] } How can I achieve something like the one above? -
Django post text using submit button without using input tag
I have a django template in which there is a form in which I am getting input from the user. template.html {% extends 'header.html' %} {% load staticfiles %} {% block content %} <h3> Questtion</h3> <img src="/media/{{ image }}" > <br> <br> <h3> Responses </h3> <form method="post" action="/tools/submit"> {% csrf_token %} <input type="text" name="first_response" placeholder="First Response" size="40" required> <input type="text" name="second_response" placeholder="Second Response" size="40" required> <input type="text" name="third_response" placeholder="Third Response" size="40" required> <input type="text" name="fourth_response" placeholder="Fourth Response" size="40" required> <input type="text" name="fifth_response" placeholder="Fifth Response" size="40" required> <button type="submit" >Submit</button> </form> {% endblock %} The text from input is easy to get with the following method in views.py def post_form(request): if request.method == 'POST': first_response = request.POST.get('first_response') second_response = request.POST.get('second_response') third_response = request.POST.get('third_response') fourth_response = request.POST.get('fourth_response') fifth_response = request.POST.get('fifth_response') image_name = # HOW TO GET {{ image }} name here ? But I want to also post {{ image }} from <img src="/media/{{ image }}" > also when the submit button is clicked. How can I do that ? -
Toggle icon on Like with Javascript
I have made a like button powered by ajax and I have defined a function that it refresh the text. Now I want to change it for updating from font awesome fa-heart-o to fa-heart and viceversa. How can I do it? see the code below base.html <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) btn.attr("data-likes", newCount) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, addLike) } else { updateText(this_, removeLike) // remove one like } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> and button like html <a class='like-btn' data-href='{{ comentario.get_api_like_url }}' data-likes='{{ comentario.likes.count }}' href='{{ comentario.get_like_url }}'>{{ comentario.likes.count }} {% if request.user in comentario.likes.all %} <i class="fa fa-heart"></i> {% else %} <i class="fa fa-heart-o"></i> {% endif %} Thank you for your help. -
Creating a Web App for the Stress Relief of people in the world [on hold]
I want to create a web app using Django or Nodejs which will be a stress reliever app can anybody help me like how should I initiate? -
Nested Field Gives TypeError upon indexing in elasticsearch-dsl-py
Whenever i try to save an object that has a nested field i get a Type error. TypeError: isinstance() arg 2 must be a type or tuple of types I have following document classes: class CreationIndex(InnerDoc): created_by = Keyword() created_date = Date() class UpdationIndex(InnerDoc): updated_by = Keyword() updated_date = Date() class IndustryIndex(DocType): name = Text(analyzer= 'english') creation = CreationIndex() updation = Nested(UpdationIndex()) class Meta: index = 'industry' def bulk_indexing(): elastic_connection = Elasticsearch(hosts=['localhost'], timeout=20) if elastic_connection.indices.exists('industry'): elastic_connection.indices.delete('industry') if elastic_connection.indices.exists('category'): elastic_connection.indices.delete('category') IndustryIndex.init() print('HI') bulk(client=elastic_connection, actions=(b.indexing() for b in models.Industry.objects.all())) My Industry Model is a django model (where i have used mongoDB so itself is a dynamic document) which is defined as class Industry(DynamicDocument,BaseCreationUpdation): name=StringField(required=True,unique=True) def save(self,*args,**kwargs): ''' ''' self=save_created_updated_info(self) super(Industry,self).save(args,kwargs) def indexing(self): objCreation = CreationIndex( created_by = self.creation.created_by, created_date = self.creation.created_date.date().isoformat() ) print(objCreation.to_dict()) obj = IndustryIndex( meta = {'id': str(self.id)}, name = self.name, creation = objCreation.to_dict(), updation = [], ) for objUp in self.updation: objUpdation = UpdationIndex( updated_by = objUp.updated_by, updated_date = objUp.updated_date.date().isoformat() ) print(objUpdation) obj.updation.append(objUpdation) print() print(obj.to_dict()) print() obj.save() return obj.to_dict(include_meta=True) @classmethod def index_document(cls,sender, document, **kwargs): document.indexing() Now whenever i run the bulk_indexing module it comes up with a problem : Traceback (most recent call last): File "<console>", line 1, in … -
Django REST framework JSON array GET
I am running a Django 2.0 and DRF (Django REST Framework) 3.8.0. I want to be able to GET JSON in a specific format as seen in GOAL NESTED JSON ARRAY. Right now, I am able to retrieve an JSON Array as shown in MY CURRENT JSON ARRAY. I have checked this question and it seems like we have the goal but i was unable to be successful. I have my model, view and serializer below. This is achieved by using this: GET /studentlectures/1/get_studlect/ where 1 is {pk} CURRENT JSON ARRAY: [ { "id": 1, "lecture": 1, "student": 1 }, { "id": 19, "lecture": 4, "student": 1 } ] GOAL NESTED JSON ARRAY { "id": 1, "student_code": "60637-009", "first_name": "Zoltan", "last_name": "Drogo", "lectures": [ { "lecture_id": 1, "subject_name": "English", "teacher_id": 1, "teacher_name": "Cirillo Kierans", "room": "Room A", "schedule": "08:00 AM - 10:00 AM" }, { "lecture_id": 2, "subject_name": "Math", "teacher_id": 3, "teacher_name": "Johanna Probate", "room": "Room C", "schedule": "08:00 AM - 10:00 AM" }, . . . . . . } MODEL: class Studentlecture(models.Model): student = models.ForeignKey(Student, default='') lecture = models.ForeignKey(Lecture, default='') studentlecture_name = models.CharField(max_length=20, default='ComputerScience Lectures') def __str__(self): return f'{self.studentlecture_name}' VIEW: class StudentlectureViewSet(ModelViewSet): """ API endpoint that allows groups … -
Django filter, filter return more than this source
print("Step 1",invs.count()) # -> 1000 # invs type: query invs2 = invs.filter(field___fields2__fields3=i) # i type:int print("Step 2",invs2.count()) # -> 40000 Is it normal for the filter function to return more than its origin ? Thank you. -
Django uploading files history for user
I am able to upload the files in django. I have also managed to register different users. But when the users log in , they all see the set of files that were uploaded by anyone. instead I want the user views only those set of files which he/she has uploaded. -
Django REST - How to make a test case that checks that a method is not allowed?
I have the following ModelViewSet: class OrderViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): I would like to create four test cases: Check that (partial) updating is not allowed via OrderViewSet Check that listing is not allowed via OrderViewSet Check that retrieving is not allowed via OrderViewSet Check that deleting is not allowed via OrderViewSet I'm facing a couple of issues. First, I'm unable to use reverse() for all of the test cases. The following test case works: def test_disable_read_order_list(self): response = self.client.get(reverse('api:orders-list', kwargs={'currency': 'eur'})) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) When I try to use reverse to get the URL of the detail route: reverse('api:orders-detail', kwargs={'currency': 'eur', 'pk': self.order.id}) I get: django.urls.exceptions.NoReverseMatch: Reverse for 'orders-detail' not found. 'orders-detail' is not a valid view function or pattern name. I have tried to hack around this by adjusting the URL that is used for the working test case: def test_disable_read_order_detail(self): response = self.client.get(reverse('api:orders-list', kwargs={'currency': 'eur'}) + str(self.order.id) + '/') self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) but then statuscode 200 is returned for some reason. What is the proper way to implement the unit tests I want?