Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: test cases development for filter query search
I am testing a Dajngo Library application, which has a Book model and a search bar to filter those books that contain title = 'q', for which I have implemented the following Class-based view: class BookSearchListView(BookListView): paginate_by = 3 def get_queryset(self): result = super(BookSearchListView, self).get_queryset() query = self.request.GET.get('q') if query: query_list = query.split() result = result.filter( reduce(operator.and_, (Q(title__icontains=q) for q in query_list)) ) return result In my tests.py, I have to develop test cases for the above view, but do not understand how to go about it. I have attempted the following: class BookSearchListViewTest(TestCase): """ Test case for the Book Search List View """ def setUp(self): test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user1.save() test_author = Author.objects.create(first_name='John', last_name='Smith') Book.objects.create(title='House', author=test_author, summary='Published in 1990', isbn='123456789123') def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('books')) self.assertRedirects(response, '/catalog/customer_login/?next=/catalog/books/') def test_query_filter(self): # what should be tested I am a complete novice in Django and have just started out with test cases. Please help! Thanks -
Steps to deploy django app with sql database on digitalocean
I want to deploy the Django app with sql database on digitalocean.I am confused how we the app on digitalocean.Please guide me to deploy it. -
How to receive invoke multiple tasks and collect task status with Django/Celery
I am setting up multiple tasks in my tasks.py, and calling the tasks from views.py. I want to invoke all the different tasks in a for loop so I can collect the status easily and build a progress bar. I am able to invoke all the tasks line by line currently (as shown below). Here are my questions: how do I invoke the different tasks from views.py in a for loop? it always give me an error of "unicode does not have attribute delay()". Or is there a better way to collect the statuses of different tasks and build the progress bar from them? I have tried to invoke the functions in views.py like this: for i in range (1, 6): functionName = "calculation" + str(i) functionName.delay(accountNumber) But this gives an error as stated above "unicode does not have attribute delay()" my guess is that the tasks are imported from tasks.py to views.py my current tasks.py: @shared_task def calculation1(arg): some action here @shared_task def calculation2(arg): some action here @shared_task def calculation3(arg): some action here @shared_task def calculation4(arg): some action here @shared_task def calculation5(arg): some action here my views.py: result_calculation1= calculation1.delay(accountNumber) result_calculation2 = calculation2.delay(accountNumber) result_calculation3 = calculation3.delay(accountNumber) result_calculation4= calculation4.delay(accountNumber) result_calculation5 = … -
How to implement single sign (SSO) on for internal apps
Currently, i am interning at a company in ID, they have assigned a task to research about single sign on implementation. So basically we have a number of apps that need authentication. I have been searching on google for possible scheme. The possible schemes are using SAML, Oauth2. But these protocols need the identity provider (IdP), so how implement those identity provider so it can be used for SSO? . One possible solution is using third parties like Okta and OneLogin. I imagined what the IdP does is storing user data using a DBMS such as postgres and then the apps request for authentication to this IdP. Or is there any other possible implementation for SSO?. Recently i have also heard about django-oauth-toolkit, is it have something to do with sso ? -
Django Channels 'ProgramConsumer' object has no attribute 'reply_channel'
I am using class based functions for Django Channels and I am receiving this error when I try to obtain the reply_channel of the client that connects with websocket_connect. I'm relatively new to channels Consumer.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread, ChatMessage class ProgramConsumer(AsyncConsumer): async def websocket_connect(self, message): print("connected", message) #What does this do??? Is it accepting the connection that is sent from the client html page await self.send({ "type": "websocket.accept" }) #Execute that code and wait await self.reply_channel.send({ "text": json.dumps({ "action": "reply_channel", "reply_channel": message.reply_channel.name, }) } ) I am trying to replicate the code below, but with class based functions. @channel_session def ws_connect(message): message.reply_channel.send({ "text": json.dumps({ "action": "reply_channel", "reply_channel": message.reply_channel.name, }) }) Below is the JQuery on my HTML page JQuery $(function() { console.log(window.location) var loc = window.location //var formData = $("#form") //Grabs the form element above //var msgInput = $("#id_message") //var chatHolder = $("#chat-items") //var me = $("#myUsername").val() var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } // Define endpoint var endpoint = wsStart + loc.host + loc.pathname // methods that come in the socket console.log("Connecting to " + endpoint) // … -
How to do multiple filtering on a queryset
I Need to make a rest api endpoint where the user can filter with multiple get parameters which are fields of the corresponding model. I got the list of model fields and obtained the get parameter values, i need to filter the all results by the given get parameters def get_queryset(self, *args, **kwargs): query_set = models.Resident.objects.all() fields = models.Resident._meta.get_fields() for x in fields: fieldValue = self.request.GET.get(x.name) fieldName = x.name if fieldValue is not None: query_set.filter(**{fieldName: fieldValue}) return query_set suppose if the user wanted to filter by username=foo & email=email@meail.com the queryset should return the value which matches the both conditions -
Send a Django variable to javascript
I'm trying to access a Django placeholder, which is an array from the database, in a javascript script for use within three.js I have the coord_x, coord_y and coord_z variables in views.py In my templates html (random testing numbers commented out, good for testing): ... for (var i = 0 ; i < numpoints ; i++) { var x = {{coord_x}}; var y = {{coord_x}}; var z = {{coord_x}}; // var x = Math.random() * (0 - 1) + 1 // var z = Math.random() * (0 - 1) + 1 // var y = Math.random() * (0 - 1) + 1 var dotGeometry = new THREE.Geometry(); dots.push(dotGeometry); dotGeometry.vertices.push(new THREE.Vector3(x, y, z)); var dotMaterial = new THREE.PointsMaterial( { size: 3, sizeAttenuation: false, color: 0xFF0000 }); var dot = new THREE.Points( dotGeometry, dotMaterial); scene.add(dot); } ... I'm guessing I need to somehow loop through the x,y,z variables? -
Django sort inside groups of related to foreign key objects
I have a following model: class Mountain(models.Model): name = CharField(max_length=200) class Climbing(models.Model): mountain = models.ForeignKey(Mountain) climber = CharField(max_length=200) date = models.DateField(auto_now_add=True) I want to group climbings by mountains and sort mountains by last climbing, also as sort climbings inside each mountain. Everest: 2018-12-21 2018-10-10 2000-01-30 K2: 2018-12-20 2018-11-30 What is the most effective way to implement it in Django but on side of database? I understand i can make a set of climbings, filter by related mountains etc, but i would like to make all calculations on postgres server. -
Django: Fields not saving to database
I'm using a state machine to manage the states of a Django model. I run the state machine in the model save method after an object's state changes and has been saved. The code looks something like this: class Foo(models.Model): name = models.CharField(max_length=20) ... def save(self, force_insert=False, force_update=False, *args, **kwargs): run_state_machine = kwargs.pop('run_state_machine', True) super(Object, self).save(*args, **kwargs) if run_state_machine: object_state_machine(object=self) def object_state_machine(object) if object.state == 'bar': object.name = 'jerry' object.save(run_state_machine=False) elif ... When I save an object from the Django Admin client, which then runs the state machine which potentially changes the attribute of the object (such as the name) as shown below, the new value isn't getting saved to the database. I have debugged the issue and if I check the value of object.name in save before super.save is called, its value is the proper value (jerry in the case below), however when I check my database after the code finishes running, the name hasn't updated. I've looked into the Django save code a bit but I'm having trouble seeing which part of the model object is used to update the database. It does seem that it's something other than object.name. Does anyone see what I'm doing wrong or … -
Django Rest Framework returns bad request when POSTED a file by filepond on React
I have a react app, that uses filepond. Filepond accepts a file, and POSTs it to the server using the following custom header: const filepondServer = { url: `${apiRoot}expenses/receipt_upload`, process: { headers: { Authorization: `Token ${this.props.auth.token}` } } }; This goes to a django rest framework view: class ExpenseReceiptUploadView(APIView): permission_classes = [permissions.IsAuthenticated, HasMetis] parser_classes = (FileUploadParser,) def post(self, request): receipt = request.data["file"] return Response(status=status.HTTP_201_CREATED) (I know it needs fleshing out for errors etc, but that will come once it works) This returns a 400 error, with no further details. If I remove the receipt = request.data["file"] line, it returns a 201, and the server doesn't complain. To debug this, I tried printing request - this works fine, but request.data results in a 400, as does request.FILES. The error is very terse, it just says: 2018-12-21 00:01:35,850 [middlewares 70] INFO: {"method": "POST", "path": "/api/v1/operations/expenses/receipt_upload", "user": "Alex", "user_id": 27192835, "device_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36", "request_post_body": {"filepond": "{}"}} 2018-12-21 00:01:35,851 [log 228] WARNING: Bad Request: /api/v1/operations/expenses/receipt_upload [21/Dec/2018 00:01:35] "POST /api/v1/operations/expenses/receipt_upload HTTP/1.1" 400 0 -
Django interview questions?
What are commonly asked Django and python interview questions? I have interview coming up next week. I am not sure for Djanog are the going to have whiteboard interview? any suggestion please -
Django Simple History, need a queryset to sort changes to model by date?
I'm creating a web app that will manage inventory that is placed in boxes. I have installed simple history in Django. Im trying to write a queryset that returns changes to a boxes contents and orders this data by the date in which this change of content occurred At the moment I have in my views.py box_content_history = Box.history.all().order_by('-history_date') In my HTML: <table id="table_id" class="display"> <thead> <tr> <th>Box</th> <th>Content Changes</th> <th>Date of change</th> </tr> </thead> <tbody> {% for item in box_content_history %} <tr> <td>{{ item.box_ref }}</td> <td>{{ item.box_contents }}</td> <td>{{ item.history_date }}</td> </tr> {% endfor %} </tbody> </table> This displays the box alongside its contents and also the date it was changed. However, its still not ordering the results by this date. Is there something I can do to change this? Thank you very much in advance. -
Django InlineFormSet generate an extra form even when populating with data
I have three inline form sets that are creating using the same model. My use case is a user has submitted a form and is going back to edit that form. If a user has not submitted any data for that form set, then an extra empty field is displayed. But, if a user has submitted data for that form set, only the data is displayed with no extra field. I would love for the extra field to show, as it gives the user (and me) an easy way for a user to add a value to that form set. My form set is set to have one extra, but as I mention above, this only seems to work if there is no instance data to be loaded in that form set. I have noticed that when there is no data, the initial forms is 0, but the total forms is 1. But when there is data the initial forms is X and the total forms is also X. I would like total forms = initial forms + 1. I assumed extra would do this, but it does not. -
validate datetime input uniqueness in CreateView form
I have this model, and what I need is the time to be unique as it's a Reservation, so when I create a new reservation, how can I check if that time is already picked. models.py class Reserva(models.Model): horario = models.DateTimeField(auto_now_add=False, auto_now=False) cancha = models.ForeignKey('Cancha', on_delete=models.CASCADE) lote = models.IntegerField() views.py class ReservasCreateView(generic.edit.CreateView): model = Reserva template_name = 'reservar.html' fields = ['horario', 'cancha', 'lote'] And another doubt I have, if I want to change some input types in the form, should I keep the default CreateView and modify it over the view, or create a custom form in forms.py and pass it as form_class. What's the recomendation? Thanks -
Passing items to django-oscars basket using a custom template - Getting 'str' object has no attribute 'is_parent' error
I am using django-oscar as the backbone of an ecommerce website, although I am using it as a bare minimum. I am using a completely custom html template that has been modified to work with django oscar, and extended the catalogue app to have additional fields in the products table. Everything is mostly working at the moment, as far as displaying and browsing products. This is the relevant code I have taken from django's basket app to add into my own templates: {% purchase_info_for_product request product as session %} {% basket_form request product as basket_form %} <form id="add_to_basket_form" action="{% url 'basket:add' pk=product.pk %}" method="post" class="add-to-basket"> {% csrf_token %} {% include "partials/form_fields.html" with form=basket_form %} <button type="submit" class="btn btn-lg btn-primary btn-add-to-basket" value="{% trans "Add to basket" %}" data-loading-text="{% trans 'Adding...' %}">{% trans "Add to basket" %}</button> </form> I have not been able to troubleshoot why this error is happening. How can I troubleshoot this and allow products to be added to django-oscars basket using my custom template? -
How should I set up a user creation form that allows managers to create accounts for employees?
So I have extended my user model with a OneToOneField. My goal is to allow a Manager type user, create users for their employee's. models.py : class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) brewery = models.ForeignKey(Brewery, models.DO_NOTHING) phone_number = models.CharField(max_length=20) phone_carrier = models.CharField(max_length=80) role = models.CharField(max_length=60) class Meta: managed = True @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.customer.save() forms.py : class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ('brewery', 'phone_number', 'phone_carrier', 'role') views.py: @login_required def adminsite_register(request): if request.method == 'POST': user_form = UserRegisterForm(request.POST) cust_form = CustomerForm(request.POST) if user_form.is_valid() and cust_form.is_valid(): user_form.save() cust_form.save() messages.success(request, f'Account has been created! You can now log in.') return redirect('index') else: messages.error(request, f'Please correct the errors.') else: user_form = UserRegisterForm(request.POST) cust_form = CustomerForm(request.POST) return render(request, "AdminSite/adminControls.html", {'user_form': user_form, 'cust_form': cust_form}) One of the main issues I'm running into is populating the brewery foreign key field. For some reason anytime I submit the form with a brewery selected I get a "Cannot insert the value NULL into column 'brewery_id'" even though a brewery_id had been chosen. A user however is still … -
Why am I getting a Type Error for valid resposne tuple?
I'm getting this error "TypeError: The view function did not return a valid response tuple. The tuple must have the form (body, status, headers), (body, status), or (body, headers)." in Flask It seems to not like : return super(Application, self).__call__(environ, start_response) But why? File "/opt/realms-wiki-master/realms/init.py", line 63, in call return super(Application, self).call(environ, start_response) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 2309, in call return self.wsgi_app(environ, start_response) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 2295, in wsgi_app response = self.handle_exception(e) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1741, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request() File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1816, in full_dispatch_request return self.finalize_request(rv) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1831, in finalize_request response = self.make_response(rv) File "/opt/realms-wiki-master/realms/init.py", line 120, in make_response return super(Application, self).make_response(tuple(rv)) File "/usr/lib/python2.7/dist-packages/flask/app.py", line 1949, in make_response 'The view function did not return a valid response tuple.' class Application(Flask): def __call__(self, environ, start_response): path_info = environ.get('PATH_INFO') if path_info and len(path_info) > 1 and path_info.endswith('/'): environ['PATH_INFO'] = path_info[:-1] scheme = environ.get('HTTP_X_SCHEME') if scheme: environ['wsgi.url_scheme'] = scheme real_ip = environ.get('HTTP_X_REAL_IP') if real_ip: environ['REMOTE_ADDR'] = real_ip **return super(Application, self).__call__(environ, start_response)** -
Django-Rest-Framework: Can I create a viewset with two different methods with the same url_path, but different request methods?
Here's the viewset class MobileDeviceViewset(ModelViewSet): @action( methods=['post', 'put', 'patch'], url_path='token', detail=True, ) def update_token(self, request, *args, **kwargs) -> Response: ... @action( methods=['get'], url_path='token', detail=True, ) def get_token(self, request, *args, **kwargs) -> Response: ... So what I want to do here is have an endpoint /token/ that the app will send a GET request to to check if there is a token, and get it if there is. I also want to use that same /token/ endpoint to send an updated token to. What happens currently is that I get an error telling me that the POST/PATCH/PUT methods are not allowed on that endpoint, so it appears to only be recognizing the get_token method. The token object here is actually a ManyToMany through model called MobileDeviceUser, so I'm not just trying to update a field on the MobileDevice object. -
Wrapping a Django query set in a raw query or vice versa?
I'm thinking of using a raw query to quickly get around limitations with either my brain or the Django ORM, but I don't want to redevelop the infrastructure required to support the existing ORM code such as filters. Right now I'm stuck with two dead ends: Writing an inner raw query and reusing that like any other query set. Even though my raw query selects the correct columns, I can't filter on it: AttributeError: 'RawQuerySet' object has no attribute 'filter' This is corroborated by another answer, but I'm still hoping that that information is out of date. Getting the SQL and parameters from the query set and wrapping that in a raw query. It seems the raw SQL should be retrievable using queryset.query.get_compiler(DEFAULT_DB_ALIAS).as_sql() - how would I get the parameters as well (obviously without actually running the query)? -
How do I get reverse() to work in a function based view
I am new to Django, and I would like to try a FBV for an activity that doesn't require a Model. This will eventually implement a search with user-defined parameters and show the results in the template, but for now my template and views are essentially empty to show this problem. I'm using python 3.6 and Django 2.1.3. The tutorials go straight to CBV and I'm having a hard time getting good info on the FBV way. File: 'positivepets/picture_search.html': ------- {% extends 'positivepets/base.html' %} {% block body %} <p> You have reached the picture search page </p> {% endblock %} File: urls.py -------- app_name = 'positivepets' urlpatterns = [... url(r'^picture_search/$', views.misc_views.picture_search, name='picture_search'), ...] File: misc_views.py -------- def picture_search(request): return render(request, 'positivepets/picture_search.html') Problem This all works fine and renders the template picture_search.html. My problem is that I want to avoid hardcoding the template name. I thought this would work: def picture_search(request): return HttpResponseRedirect(reverse('positivepets:picture_search')) This takes the user to http://127.0.0.1:8000/positivepets/picture_search/ but produces a "too many redirects" error in chrome. I think I am just telling it to redirect to itself over and over. Question: Where do I specify that "picture_search.html" is the template that I want to render without hardcoding it in … -
Defaulting an updateview action in django form under a def post
Working with another coder on a project. His change stopped the UpdatView on some forms from saving edits. I realized why.... he defined a def post which works for the case he was working on, but needs an else action that just does a default update. I am not sure how to do this when he UpdatView isn't doing it all automagically. The code to the UpdateView: class ProviderUpdateView(UpdateView): model = Provider form_class = ProviderForm provider_form_class = ProviderForm provider_term_form_class = ProviderTermForm template_name = 'ipaswdb/provider/provider_form.html' success_url = '/ipaswdb/provider/' def get_context_data(self, **kwargs): context = super(ProviderUpdateView, self).get_context_data(**kwargs) provider = context['object'] context['provider_id'] = provider.id prov = Provider.objects.get(pk=provider.id) #print "provider: ", #print prov #print "provider terminated: ", #print prov.is_terminated if prov.is_terminated: provider_form = ProviderFormView(instance=prov) context['readonly'] = True else: print("NOT TERMINATED SO LETS DO THIS") provider_form = ProviderForm(instance=prov) context['readonly'] = False context['provider_form'] = provider_form provider_term_form = ProviderTermForm() context['provider_term_form'] = provider_term_form ### Get the list of GroupLocations, but remove the current one this provider is associated with ### I just need the grouplocation id and the name #grplocs = GroupLocationProvider.objects.filter( return context def post(self, request, *args, **kwargs): #print self.request.POST.keys() #print self.request.POST.values() print("Posting...") if self.request.POST.has_key('terminate'): provider = Provider.objects.get(pk=kwargs['pk']) form = ProviderTermForm(request.POST) if form.is_valid(): print "Terminating Provider: ", print … -
Get queryset for a ListView on a boolean field
I can't understand why this code doesn't work. I have a model called CustomUser with a BooleanField field called expert. I want to filter the users to include users where expert = True. I've tried self.expert, user___expert and customuser__expert in place of "expert" and none of these worked. views.py: from django.shortcuts import render from django.views.generic import TemplateView, ListView from users.models import CustomUser class BrowseView(ListView): model = CustomUser template = 'expert_list.html' def get_queryset(self): experts = CustomUser.objects.filter(expert == True) return experts models.py: class CustomUser(AbstractUser): objects = CustomUserManager() position = models.CharField(max_length =50, null=True, default='') bio = models.CharField(max_length=300, null=True, default='') expert = models.BooleanField(blank=True, default=False) -
Django Admin: Saving objects in state machine code
I've built an api that has a state machine built around a bookings model. Meaning as a booking changes between states, different blocks of code are run by the state machine. The state machine is triggered in the booking object's save method. There are certain instances in the state machine where the booking object can be updated, which then triggers on save a second time (I do have checks to prevent the state machine from recursive behavior). All works as expected when I move through the state machine with any client I've tested it against except Django admin. When I change states with Django Admin, the code blocks run as expected in all cases except when a booking is updated (and saved) within the state machine. In these instances, the object updates come through in on save, however they do not get saved to the database. I'm wondering if this is some sort of known issue with Django Admin or I may have some problem in my code. I can obviously provide code as needed, but being it works with other clients I'm wondering if the issue isn't with Django Admin. Any ideas? -
Python script communicate via websockets to Django Channels
Looking for some guidance or advice. I have Django channels set up on my webserver that allows two users to chat between each other using redis and websockets. How do I setup a standalone python script, so that it can communicate and take commands via websocket messages sent by a user in Django. The goal is to have this standalone python script be controlled via a Django channels websockets. The python script runs a physical motor, so some example functions would be Start() and Stop(). -
Django admin model not update in admin
I use django admin to add data, i run makemigrations and migrate on my code but the Choice model won't update and i cant see the Choice model in admin. Where is my mistake? model.py: class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text