Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom token generation with Django rest framework
I am currently working on building an API for an uni project. I am facing a problem with generating an auth token in a custom way. Let me explain: I am supposed to receive a POST request in an endpoint with the following: { "university_id": 1, "coords":{ "latitude": 0.0, "longitude": 0.0 } } The idea is that, given the university_id and the coords, The backend validates it (checks if the coordinates are inside the valid area) and then, returns a token like so: { "token": asdfsagag23214, } As you can see, there're no login credentials involved, so my guess was that I would need to create a custom token. I looked up Django REST Framework documentation, and came up with something like this for my token model: class AuthToken(models.Model): key = models.CharField(verbose_name='Key', max_length=40, primary_key=True) created = models.DateTimeField( verbose_name='Creation date', auto_now_add=True) class Meta: verbose_name = 'Token' verbose_name_plural = 'Tokens' def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super().save(*args, **kwargs) def generate_key(self): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key and then, it's serializer: class AuthTokenSerializer(serializers.Serializer): class Meta: model = AuthToken fields = ('key', 'created', ) def to_internal_value(self, data): university = data.get('university') coords = data.get('coords') if not university: raise serializers.ValidationError({ 'university': … -
How to autofill variable with foreign key in django form?
In short: I want to autofill form's foreign variable: TL;DR I have a model: from django.db import models from django.urls import reverse # Create your models here. class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) def __str__(self): return self.name def get_absolute_url(self): return reverse('basic:detail', kwargs={'pk': self.pk}) class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School, on_delete=models.CASCADE, related_name='students') def __str__(self): return self.name def get_absolute_url(self): return reverse('basic:detail', kwargs={'pk': self.school.pk}) and url.py: urlpatterns = [ path('', views.Index.as_view(), name='index'), path('list/', views.SchoolListView.as_view(), name='list'), path('<int:pk>/', views.SchoolDetailView.as_view(), name='detail'), path('create/', views.SchoolCreateView.as_view(), name='create'), path('update/<int:pk>/', views.SchoolUpdateView.as_view(), name='update'), path('delete/<int:pk>/', views.SchoolDeleteView.as_view(), name='delete'), path('student/create/', views.StudentCreateView.as_view(), name='creates'), path('student/create/<int:pk>', views.StudentCreateView.as_view(), name='createspk'), path('student/update/<int:pk>/', views.StudentUpdateView.as_view(), name='updates'), path('student/delete/<int:pk>/', views.StudentDeleteView.as_view(), name='deletes'), ] and i am using CBV: class StudentCreateView(CreateView): try: print("*******") print(pk) except: pass model = Student fields = ["name", "age", 'school'] I added a link to create student in school detail as shown below: When I click create new with pk, I am passing pk of School and I go to: As you can see School field is dropdown with nothing selected, I would like to make that the school default value to be the school from where it is called, in this case xavier school for gifted childrens. My form code is: {% … -
Django get url parameter into form_valid
I have a url of the form: path('makeoffer/<listing_id>', OfferCreateView.as_view(), name="CreateOfferview"), This view is a form, with a couple of parameters. The listing_id needs to be saved as part of the Offer object, and is not user-editable. I essentially want to do this: def form_valid(self, form): form.instance.user = self.request.user form.instance.datetime = dt.now() form.instance.listing_id = listing_id #(from the url) How do I access the parameter from inside the form_valid function? I've tried get_context_data, but the only way I could see to do it would be for the get_context_data to pass it to the view, and then have the view pass it back to the form, which seems a bit hacky. -
Associate one foreign key with two different models in django
I have to associate foreign keys that can point to two different tables. Following are the solutions I have found online - Create a model and make it the parent class of the models you want to use as foreign keys. Django - Foreign key referencing one of two tables depending on its content I am a bit wary of this solution since it will create another table which I don’t want. For accessing values I will have to do unnecessary joins which I am not inclined to do. The second option that I found is to create two columns and the have another column which tells which is set. https://www.reddit.com/r/django/comments/zk6zv/creating_a_task_model_with_a_foreign_key_to_two/c65db4y This doesn’t seem very clean since we are adding one extra column. Ideally I would want one column which would contain the type and other that will have the foreign key of one of the models. Is there any way to do this? -
Python 2 -> 3 Django migration causes field parameter type change
We are transitioning a Django project from Django 1.8 -> 2.1 and Python 2.7 -> 3.6. In the old project version, there are Django models that looked like this, for example: # models.py from django.db import models class RowStatusModel(models.Model): active = models.BooleanField(default=True, db_column='is_active') # ... class Meta: abstract = True Notice that from __future__ import unicode_literals is not used in this module. That means that db_column is a Python 2 str, corresponding to bytes in Python 3. The initial migration, 0001_initial.py, looks like this: # 0001_initial.py operations = [ # ... ('row_ef', models.BooleanField(default=True, db_column=b'is_active') # ... ] Notice the byte-literal b'is_active, which I suppose was done by Django in the interest of being more explicit, but am not sure. Now after transitioning most of the codebase with 2to3 and running makemigrations, Python 3 treats a string literal as what would be the unicode type in Python 2, and consequently generates a migration where the db_column is a string literal, for every single model that inherits from RowStatusModel: # migrations/0023_auto_20180827_1955.py migrations.AlterField( # ... field=models.BooleanField(default=True, db_column='is_active') ), # ... What effect, if any, will this have on the database side when ./manage.py migrate is ran? Is the "change" purely on the Python … -
I'm trying to create a Settings Model for my api in Django. Custom File uploading is what tricking me
I have 3 fields in my model. below is the code. Model.py class Settings(models.Model): typeOptions = ( ('txt', 'text'), ('img', 'image'), ('json', 'json'), ) title = models.CharField(max_length=80) type = models.CharField(max_length=5, choices=typeOptions, default='txt') value = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, null=True, editable=False, on_delete=models.SET_NULL, related_name='%(class)s_created') updated_by = models.ForeignKey(User, null=True, editable=False, on_delete=models.SET_NULL, related_name='%(class)s_updated') class Meta: verbose_name_plural = 'Settings' verbose_name = 'Setting' def __str__(self): return self.title as you see I've 3 types for my type field i can save text and json directly in my database as my value is a text filed but i want a custom file handler so i can see if type of the post is image than i need to upload the file and save path to database. I'll be using it just for API so i'm not practically concerned about Django admin. I hope someone will be able to help me. I need to work this Django Rest framework so when i send a post request it manage the data. -
How to write functions/definitions such that to render in HTML templates Django?
How do i write these type of functions in django template or in views.py so that I can apply it in my html template? in views.py def my_func(request): data = My_model.objects.filter(emp_id = request.user.username) for x in data: if(x.leave == 'earned_leave'): el += el+1 #I want to declare a local variable called 'el' and thereby increase it each time when it is called return render(request, "template.html",{el}) I know el isn't a dictionary but what i put there? urls.py urlpatterns = { path('status/', views.my_func, name = 'sick'), } Basically, this is a function that works on employee attendance, type of leaves etc. in the template i want to have as {{el}} #this should fetch the value directly to the template -
Terrible Django Admin Performance
I am developing a Django project, which already got plenty of real world data so I can see its performance. The performances of few DjangoAdmin lists are just terrible. I have one admin list, lets call it devices. In that list I am fetching additional informations for each row, those fields are related from other tables and connected via FK/PK/M2N. List contains about 500 records and loading of that screen takes, according to django-debug-toolbar, around 6.5 seconds, which is unbearable. This admin class @admin.register(Device) class DeviceAdmin(admin.ModelAdmin): list_select_related = True list_display = ('id', 'name', 'project', 'location', 'machine', 'type', 'last_maintenance_log') inlines = [CommentInline, TestLogInline] def project(self, obj): try: return Device.objects.get(pk=obj.pk).machine.location.project.project_name except AttributeError: return '-' def location(self, obj): try: return Device.objects.get(pk=obj.pk).machine.location.name except AttributeError: return '-' def last_maintenance_log(self, obj): try: log = AdminLog.objects.filter(object_id=obj.pk).latest('time') return '{} | {}'.format(log.time.strftime("%d/%m/%Y, %-I:%M %p"), log.title) except AttributeError: return '-' All Machine, Location and Project are tables in database. After looking into queries in django-debug-toolbar I discovered something terrible. That screen required 287 sql queries ! Yes, over two hundreds! Is there anything I can do to reduce this time to something reasonable? -
New user creation in test case
I am trying to create a new user in django rest framework test case in order to be able to create a post action with the following code: from django.contrib.auth.models import User user = User.objects.create_user('username', 'Pas$w0rd') user = authenticate(username='username', password='Pas$w0rd') client = APIClient() client.force_authenticate(user=user) r = client.post('/api/v1/event/', {'name': 'testevent'}, format='json') Getting the following error: user = User.objects.create_user('username', 'Pas$w0rd') File "/opt/dev/wgptx/venv/lib/python2.7/site-packages/django/db/models/manager.py", line 277, in __get__ self.model._meta.swapped, AttributeError: Manager isn't available; 'auth.User' has been swapped for 'account.User' Any help please ? -
Django Rest Framework return empty list in results randomly, but count still correct
When I'm trying to use custom filter it's working all the time in local development, but when we deploy to Production (Docker Swarm) We found an issue that sometime the API response is return empty results randomly, but the count is correct. Below is the example results from the API API Response { 'count': 1, 'next': 'http://localhost:8000/api/somethings/?email=test%40example.com&limit=0&offset=0', 'previous': None, 'results': [] } Right now we need to restart a uwsgi service (By restarting docker swarm for this service) and the problem is fixed for a moment and randomly happen again. Here is our DRF view class SomeView(ListCreateAPIView): queryset = SomeModel.objects.all() serializer_class = SomeModelSerializer filter_backends = (OrderingFilter, DjangoFilterBackend) filter_class = CustomFilter ordering = ('id',) def list(self, request, *args, **kwargs): if request.GET.get('all', None): # Do something serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) else: return super(SomeView, self).list(self, request, *args, **kwargs) Here is our CustomFilter from django_filters.rest_framework.filters import CharFilter import rest_framework_filters as filters class CustomFilter(filters.FilterSet): json_field_separator = '___' json_field_is = CharFilter(name='json_field', method='filter_json_field') json_field_is_not = CharFilter(name='json_field', method='exclude_json_field') def split_lookup_field(self, value): return dict(field.split(':') for field in value.split(self.json_field_separator)) def filter_json_field(self, queryset, name, value): try: lookup_field = self.split_lookup_field(value) return queryset.filter(**lookup_field) except (ValueError, FieldError): return queryset.none() def exclude_json_field(self, queryset, name, value): try: lookup_field = self.split_lookup_field(value) except (ValueError, FieldError): return … -
How can i add a user to a query set of users
I was getting all the users of following in which all user present except the logged-in one. def FeedListView(request): my_users=request.user.following.all() my_users.append(request.user) print(my_users) query=FeedDetail.objects.filter(user__in=my_users) return render(request,'feed/feed_list.html',{'objects':query}) I can't append the query list but for query i also want it to filter for requested user thatare not present in my_users Thanks -
What are common technique, to ensure code logic in TemplateView's get_context_data being executed once?
Currently, I have the following payment button. <a href="https://localhost/subscribe/?payload_nonce=token123">PAY NOW</a> When user click on the link, here's what happens behind the scene. Get token input from user. Payment gateway processes the received token, and return success/fail result. Display success/fail result to user. What I wish is, when user click on refresh button in browser, step 1 & step 2 will be skipped. We don't want user makes duplicated payment. But, only displayed previous gateway success/fail result. Here's the TemplateView code. class SubscribeView(TemplateView): template_name = 'subscribe.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(SubscribeView, self).get_context_data(**kwargs) # Step 1: Get token input from user # payload_nonce = self.request.GET.get('payload_nonce') # Step 2: Payment gateway processes the # received token, and return success/fail result. ... ... ############################## # Submit it to payment gateway ############################## ... ... # Step 3: Display success/fail result to user. # context['is_success'] = result.is_success context['message'] = result.message return context May I know, what are common technique, to ensure code logic in TemplateView's get_context_data being executed once? -
how to convert mongodb query to sql query
Here is my sql query: select count(id) from bandwidth_log where studio_id=8130 group by country Here is my mongo query: ( [ { "$match": { "studio_id": studio_id } }, {"$group" : {"_id":"$country", "view_count":{"$sum":1}}}, {"$sort": {"_id": 1 }} ] ) I am expecting the translation query for my above sql to mongodb query is like this. and it working fine in my mongo shell. but its coming emplty data while working with python. wheather records are available in database. I have requirement to write mongo query.. -
Django trying to access the site results in connection-refused
I am trying to access my site from my phone. Both my laptop and phone connected to the same wifi network. I tried to access the website with Postman and got a successful response. However when I try to access the site from my phone I get ERR_CONNECTION_REFUSED. What can be the reason for this? I use this test url that I know works: http://127.0.0.1:8000/policies/myModels_asJson -
select or fetchall not working - django
i use the select sqlite3 statement to get info. from django db (default db) p=connection.cursor().execute("SELECT * FROM webapp_information WHERE dat BETWEEN date('now', 'start of day') AND date('now', 'localtime');") a=p.fetchall() for i in a: print(i) i select the dat(date field) from a day i checked the admin panel the date are stored.. but it returns nothing i tried in diffetent way.. In [206]: p=connection.cursor().execute("SELECT * FROM webapp_information WHERE dat='2018-08-28';") but it returns a empty list the date are stored in the db.. what to do..thanks -
How to add a datepicker into Django ModelFrom?
These are my scripts - models.py from django.db import models class Leave(models.Model): ... from_date = models.DateField() to_date = models.DateField() def __str__(self): return self.name I wanted to have datepickers for the above DateField(s). This is my form template:- {% extends "base.html" %} {% block content %} <div class="container"> <h3> Fill out the form please! </h3> <h4> <form action="." role="form", method="POST"> {% csrf_token %} {{ form.as_p }} <button type = "submit">Submit</button> </form> </h4> </div> {% endblock %} So far, what i have done - I have included this in my base.html. <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script> <script> $(document).ready(function() { $('.datepicker').datepicker(); }); </script> In my forms.py as I'm using ModelForms, I have included this code - class LeaveRequestForm(ModelForm): class Meta: fields = ("from_date", "to_date") model = Leave widgets = { 'from_date' : DateInput(attrs={'class': 'datepicker', 'id': 'data_input'}), 'to_date' : DateInput(attrs={'class': 'datepicker', 'id': 'data_input'}), } But no datepicker is being reflected in my html template. I have read many other question related to this but couldn't understand. Hope, anyone explains me in detail. -
django smart select not working in admin
I am using python 3.6 with django 2.1 version. Already I have install smart select library. But when I am trying use my admin side model form it's showing java script error. Uncaught ReferenceError: chainedfk is not defined at initItem (bindfields.js:12) at HTMLSelectElement.<anonymous> (bindfields.js:31) at Function.each (jquery.min.js:2) at HTMLDocument.<anonymous> (bindfields.js:30) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at Function.ready (jquery.min.js:2) at HTMLDocument.J (jquery.min.js:2) -
Django "ajax-CRUD-tutorial", "NoReverseMatch" on update customer
So I have been working on this ajax CRUD tutorial from Simple is better than complex: How to Implement CRUD Using Ajax and Json Event though I can get the "create" part of the CRUD working with ajax, I get stuck at the "update part". To update data for a customer I need to retrieve the "customer.id" and pass it to the url. In the tutorial described above we use the action of the form with an argument for the book.id, or in my case customer.id. When I use a direct customer id, for example #72, the view works ok but when I try to use form.instance.pk, I get a NoReverseMatch error. Reverse for 'customer_update_modal' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P<pk>\\d+)/update/$'] How should i put the customer.id into the argument to get the wanted result? partial_customer_update.html <form class="form-on-card--modal modal-trigger js-customer-update-form" action="{% url 'customer_update_modal' form.instance.pk %}" method="POST" novalidate> views.py def save_customer_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True customers = Customer.objects.all()[:10] data['html_show_all_customers'] = render_to_string('includes/partial_customer_list.html', {'customer_list': customers} ) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) return JsonResponse(data) def customer_create(request):# Function based view to create a … -
How to create tree list view in Django app?
I am creating a web app using Django in which I have 2 plugins that load json and html files. The data is loaded in a model that I created. Here is the model: from django.db import models class Node: def __init__(self, identifier, name, attributes): self._identifier = identifier self._name = name self._marked = False if attributes is None: self._attributes = {} else: self._attributes = attributes self._neighbour_nodes = [] def identifier(self): return self._identifier def name(self): return self._name def marked(self): return self._marked def attributes(self): return self._attributes def attribute(self, attribute): return self._attributes.get(attribute) def neighbour_nodes(self): return self._neighbour_nodes def set_attribute(self, name, value): self._attributes[name] = value def add_neighbour_node(self, neighbour_node): if neighbour_node != self._identifier and neighbour_node not in self._neighbour_nodes: self._neighbour_nodes.append(neighbour_node) def __str__(self): return "Objekat " + self._name + " " + str(self.identifier) + " " Class graph: class Graph: def __init__(self, is_tree=False): self._nodes = {} self._is_tree = is_tree self._root = None self._path = None def set_path(self, path): self._path = path def get_path(self): if self._path is not None: return self._path def set_root(self, root): if self._is_tree: self._root = root def get_root(self): if self._is_tree: return self._root def get_edges_number(self): numberOfEdges = 0 for node in self._nodes.values(): numberOfEdges += len(node.neighbour_nodes()) return numberOfEdges def is_tree(self): return self.is_tree def get_nodes(self): return self._nodes def add_node(self, … -
Django forms how to get cleaned_data from fields
Im creating simple dynamic form fields that user can add their form fields and all fields are related to category model. I want that when user select category named car then show them related fields to that car. my structure: class Category: name = ... class Field: label = ... category = ForeignKey(Category) class FieldValue: value = ... field = ForeignKey(Field) My problem is how can I generate my form and how to retrieve data from form.cleaned_data and so I can add records to FieldValue model. I created a form and its working fine for rendering using __init__. And I want to retrieve data from rendered form fields. my form: class CategoryFieldsForm(forms.Form): def __init__(self, category_id, *args, **kwargs): super(CategoryFieldsForm, self).__init__(*args, **kwargs) fields = Field.objects.filter(category_id=category_id) for i in range(1, len(fields)): for field in fields: self.fields[field.slug] = forms.CharField() def clean(self): # how can i validate def save(self): print(self.cleaned_data) # how can i save fields my view: def some_create_view(request, category_id): if request.method == 'POST': form = CategoryFieldsForm(category_id) form.save() form = CategoryFieldsForm(category_id) return render(request, 'create.html', {'form': form}) When I submit my form CategoryFieldsForm object has no attribute cleaned_data is showing. -
How to add a foreign key from multiple options available in model for that key in django?
models.py class Currency(models.Model): currency_name = models.CharField(max_length=250) class Address(models.Model): user = models.ForeignKey(settings.common.AUTH_USER_MODEL, on_delete=models.CASCADE) currency_names = models.ForeignKey(Currency, on_delete=models.CASCADE) zebpay = models.CharField(max_length=250, blank=True, null=True) This is the model that I have for adding an address of an exchange. Every address will be saved in respective exchanges's form field. There are multiple currencies like bitcoin, ethereum, etc. When a user clicks on bitcoin tab, exchanges corresponding to it will be show where in form field address can be added and saved. Similarly for ethereum and others. After adding the address and clicking the save button, added address will be shown to the user. On admin panel, when admin clicks on an address it will show 3 things mainly :- The user it belongs to The currency it is related to What exchange it is I am able to do 1 (because user is already logged in) and 3 (address added in form field) but cannot add exchange to the saved address. views.py class ZebpayView(TemplateView): template_name = 'currencies/addresses.html' def get(self, request): form = ZebpayForm() addresses = Address.objects.all().order_by('-addition_date') users = User.objects.exclude(id=request.user.id) friend = Friends.objects.all().first() friends = friend.users.all() context = {'form': form, 'addresses': addresses, 'users': users, 'friends': friends} return render(request, self.template_name, context) def post(self, request): form = … -
kombu utils objects py line 42 in __ get __ return obj __ dict __[ self __ name __] keyerror data
settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Makassar' # Other Celery settings CELERY_BEAT_SCHEDULE = { 'add_task': { 'add_task': 'data_loader.tasks.add_task', 'schedule': crontab(minute=55, hour=13), } # 'task-number-two': { # 'task': 'data_loader.tasks.demo', # 'schedule': crontab(minute=2, hour='18'), # } } celery.py .............. from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'resolution_validator.settings') app = Celery('resolution_validator') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py ............ from __future__ import absolute_import, unicode_literals from celery.task import task @task() def add_task(): print("hello world") a = 10 return True init.py ............... from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] I am also getting "RecursionError: maximum recursion depth exceeded" with the KeyError. I am using … -
{OverflowError} Python int too large to convert to C long
Getting the below error {OverflowError}Python int too large to convert to C long when running. EN_Users.objects.get(id=1) # EN_User --> Model | id--> primary key Any help to fix this issue is highly appreciated. -
Set number of rounds in a tournament conditionally (OOP, python)
Part of the reason why I'm asking this question is because I don't know what the proper way to ask this question is. I'm trying to create a calculator for Swiss-style tournaments in Django. Tournaments may have different numbers of rounds, so I need to be able to access the score for each round. Here is my model for a single participant in the tournament: class Speaker(models.Model): speaker = models.CharField(max_length = 32) team_name = models.ForeignKey(Team, on_delete = models.CASCADE) tournaName = models.CharField(max_length = 32) round1 = models.IntegerField() round2 = models.IntegerField() round3 = models.IntegerField() round4 = models.IntegerField() #what if I only wanted three rounds? or five? totalScores = models.IntegerField() def updateTotals(self): self.totalScores = self.round1 + self.round2 + self.round3 + self.round4 Basically, I want to be able to make as many or as little "round" variables as I want. Is there a way to do what I want or should I be rethinking how I'm structuring my models? -
How to set style on Django Filter 'Safe'
I have code like this. ... <p style="font-size: 1.3rem; margin-top: 1.5rem; border: solid 1px #eaeaea; padding: 2rem; background-color: #efefff;"> {{ object.content|safe}} </p> ... I expected it would set style on object.content. But what I got is the content went below styled tag <p> not inside it. Because object.content also has its tag <p>. So how do I set style using safe filter?