Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django tests with model mommy - issue with a model
I'm experiencing issues on creating fixtures for a particular model in a test class with Django and the DRF. I'm using model-mommy, but even creating a single instance for that model does not work: from rest_framework.test import APIRequestFactory, APITestCase from model_mommy import mommy from api.v1 import views from company.models.models import CompanyUserProfile, ManagerRelation, DynamicRelation User = get_user_model() class APIViewsTestCase(APITestCase): @classmethod def setUpTestData(cls): supervisory_id = "1337" emp_group_id = "119" prd_scope_id = "1334" user = mommy.make(User) setattr(cls, 'user', user) company_user_profile_1 = mommy.make(CompanyUserProfile) requestor = mommy.make( CompanyUserProfile, is_manager=True, supervisory_id=supervisory_id, emp_group_id=emp_group_id, prd_scope_id=prd_scope_id, user=user ) cls.user = user manager_relation = mommy.make( ManagerRelation, manager_id=requestor.id, mgr_type="Direct Mgr", _quantity=5 ) dynamic_relations = mommy.make( DynamicRelation,target_id=requestor.id, _quantity=5 ) def setUp(self) -> None: super().setUp() self.client.force_authenticate(user=self.user) def test_employee_view(self): CompanyUserProfile.objects.create( guid=uuid.uuid4(), csod_user_id='idcbijnccdocwocd', csod_username='djchbdcjnwdskjcn', id=3333 ) print('cup count:', CompanyUserProfile.objects.count()) print('user count:', User.objects.count()) print('m_rels count:', ManagerRelation.objects.count()) print('d_rels count:', DynamicRelation.objects.count()) rsp = self.client.get('/api/v1/employees/') self.assertEqual(rsp.status_code, HTTPStatus.OK) however CompanyUserProfile records are not created, both using mommy.make or CompanyUserProfile.objects.create: -- test run output Creating test database for alias 'default'... System check identified no issues (0 silenced). cup count: 0 user count: 1 m_rels count: 5 d_rels count: 5 Destroying test database for alias 'default'... CompanyUserProfile inherits from AbstractCornerstoneUserProfile (abstract base model), that's the main difference between this and the other … -
Getting a django queryset from a backward foreign key relationship with one distinct field
Using Django 1.8 I'm trying to get a queryset through the backward foreign key relationship where there is only one distinct value of one the fields in the source models. class Franchise(models.Model): ... class Title(models.Model): franchise = models.ForeignKey(Franchise, related_name='titles') genre = models.CharField(max_length=20) ... So in this example I would like to get a queryset of Franchise objects of which all Titles have the same genre. I can add methods to the Franchise model and generate a list of franchise id's obtain a queryset, but this is very slow. class Franchise(models.Model): ... def get_title_genres(self): self.titles.values_list('genre', flat=True).distinct() def is_single_genre(self): return len(self.get_title_genres()) == 1 franchise_ids = [ franchise.id for franchise Franchise.objects.all() if franchise.is_single_genre() ] queryset = Franchise.objects.filter(id__in=franchise_ids) Is there a more efficient way I can do this? -
How to get the related column value, Django
I've looked at various posts on this, but I'm still failing to get the contents of a related column. I have 2 tables related by a foreign key. I've added a related name - locations. # models.py class Container(models.Model): #like a friend container_id = models.AutoField(primary_key=True) container_name = models.CharField(max_length=50, blank=True, null=True) container_type = models.CharField(max_length=50, blank=True, null=True) location_id = models.ForeignKey(Location, db_column='location_id', on_delete = models.PROTECT, related_name = 'locations') icon_desc = models.ForeignKey(Icon, db_column='icon_desc', null=True, blank=True, default='Box',on_delete = models.PROTECT) samples = models.ManyToManyField('Sample', through='ContainerSamples') class Location(models.Model): location_id = models.AutoField(primary_key=True) store_id = models.ForeignKey(Storage, db_column='store_id', on_delete = models.PROTECT) icon_desc = models.ForeignKey(Icon, db_column='icon_desc', on_delete = models.PROTECT, null=True, blank=True) location_type = models.CharField(max_length=100, blank=True, null=True) location_name = models.CharField(max_length=100, blank=True, null=True) orderby = models.IntegerField(blank=True, null=True) My views returns container # views.py def allcontainer(request): allcontainer = Container.objects.all() return render(request, 'container/allcontainer.html', { 'container':allcontainer }) And in my template: {% for contents in container_contents %} <p>{{ contents.sample_id }}</p> <p>{{ contents.area_easting }}. {{ contents.area_northing }}. {{ contents.context_number }}. {{ contents.sample_number }}</p> I want to add the Locations, I've tried the following:.. <p>{{ contents.locations.location_name }}</p> {% end for %} Where am I going wrong? -
How to get all value from request.POST in intermediate pages of django admin action
As shown above, after press Export button, only "Django 1" returns through the print() command. Wondering hwo to get all three values from this kind of interactive? # admin.py def export(self, request, queryset): if "apply" in request.POST: queryset.update(status="exported") title = request.POST['title'] print(title, _selected_action) self.message_user(request, "Changed status on {} orders".format(queryset.count())) return HttpResponseRedirect(request.get_full_path()) context = admin.site.each_context(request) context.update({ 'data': queryset }) return render(request, 'admin/export.html', context=context) export.short_description = "export" <!-- export.html --> {% extends "admin/base_site.html" %} {% block content %} <form action="" method="POST"> {% csrf_token %} {% for d in data %} <p> {{ d.pk }}.{{ d }} <input type="text" name="title" value={{ d.title }} size="50" autofocus /> </p> <input type="hidden" name="_selected_action" value="{{ d.pk }}" /> {% endfor %} <input type="hidden" name="action" value="export" /> <input type="submit" name="apply" value="Export" /> </form> {% endblock %} -
Django OAuth Toolkit how to log the user out
I have set up Django OAuth Toolkit in my project where the authorization server is separate from the application server (i.e accounts.example.com and app.example.com). App server redirects to accounts server using authorize flow; the user inputs credentials to sign in to auth server, then auth server redirects the user back to application; so that the app can retrieve tokens. The above flow currently works as expected. If I do not click explicitly Log out the user and the application signs out (e.g session expires or browser cookies are cleared), the above flow will be performed again and there won't be a need for credentials because auth server still knows who is signed it. However, I am having trouble with explicitly logging the user out of the application. If a user explicitly clicks login, firstly, the token must be revoked and secondly, the auth server must sign out. What is the proper way to achieve this? As far as I am concerned, I won't be able to use Ajax to log out the user because the session must be destroyed in auth server. So, I have been thinking of redirecting the user to accounts.example.com/signout?token=${accessToken}&client_id=${clientID}. However, I am not sure if this … -
Render a dictionary with object list as values in django
I have a dictionary new: new = {'Delhi-Mumbai': [<Truckdb: Truckdb object (6)>], 'Doon-Gurgaon': [<Truckdb: Truckdb object (8)>, <Truckdb: Truckdb object (6)>]} I am not able to render the objects from TruckDb in templates this is what i tried in views.py return render(request, 'classroom/teachers/dispatcher_output.html',{'res':new}) this is my template: {% for k,v in res.items %} <h1>v value is </h1> {{ v.Name }} {% endfor %} I am not able to understand what I am doing wrong ? -
I need help creating a custom counter for items in my SQLite database
I am new to Python and Django and I am trying to count the number items(documents) in my SQLite database base on the status of the document, (canceled or not canceled). I have tried multiple ways to do this but, I cannot find one that works correctly for me. I have tried forloop.counter, .count(), and a few other ways that i found online. All I want to do is go through the database and have it tell me how many canceled procedures I have in the database. I am trying to display the results on a html page. Thanks. enter code here models.py class posts(models.Model): OPMnumber = models.CharField(max_length = 30) title = models.TextField() contacts = models.CharField(max_length = 50) dateLastReviewed = models.DateTimeField() reviewDue = models.DateTimeField() status = models.CharField(max_length = 20) assignedTo = models.CharField(max_length = 30) comments = models.TextField() views.py def opmStatistics(request): """ Return opmStatus page """ entries = posts.objects.all()#[:10] limits the number of entries displayed #opm_count = posts.objects.filter(posts.status=='Canceled').count() #return render_to_response('opmStatistics.html', {'posts' : opm_count}) return render_to_response('opmStatistics.html', {'posts' : entries}) My html code: <tr><td>Current Number of Active Accelerator Operations OPMs: </td> <td> {% for post in posts %} {% if post.status != "Canceled" %} {% with OPM_count=forloop.counter %} <!-- how to save final … -
Object of type CarCategory is not JSON serializable
Before you mark it as duplicate, please take a look, i have been looking at other samples but none is similar to mine, (as strange as it is). I have this code: # model class CarCategory(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name # model class Car(models.Model): id = models.CharField(max_length=255) number = models.CharField(max_length=255) description = models.CharField(max_length=1524) price = models.IntegerField() category = models.ForeignKey(CarCategory, on_delete=models.CASCADE, blank=True) # view def search(request): if 'search_filter' in request.GET: # set a hidden field (search_filter) so you know that you need to perform a search search_params = request.GET.dict() search_params.pop("search_filter") # for all search params which are not null, create a Q object # assuming that you provide the column name as search criteria. q_list = [Q(("{}__icontains".format(param), search_params[param])) for param in search_params if search_params[param] is not None] queryset = Car.objects.filter(reduce(operator.and_, q_list)) # combine Q object using & operation cars = [{ 'id': x.id, 'driven': x.driven, 'description': x.description, 'price': x.price, 'firstImage': x.carimage_set.first().image } for x in queryset ] return JsonResponse({'data': cars}) context = {'cars': Car.objects.all().order_by('price')} return render(request, 'cars/car_index.html', context) # error # Object of type CarCategory is not JSON serializable The search query works fine, i printed and it returns in the console with the correct data, but this … -
Django - update id of model referenced by a non-nullable foreign-key
I have a simple model. Let's say something similar to: Person(id-uuid, name-string) Dog(id-uuid, name-string, owner-ForeignKey(Person, null=False) I have an instance of both of them: p, d I want to change the id of the person p The problem is that I can't change the if of the person p because it is being reference by d, and I can't change the reference of d since it's not nullable. I don't think it matters, but I use either sqlite or postgres -
Cannot connect postgresql to django-project
пытаюсь подключить postgresql к проекту django, но при makemigrations создаётся файл db.sqlite3 thank you for any help DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mybase_db', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } -
Customized Interactive card bot
How to customize the style of interactive cards in hangout chat rooms. I want to increase the width of the cards. I have used like this : { "cards": [ { "header": { "title": "Pizza Bot Customer Support", "subtitle": "pizzabot@example.com", "imageUrl": "" }, "sections": [ { "widgets": [ { "keyValue": { "topLabel": "Order No.", "content": "12345" } } ] } ] } ] } See intrective Card bot images -
distinct method not working correctly in Django
I want to get distinct pair of quarter and year but following query is giving duplicate pairs DataValue.objects.values('period_quarter','period_year').distinct() output: [ { 'period_year': '2019', 'period_quarter': 'Q2' }, { 'period_year': '2019', 'period_quarter': 'Q2' }, { 'period_year': '2019', 'period_quarter': 'Q2' } ] -
'AppRegistryNotReady' error after Django Upgrade from 1.8 to 1.9 version
In our process of upgrading our Django project from 1.8 to 1.9 version, we removed all the deprecation warnings/errors according to Django-1.9 release notes. But, after updating the Django version to 1.9 in the project's virtual environment, we got the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. We have many installed apps in the project and using PostgreSQL-9.5 database. We know that the apps which have model classes in it, cause this error to occur. The above error even occured when connecting to the database using connection cursor: django.db.connection.cursor().execute() -
Heroku Python django bad request(400)
I wanted deploy my app on Heroku. After pushing on server and start open web page of my app, i get bad request (400). Link to app: "https://virtual-learning-log.herokuapp.com/" my ALLOWED_HOSTS = [".herokuapp.com", ".virtual-learning-log.herokuapp.com"] My DEBUG option is actually True. I tried to do with True/False and was the same. My procfile: web: gunicorn learning_log.wsgi --log-file - My wsgi.py: import os from django.core.wsgi import get_wsgi_application from dj_static import Cling os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') application = Cling(get_wsgi_application()) Logs from heroku: tate changed from starting to up 2019-05-09T11:35:24.900723+00:00 heroku[router]: at=info method=GET path="/admin" host=virtual-learning-log.herokuapp.com request_id=53ea1743-0422-45d7-840d-1fe1e855c79f fwd="83.26.219.46" dyno=web.1 connect=0ms service=82ms status=400 bytes=199 protocol=https 2019-05-09T11:35:24.899883+00:00 app[web.1]: 10.69.140.54 - - [09/May/2019:13:35:24 +0200] "GET /admin HTTP/1.1" 400 26 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 2019-05-09T11:35:25.188369+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=virtual-learning-log.herokuapp.com request_id=63dbc82d-628b-45c7-8317-931e5b4ac7e2 fwd="83.26.219.46" dyno=web.1 connect=0ms service=47ms status=400 bytes=199 protocol=https 2019-05-09T11:35:25.187500+00:00 app[web.1]: 10.69.140.54 - - [09/May/2019:13:35:25 +0200] "GET /favicon.ico HTTP/1.1" 400 26 "https://virtual-learning-log.herokuapp.com/admin" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 2019-05-09T11:35:27.753076+00:00 heroku[router]: at=info method=GET path="/" host=virtual-learning-log.herokuapp.com request_id=02862f51-65b1-4e16-ba35-0275a39f3bcf fwd="83.26.219.46" dyno=web.1 connect=0ms service=15ms status=400 bytes=199 protocol=https 2019-05-09T11:35:27.752324+00:00 app[web.1]: 10.69.140.54 - - [09/May/2019:13:35:27 +0200] "GET / HTTP/1.1" 400 26 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36" 2019-05-09T11:35:28.015809+00:00 … -
How to upload file to google drive without manually doing anything using python?
from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools from googleapiclient.http import MediaFileUpload,MediaIoBaseDownload import io # Setup the Drive v3 API SCOPES = 'https://www.googleapis.com/auth/drive' store = file.Storage('client_secrets.json') creds = None if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES) creds = tools.run_flow(flow, store) drive_service = build('drive', 'v3', http=creds.authorize(Http())) def uploadFile(): file_metadata = { 'name': 'new_json.json', 'mimeType': '*/*' } media = MediaFileUpload('/home/trigensoft/new_json.json', mimetype='*/*', resumable=True) file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute() print ('File ID: ' + file.get('id')) uploadFile() This code can also upload file to google drive, but during execution it takes to gmail login page. After selecting correct mail and giving permission to allow delete/create, etc or not, it add file to drive. I want upload file to drive without manually doing anything. Please help.. -
Annotating User objects with filtered Groups
I am trying to serialize user data in Django Rest Framework and I wish to only return selected groups that a user is a member of. Based off if the group name ends with _certified. I've looked at F expressions, and even Q objects but I can't seem to find an easy way to do this or if it's even possible. My expected result is { "User": { ... "Groups": ['role1_certified', 'role2_certified' ...] } } Groups should only contain groups that end in _certified -
Django filter manytomanyfield exclude objects that are related to another model
I have 2 models, File and Fileset: class File(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) class Fileset(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) files = models.ManyToManyField(Foo, related_name='fileset_files') I want to filter File objects that are not related to any other Fileset Problem Consider that I have File objects: File1 File2 File3 I have 2 Fileset objects: Fileset1 (is related to File1) Fileset2 (is related to File1, File2 & File3) When I try the query: File.objects .filter(fileset_files__fileset_name='Fileset2') # all files from Fileset2 .exclude(fileset_files=Fileset.objects.get(fileset_name='Fileset1')) # exclude the files that are in Fileset1 This returns File2 & File3 like I want. How do I make this work when I have, lets say 20 Filesets? How should I filter for Files that are in other Filesets when I have multiple Filesets? -
How to replace values in a dictionary with corresponding primary key values from a model in django?
I have a dictionary : a = {"'Delhi-Mumbai'": 6, "'Chicago-Washington'": [8,6]} I want to replace each of the value by an object with the same id of a model MyModel. I tried using for k,v in res.items(): v = get_object_or_404(MyModel, id=v) I want to pass the objects with the same ID as the values on a django template like so in my views function: return render(request, 'dispatcher_output.html',{'a':a}) -
Django: Signal fails to add user to group
After a user is created, I want to add the user to a group. To do this, I have setup a post-save signal. The signal fires, however the user is not added to the group. The signal does not return an error, it just fails to add the user. from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.db.models.signals import post_save from django.dispatch import receiver User = get_user_model() @receiver(post_save, sender=User) def add_to_reviewers(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='Test') instance.groups.add(group) -
Django: Model function is not returning proper value in template
have the bookingrecordsView view in which I fetch all reservations made by a user. I added a model function is_pending() that fetches a reservation instance, checks whether the date_to field has passed or not, and returns a string. The view that fetches the reservations: def bookingrecordsView(request): rsv = Reservation.objects.filter(user=request.user) return render(request, 'booking_history_page.html', {'rsv': rsv}) And the function that checks the date: class Reservation (models.Model): .... @property Def is_pending(self): if self.date_to < datetime.date.today(): return "Pending" else: return "Over"` This is my template snippet: {% for r in rsv %} <tr> <td>{{ r.id }}</td> <td>{{ r.date_from }} - {{ r.date_to }}</td> <td>{{ r.time_from }} - {{ r.time_to }}</td> <td>{{ r.chosen_vehicle }}</td> <td>{{ r.garage }}</td> <td>{{ r.destination }}</td> <td>{{ r.is_pending }}</td> </tr> {% endfor %}` Now, for all the bookings, even those passed months earlier, this status is always returning 'Pending'. How do I get the correct return value for every Reservation instance from is_pending() function and pass it accordingly to the template? -
Get a nullable datetime from django and convert it in golang
Here is the date that i send (in raw text) mode from a jsonified models.DateTimeField : 2019-05-07 16:49:47.351628+00:00 How i receive it in golang : package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "github.com/lib/pq" ) type DataLink struct { Created pq.NullTime `json:"created"` } type SendData struct { Name string `json:"Name"` } func main() { var reception = DataLink{} var sendData = SendData{} sendData.Name = "Melon" url := "http://127.0.0.1:8309/getLinks/" fmt.Println("URL:>", url) js, err := json.Marshal(sendData) req, err := http.NewRequest("POST", url, bytes.NewBuffer(js)) req.Header.Set("X-Custom-Header", "myvalue") req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() //fmt.Println("response Status:", resp.Status) //fmt.Println("response Headers:", resp.Header) body, _ := ioutil.ReadAll(resp.Body) //fmt.Println("response Body:", string(body)) err = json.Unmarshal(body, &reception) fmt.Println(reception.Created) } But when i print my object i have a : {0001-01-01 00:00:00 +0000 UTC false} How to convert ideally from a django time field or with string manipulation my date time to make it compatible with go and pq.NullTime ? Everything else works (bool, int, float , string) but not the date ... -
POST selection from dropdown/update database using Javascript/Django
I currently have the following template, which has a dropdown list for each row in a table. Anytime a selection from one of these dropdown's is selected/clicked, it should POST. However, I don't understand what I need to do in my View class to get it to send the data to the database. <div class="dropdown"> <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Change Status</button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <button onclick="status_update("In Session", {{a.patient_id}})" class="dropdown-item">In Session</button> <button onclick="status_update("Complete", {{a.patient_id}})" class="dropdown-item">Complete</button> <button onclick="status_update("Canceled", {{a.patient_id}})" class="dropdown-item">Canceled</button> </div> </div> </td> </div></tr>{% endfor %} </table> </div> </div> {% endblock body %} {% block script %} <script type="text/javascript"> function update_status(status, id) { var patient_pid = id; $.ajax({ type: "POST", url: "{% url 'dashboard' %}", data: {'patient_id': id, 'status': status, csrfmiddlewaretoken:'{{csrf_token}}'}, success: function() { $.ajax({ type: "POST", url: "{% url 'dashboard' %}", data: {'patient_id': id, 'status': status, csrfmiddlewaretoken:'{{csrf_token}}'} }); } }); } </script> The view which matches this template is defined as follows: class DashboardView(TemplateView): template_name = 'dashboard.html' def get_context_data(self, **kwargs): kwargs = super(DashboardView, self).get_context_data(**kwargs) # Hit the API using one of the endpoints just to prove that we can # If this works, then your oAuth setup is working correctly. # appointments = self.make_api_request() #get all the appointments/update … -
django: update field after drop down selection without javascript
I have a data table as a formset with several columns. One of the columns is a drop down field. I want to update the value of a field depending on the selected value of the drop down field and I would prefer a solution without using javascript. Is this possible in django? -
How to set login URL in Django Admin on session timeout?
I wrote a Django app which has an external authentication system reacheable at some URL (say, https://.../myproject/login). This is working well. However, when the session expires, the user gets redirected to the default login url which is https://.../myproject/admin). I'd like to change the behavior of the app so if the session expires, the user should be redirected to https://.../myproject/login and only use the /admin login when explicitly opened. Is there a built-in way to do this in Django? -
Allow only one user at a time to land on page
I'm building an app where users can navigate through pages of Treasure objects. Each treasure.html template has a Next button to reach the next available treasure. I want to allow only one user to land on a specific treasure page. Once the user reached the page, the Treasure instance is "owned" by that user (treasure.captured_by = user). Therefore, the Next button should return the page of a treasure that has never been captured. Unfortunately, when many users are connected, it happens sometimes that two users land on the same treasure page. How can this be? The button calls a view which does something like: def get_next_available_treasure(request, current_treasure_id): """Retrieve the next unclaimed treasure.""" treasure = Treasure.objects.filter( id__gt=current_treasure_id, # Only consider Treasures that have been stored later on the db captured_by__isnull=True ).order_by('id').first() return redirect('treasure-page', treasure_id=treasure.id) How can I fix the issue and have a sort of "lock" on the treasure page/instance?