Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make the output "pretty" using Django Rest Framework?
Is there a way to format output that comes out from Django Rest Framework? What I'm looking for is a Django/DRF equivalent to PHP JSON_PRETTY_PRINT Currently, the output looks like this: {"id":1,"username":"bartalamej","city":"Ostrava","photo":"uploads/avatars/a84232eff3aa407db95ff792aec77414.jpg"} But I'd like it to look like this: { "id":1, "username":"bartalamej", "city":"Ostrava", "photo":"uploads/avatars/a84232eff3aa407db95ff792aec77414.jpg" } Does anybody know how to achieve this? -
django.db.utils.OperationalError: FATAL: database "clinilead_e " does not exist
After changing the db from sqlite to postgresql(python manage.py makemigrations)running, I am getting this error.How could i overcome this? DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'clinilead_e ', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '5432', } } -
why do i need RestFul api To link Between Angular and django?
` why do i need RestFul api To link Between Angular and django ? ` -
TypeError: Object of type 'Hit' is not JSON serializable
I am getting error when I run following script , "TypeError: Object of type 'Hit' is not JSON serializable". could anyone help me? class Multiresponse(View): def post(self, request, *args, **kwargs): input_data = json.loads(request.body.decode('utf-8')) if 'text' not in input_data: return JsonResponse({ 'output': ['The attribute "text" is required.'] }, status=400) Input = str(input_data["text"]) filterObj = FilterData(Input) filterObj.UpdateDB() result = filterObj.get() xx = json.dumps(result) if 'Sorry I could not understand' in xx: index_dir = os.path.join(settings.STATICFILES_DIRS[0],"textdata") ix= open_dir(index_dir) with ix.searcher() as searcher: query = QueryParser("content", ix.schema).parse(result) results= searcher.search(query, limit=3) if len(results)!=0: for res in results: print('filepath:', res['path']) return JsonResponse({"output": res}, status=200) else: return JsonResponse({"output": "No result found"}, status=200) else: return JsonResponse(xx, safe=False) -
Django StaticLiveServerTeastCase tests fail when run together
There are two tests both of then do the same thing log a user in if, if I run ever test individually but if I try to test the whole class the first passes and the second one gives Server Error ( 500 ) All of the tests involve the user logging in I tried creating users locally in each test but that didn't work either is any help is appreciated. class SomeTest(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(10) self.user = User.objects.create_user(username="user1",password="somepassword") self.user.save() qrt, created = Group.objects.get_or_create(name="A Team") qrt.user_set.add(self.user) def tearDown(self): self.browser.quit() def test_user_can_login(self): self.browser.get(self.live_server_url) user = self.browser.find_element_by_id("id_username") pa = self.browser.find_element_by_id("id_password") user.send_keys("user1") pa.send_keys("somepassword") pa.send_keys(Keys.ENTER) title = self.browser.find_element_by_id("title").text self.assertIn(title, "Welcome") def test_user_can_login_again(self): self.browser.get(self.live_server_url) user = self.browser.find_element_by_id("id_username") pa = self.browser.find_element_by_id("id_password") user.send_keys("user1") pa.send_keys("somepassword") pa.send_keys(Keys.ENTER) title = self.browser.find_element_by_id("title").text self.assertIn(title, "Welcome") -
Force Django to recognize multiple "models" folders in the same app?
My Django project is laid out strangely: /project |----manage.py |----/project |----settings.py |----urls.py |----/main |----/users |----/models |----__init__.py |----model1.py |----model2.py |----model3.py |----/views |----__init__.py |----view1.py |----view2.py |----/forms |----__init__.py |----form1.py |---form2.py |----urls.py |----/activities |----/models |----__init__.py |----model1.py |----model3.py |----/views |----__init__.py |----view1.py |----view2.py |----/forms |----__init__.py |----form1.py |----urls.py |----/migrations |----urls.py |----admin.py |----apps.py This is almost a normal setup—except users and activities aren't technically apps.; main is the app. My goal is to keep all migrations linear. When I run python manage.py, Django sees the models in main/users/models but not in main/activities/models. Is there a way of forcing Django to look in both folders when considering its migrations. I could create models folder w/ __init__.py that imports everything in main, but, if possible, I'd like to keep my current setup and just change where Django looks. -
RelatedObjectDoesNotExist when nesting data in DRF
I'm trying to serialize a model with nested data for its relationships. The data is returned properly in a GET request but when trying to POST data the following error is returned: api.models.Narration.narrative.RelatedObjectDoesNotExist: Narration has no narrative. I have no interest in POSTing nested data, it only needs to be returned in the GET requests and PKs can be used everywhere else. I have tried to using Meta.depth as well as defining the fields manually, both of which return the same exception. Code is below, any help is appreciated. # serializers.py class NarrationSerializer(ModelSerializer): narrative = NarrativeSerializer(read_only=True) settings = MapSettingsSerializer(read_only=True) attached_events = CachedDataSerializer(many=True, read_only=True) class Meta: model = Narration fields = "__all__" # depth = 1 [also doesn't work] # models.py class Narration(OrderedModel): narrative = models.ForeignKey(Narrative, on_delete=models.CASCADE) title = models.TextField() description = models.TextField() date_label = models.CharField(max_length=100) map_datetime = models.DateTimeField() attached_events = models.ManyToManyField(CachedData) img = models.URLField(blank=True, null=True) video = models.URLField(blank=True, null=True) settings = models.ForeignKey(MapSettings, on_delete=models.CASCADE) order_with_respect_to = "narrative" -
IntegrityError Null constraint violation two levels deep
I have three models in my django app...a members model, an application model and an applications review model. My members model looks like this... class Members(models.Model): TITLES = ( ('chairman', 'Chairman'), ('secretary', 'Secretary') ) user = models.OneToOneField(User, on_delete=models.CASCADE) title = models.CharField(max_length=10, choices=TITLES, default='secretary') My Applications model... class Application(models.Model): firstname = models.CharField(max_length=20) middlename = models.CharField(max_length=20) lastname = models.CharField(max_length=20) dob = DateField() The applications review model... class ApplicationsReview(models.Model): APPLICATION_STATUS = ( ('pending', 'Pending Review'), ('approved', 'Approved'), ('rejected', 'Rejected') ) applicant = models.OneToOneField(Application, on_delete=models.CASCADE, primary_key=True) chairman = models.ForeignKey(Members, related_name='chairs', on_delete=models.CASCADE) secretary = models.ForeignKey(Members, related_name='secretaries', on_delete=models.CASCADE) application_status = models.CharField(max_length=10, choices=APPLICATION_STATUS, default='pending') status_justification = models.TextField() date = models.DateTimeField(auto_now_add=True) When an application is created, I would like its review instantiated as well, hence, I have the following signal right below the applications review model... # When an application is created, create with it an application review and associate it with the application instance @receiver(post_save, sender=Application) def create_application_review(sender, **kwargs): instance = kwargs['instance'] created = kwargs['created'] if created: ApplicationReview.objects.create(applicant=instance) However, when I try to add an application in django admin I get the error null value in column "chairman_id" violates not-null constraint DETAIL: Failing row contains (3, pending, 2019-02-08 03:26:04.643452+00, null, null). The error seems to be as … -
How to clear up the certain columns of the same title generated by Django
I am trying to display some records generated by Django. If it has same title, it only displays certain fields, not all of them. #html <table class="table"> <tr> <td>Title</td> <td></td> <td></td> <td></td> </tr> {% for item in items %} <tr> <td>{{ title }}</td> <td>{{ first name }}</td> <td>{{ last name }}</td> <td>{{ item_1}}</td> <td>{{ item_2}}</td> </tr> {% endfor %} ... If the title is the same, I want to display first name, last name once such as title-1, Henry Wattson, Apple, Peach Cat, Dog title-2, Sarah Smith, Banana, Strawberry Hamspter, Parrot How can I do in Django, if not possible, in JQuery? -
how to include USA map in my django web application
I am preparing django web application. I am new to django. I want to include USA state map in my application. Please some one help me. -
Overriding Django Admin with AllAuth
I don't feel that the original django admin login is secure, so I want to have /admin always redirect to my AllAuth login page, even if the user is logged in. urls.py admin.site.login = login_required(admin.site.login) This will redirect users from the django admin login page if they are not logged in, but it does not redirect users if they ARE logged in. So they can still brute force it. How do I edit the login_required decorator to check for is_superuser. -
Custom submit form always redirects to a 'change' url (change_form)
I extended the change_list template of the django admin and plugged in a custom form inside. I have a custom action with url: /admin/automation/test/. The problem is my submit action always redirects to the change view url of django admin, so it always being appended with 'change' (/admin/automation/test/change/) in the url resulting to an error '/admin/automation/test/' being treated as an object id. For more context, the default change_list template of django displays links of items and when you click to an item (e.g. item-sample-1), it redirects you to the change_form of that item ...//change/ custom change_list.html: <form id="mark-module" method="POST" action="/admin/automation/test/"> {% csrf_token %} <select name="mark-option"> <option value="install">Mark as 'to install'</option> </select> <button class="button" type="submit">Apply</button> </form> -
Heroku Push Fail: error: RPC failed; curl 18 transfer closed with outstanding read data remaining
I'm deploying a Django project on Heroku but this error constantly occurred during git push heroku master: remote: -----> $ python manage.py collectstatic --noinput error: RPC failed; curl 18 transfer closed with outstanding read data remaining fatal: The remote end hung up unexpectedly fatal: The remote end hung up unexpectedly Everything up-to-date I have searched other answers and it seems like it's the slow internet connection problem with huge codebase. So far I have tried: 1. increase the buffer git config --global http.postBuffer 1048576000 2. verified my Heroku account 3. added my SSH key to Heroku app But none of this worked. I still get no response at the collect statics stage and after a few hours the same error happened. Can someone tell me what's wrong with this? How can I fix this? Thanks a lot! the full log (venv) my@my-pc:~/Dropbox/CS/web/pro001$ git push heroku master Counting objects: 401, done. Delta compression using up to 4 threads. Compressing objects: 100% (390/390), done. Writing objects: 100% (401/401), 29.70 MiB | 1.57 MiB/s, done. Total 401 (delta 170), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.7 remote: -----> … -
How to integrated multiselected field in dropdown list in Django
I want to implement a filter function for a multiselected field. Since there are a lot of options, I cannot list all the options plainly on the webpage. I got the desire outcome from my colleague, which is integrating the multiselected in a dropdown list. As shown by the attachment. I wonder if it is possible to implement this using django? Has anyone do something like this? Would like to hear any advice that helps. I would really appreciate your time and help!! Multiselected field in dropdown list -
Using Pylatex with django
Could anyone tell me how I could render or generate a .tex file with information from a database and generate a pdf (with pylatex) from it, and in django display that PDF as an answer? -
What is the contain method in Dango rest_framework Filter
Let's say I have a database that looks like this: { name: 'We love Football', type: 'Sports', } { name: 'Let's play Football', type: 'Sports' } { name: 'Let's play Basketball', type: 'Sports' } I need to implement something like this: class GameAPIListView(ListAPIView): serializer_class = GameSerializer def get_queryset(self): term = self.request.GET['term'] data = Game.objects.filter(name.contains(term)) return data If I type "Fooball", the first two items will be returned, since they contain the token "Football". What is the correct way to do this? Thanks in advance. -
Django oAuth2 implementation details with external user database
I need to allow signing into my Django application located at example.com with user accounts of classmates.com without knowing their usernames and passwords. I know that I need to implement oAuth2 some how, but cannot figure out where to start, or if there is something to do in the classmates.com side. Any help would be much appreciated, thank you -
Django how to filter objects in Queryset
I know the normal way to filter item in a QuerySet looks something like this: class GameAPIListView(ListAPIView): serializer_class = GameSerializer def get_queryset(self): data = Game.objects.filter(name="Football") return data What if I have a model that looks like this: { "category_id": { "parent_id": { "name": "Sports", "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1", "parent_id": null }, "name": "Football", "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35" }, "name": "Play Football", } { "category_id": { "parent_id": { "name": "Sports", "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1", "parent_id": null }, "name": "Basketball", "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35" }, "name": "Play Basketall", } { "category_id": { "parent_id": { "name": "Poker", "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1", "parent_id": null }, "name": "blackjack", "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35" }, "name": "Play blackjack", } And I would like to get all the items whose name of its parent_id is Sports. In this case I will get Football and Basketball. I tried something like data = Game.objects.filter(category_id.parent_id.name = "Sports") But it did not work. Can someone show me the correct way to do this? Thanks a lot! -
How to show a django-admin command in the Django admin web interface?
I've written a couple of django-admin commands, and they work fine on the command line. Is there some way to register these with the Django admin web interface for accessibility, similar to how models are registered? -
I'm wondering the most effective way to send logout to POST from Django
I would like to process logout in POST way. I would like to put a logout link in the navbar if the user session is verified. However, I did not use the POST method with the anchor tag, so I used the form button. However, the form button does not match any other anchor tag because it is a button-like shape, unlike an anchor tag. Is there a good way to solve this problem? For example, if there is a way to apply the http method directly to the anchor tag, I would like to know. -
sending image through android app to django server and executing python scripts on that image
i want to create an android app that will send image to server using Django rest framework. The Django server should execute python scripts on the image and send the result back to the android app. Basically i am creating a project that has to take photos of clothing(shirts, pants) and find the measurements of that clothing and then compare it with the size charts of different brands and tell the user that what size of which brand will best fit them. -
Django 'list' object has no attribute 'model'
// Views.py class GameAPIListView(ListAPIView): serializer_class = GameSerializer def get_queryset(self): term = self.request.GET['term'] result = [] data = Game.objects.all() print(data) for item in data: if item.category_id.parent_id.name == term: result.append(item) elif item.category_id.name == term: result.append(item) elif term in item.name: result.append(item) return result // Models class Category(models.Model): category_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) notes = models.CharField(max_length=200) def __str__(self): return '{0}, parent: {1}'.format(self.name, self.parent_id) class Game(models.Model): name = models.CharField(max_length=50) category_id = models.ForeignKey(Category, on_delete=models.CASCADE) start_time = models.DateTimeField('Start Time', null=True, blank=True) end_time = models.DateTimeField('End Time', null=True, blank=True) opponent1 = models.CharField(max_length=200, null=True, blank=True) opponent2 = models.CharField(max_length=200, null=True, blank=True) description = models.CharField(max_length=200) status_id = models.ForeignKey(Status, on_delete=models.CASCADE) // API result { "category_id": { "parent_id": { "name": "Sports", "notes": "Sports", "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1", "parent_id": null }, "name": "Football", "notes": "Football", "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35" }, "name": "Football Game", "description": , "start_time": "2019-01-01T03:32:30Z", "end_time": "2019-01-31T03:32:35Z", "opponent1": , "opponent2": ", "status_id": "ca286fb8-ee9e-4264-a15f-9165e1cb038b" } API request: http://127.0.0.1:8000/users/api/games/?term=Sports I am writing a backend API to filter the games. First, I tried to filter the game through the parent cateogry and then by its category and the name of the game. I tried to implement this in the View.py, but I got the error says that: AttributeError: 'list' object has … -
The instant type changes to int in Foreign Key in Django
This is my models.py in django class Site(models.Model): # Site ID siteID = models.CharField(max_length=255, null=True, unique = True) def __str__(self): return "{} ".format(self.siteID,) class EndDevice(models.Model): edevID = models.CharField(max_length=255) siteID = models.ForeignKey(Site, on_delete=models.CASCADE) deviceCategory = models.BigIntegerField() And this is the method to post in views.py: class RegisterSite(generics.ListAPIView): ''' GET site/ POST site/ ''' queryset = Site.objects.all() serializer_class = DataSerializer # POST Regisger Site def post(self, request, *args, **kwargs): a_site = Site.objects.create( siteID=request.data["siteID"], # edevID=request.data["edevID"] ) return Response( data=DataSerializer(a_site).data, status=status.HTTP_201_CREATED ) class RegisterDevice(generics.ListAPIView): ''' GET device/ POST device/ ''' queryset = EndDevice.objects.all() serializer_class = DeviceSerializer def post(self, request, *args, **kwargs): siteID, created = Site.objects.get_or_create( siteID=request.data["siteID"], ) a_site = EndDevice.objects.create( edevID=request.data["edevID"], siteID = siteID, deviceCategory=request.data["deviceCategory"], ) return Response( data=DeviceSerializer(a_site).data, status=status.HTTP_201_CREATED ) So what I am trying t do here is use the siteID from class Site for class EndDevice. But when I enter/ chose the value of siteID in Enddevice it changes to integer value. I checked the data base and it shows me int as its (siteID in EndDevice) characteristics. I was wondering how could I get the real value of siteID instead of an integer value.And I can accept character values while posting for class Site. Thanks -
Django - Is there a way to optimize ORM ManyToOne calls in a loop?
I see myself having this kind of pattern in my Django views: <ol> {% for a in ModelA %} <li>{{ a.title }}</li> <ol> {% for b in a.modelb_set.all %} <li>{{ b.title }}</li> <ul> {% for c in b.modelc_set.all %} <li>{{ c.text }}</li> <ul> {% for d in c.modeld_set.all %} <li>{{ d.text }}</li> {% endfor %} </ul> {% endfor %} {% endif %} </ul> {% endfor %} </ol> {% endfor %} </ol> The problem here of course is that this is making n^4 database calls, which is very unscalable. For a single ModelA object, I am making about 23 SQL queries, and I assume this number will only go up as the number of ModelA queries goes up. Is there a general way to lower the number of queries that are needed to be made here? Any ideas would be appreciated :) (If you're curious, the actual code is here - ModelA is Poll, ModelB is TextChoiceQuestion, ModelC is TextChoice and ModelD is TextChoiceNuance. -
Django - call celery Task from view
i want to call a celery task from my views.py but for some reason i get the following error: 'function' object has no attribute 'objects' views.py def wallet_deposit_gen_new_addr_btc(request, pk=None): if request.method == 'GET': user = get_user_model.objects.get(pk=pk) allocate_new_btc_address.delay(user) else: user = request.user args = {'user': user} return render(request, 'MyProject/wallet_deposit.html', args) tasks.py @app.task def allocate_new_btc_address(user): new_address = subprocess.Popen(['electrum', 'createnewaddress']) try: user = user.objects.update_or_create(acc_btc_addr=new_address) user.save() print(new_address) logger.info("New BTC address has been allocated to a user account") except Exception as e: print(e) Thanks in advance