Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Authenticating requests in Django test client
My API works when I test it using Postman (with the server running). For example: When I test using Django test client, I am able to log in, but not to authenticate a request. For example: headers = {'Authorization': 'Token ' + token} response = client.get('/api/v1/users/auth/user/', **headers) The response object contains: '_container': [b'{"detail":"Authentication credentials were not provided."}'] For some reason, the token ends up in the request, not in headers: 'request': {'Authorization': 'Token 665c371b1b894abba102cdbae8b35b613321791d', What am I missing? -
Reuse context in multiple views
I'm very new to Django and in my application I have a dynamic navbar on top. The context are passed in as context. Imagine it looks like this: <ul> {% for link in links %} <li><a href="{{ link }}"></a></li> {% endif %} </ul> The views may look like this: def nav_links(): # Display links to first 5 MyModel objects objects = MyModel.objects.all()[:5] return [o.get_absolute_url() for o in objects] def index(request): return render("request", "app/index.html", context={"links": nav_links()}) def page1(request) some_data = ... return render("request", "app/page1.html", context={"links": nav_links(), "data": some_data}) def page2(request) return render("request", "app/page2.html", context={"links": nav_links()}) ... Currently, I need to pass in links as context in each of the views. This is obviously bad design. Is there a way to pass in the same context for all views? -
Convert sql code to django orm self table and no foreignkey used
This is a part of sql query which i need to convert to django query using orm. Now the thing is that i don't need to use raw sql django way instead only django orm. As you all can see in the sql query it is left joining self table twice. Their is no foreignkey on self for columns. Model class PurchaseOrders(models.Model): id = models.AutoField(primary_key=True, unique=True) po_no = models.CharField(max_length=255) type = models.CharField(choices=TYPE_CHOICES, max_length=17) franchise = models.ForeignKey( 'franchise.Franchise', on_delete=models.DO_NOTHING, db_column='franchise_id' ) status = models.CharField(choices=STATUS_CHOICES, max_length=15) parent_po_id = models.IntegerField() ref_po_no = models.CharField(max_length=255, blank=True, null=True) is_deleted = models.BooleanField(default=False) class Meta: db_table = 'purchase_orders' Raw Sql Query: SELECT po.`po_no`, po.`type`, f.`gst_no`, po2.`po_no` as 'parent_po_no', po2.`type` as 'parent_po_type', refPo.`type` as 'ref_po_type', refPo.`po_amount` as 'ref_po_amt' INNER JOIN `franchise` f ON f.`franchise_id` = po.`franchise_id` LEFT JOIN `purchase_orders` po2 ON po2.`id` = po.`parent_po_id` LEFT JOIN `purchase_orders` refPo ON refPo.`po_no` = po.`ref_po_no` WHERE po.`id` = ? AND po.`is_deleted`=0 AND po.`status` <> 'rejected' "; -
Session handling with django-rest-framework
I'm building a django-rest-framework application in which a user should only be logged in 1 system at a time, I want the user to be able to login from another device as soon as he closes the site from the 1st device , what approach and Auth type will be appropriate for this task? -
Django allow only a one time form submission and create and save variable
I've various probem with my code: I'd like my user to be able to complete ony one time my form and then when they try to access again the page to receive the success message alert and not the form anymore. How can I achieve this? When the form is submitted I get two successufull alert msg and I'd like to have just one test_date field doesn't appear in my database at all. I'd like to calculate the age and not making the person input that and also to create and save in my databese a code based on the input user, but I'm keeing getting an error so I # that part of the code. Is it possible? Thank you alll! model class UserBio(models.Model): name = models.CharField(max_length=120) birthdate = models.DateField() age = models.CharField(max_length=2) phone = models.CharField(max_length=10) test_date = models.DateField(auto_now_add=True) height = models.CharField(max_length=3) weight = models.CharField(max_length=3) id = models.CharField(max_length=120) form class UserBio(forms.ModelForm): class Meta: model = UserBio fields = (name', 'phone', 'height', 'weight') views def add_bio(request): if request.method == "POST": form = UserBio(request.POST) if form.is_valid(): #age = datetime.now().year - self.birthdate.year #id = self.name + '_' self.height + '/' + self.weight + '_' self.phone form.save() messages.success(request, 'Form submission successful') else: form … -
Accessing host data modified by docker container
I am trying to use docker on my local system for development purposes. I am using Django Framework and with docker, I added some apps. docker exec -it CONTAINER_ID python3 manage.py startapp myapp This adds an app to my host as well. But it is readonly. How can I change the permission to make it executable and writable from my host as well? -
Django: ¿Is it better to load choices field dynamically or to create a Foreign Key model?
I have the case where I want a model to have a lot of choices and right now I dont have that information persisted in my database. This information is the link between the urls and the views related to them in my application. I was trying to override the ModelAdmin to show all of this choices loaded dynamically but surprisingly, for me, I couldn't do that because the model field choices are evaluated just once. That kept me wondering about if it's a good idea to load this choices right in the model dynamically. After that, I read from the django docs that choices are meant to be unvariable data. And this choices, because of it's conceptualization (url and view linked to it) are necessarily going to increase. So, my question is: ¿is there a good way to load the choices of a field in Django or should I just create a ForeignKey for this choices? -
Django unit testing authentication token not accepted
I've checked the DRF official documentation, have read the below posts and copy-pasted code from some answers to avoid any typo, but I still can't authenticate in my unit tests. I always get a 401 response code. I have a custom User model that just has a couple of none required fields so far. Can anyone see any logic issue, or error in the code? Could the issue originate from having a proper local DB and a testing DB and the authentication mixing both up somehow? Checked posts that did not solve the problem: DRF documentation SO post 1 SO post 2 SO post 3 So here's my code. Unit test from django.test.testcases import SimpleTestCase from django.urls import reverse, resolve from rest_framework import status from rest_framework.test import APITestCase from rest_framework.authtoken.models import Token from test_project.models.user import * from test_project.views import UserViewSet # from django.contrib.auth.models import User from test_project.models import * class UserAPIViewTests(APITestCase): def setUp(self) -> None: self.users_list_url = reverse('user-list') self.users_detail_url = reverse('user-detail', args=[1]) self.user =User.objects.create( username="admin", password="admin", email="test@necktie.com", first_name="test first name", last_name="test last name", is_superuser=True, is_staff=True, is_active=True ) self.token = Token.objects.create(user=user) self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.key) # The testing DB is automatically torn down, no implementation required for those tests def tearDown(self) … -
How to leave Django mode in VS Code
Have been following a Django tutorial and now I would like to 'quit' Django mode in VS Code. Any thoughts on how I could achieve that? See attached for clarification. Thanks! -
Django Admin ModelMultipleChoiceField Form Updation not working
Models.py class CustomUser(models.Model): username = models.CharField(max_length=20) ...<fields>.... firm = models.ForeignKey( 'Firm', null = True, blank = True, on_delete = models.Set_NULL, related_name = 'users' ) class Firm(models.Model): firm_name = models.CharField(max_length=20) .....<fields>..... Forms.py class FirmAdminForm(forms.ModelForm): users = forms.ModelMultipleChoiceField( widget = FilteredSelectMultiple('username', is_stacked=False), queryset=User.objects.exclude(is_staff=True).filter(firm=None), required=False, ) class Meta: model = Firm, fields = [...<other fields>, 'users'] def save(self, commit=True): # Save the provided password in hashed format firm = super().save(commit=False) users = self.cleaned_data['users'] firm.users.set(users) return firm admin.py class FirmAdmin(admin.ModelAdmin): form = FirmAdminform ...other codes ..... def render_change_form(self, request, context, add, change, form_url, obj): users = SalesToolUser.objects.exclude(is_staff=True).filter(partner_firm=None) if obj: partner_agents = obj.users.all() users = User.objects.exclude(is_staff=True).filter(Q(firm=None)|Q(firm=obj)) context['adminform'].form.fields['users'].initial = partner_agents context['adminform'].form.fields['users'].queryset = users return super().render_change_form(request, context, add=add, change=change, form_url=form_url, obj=obj) While I Crete a new firm, where I can add users without any error. But while I'm trying to update the firm, I selected default the users already infirm using initial with field(I am not sure it is a good method), I'm getting this error Select a valid choice. 3 is not one of the available choices . I think that my default selecting method is not good. Answer me if anyone knows working with this. -
How to Add/remove the event source of Full Calendar on checkboxes?
I am trying to add/remove the event sources of full Calendar depending on which checkbox This is my checkbox and calendar. <div class="x_content"> <div class="row"> {% for key,val in mydict.items %} <label class="checkbox-inline" style="margin: 5px;"> <input class="email_id" type="checkbox" id="{{key}}" value = "{{key}}">{{key}} </label> {% endfor %} </div> <div class="clearfix"></div> <br> <div id="calendar"></div> </div> This is my javascript added in html. <script> var eventSourceName = new Array(); var eventSourceData = new Array(); var i = 0; {% for key,val in mydict.items %} eventSourceName[i] = "{{key}}"; eventSourceData[i] = [ {% for dt in val %} { "title": "{{dt.title}}", "start": "{{dt.start}}", "end": "{{dt.end}}", "id": "{{dt.id}}", "color": "{{dt.color}}", }, {% endfor %} ]; i = i+1; {% endfor %} document.addEventListener('DOMContentLoaded', function () { var calendarEl = document.getElementById('calendar'); var currentDate = new Date(); var day = currentDate.getDate(); var month = currentDate.getMonth() + 1; var year = currentDate.getFullYear(); current_date = year + "-" + month + "-" + day; var calendar = new FullCalendar.Calendar(calendarEl, { initialView: 'dayGridMonth', initialDate: currentDate, headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,timeGridWeek,timeGridDay' }, editable: true, slotMinTime: "07:00:00", slotMaxTime: "20:00:00", eventSources:[ ] }); calendar.render(); }); jQuery(function(){ $("input.email_id").click(function(){ $("input.email_id:checked").each(function(){ var temp = $(this).val(); for(let i = 0;i<eventSourceName.length;i++){ if(eventSourceName[i] === temp){ $('#calender').fullCalendar('addEventSource',eventSourceData[i]); } … -
request.data changes in every variable
I have this code: initial_data = dict(request.data.copy()) reserve_data = dict(request.data.copy()) print(initial_data) for key in initial_data.keys(): merchant_data = initial_data.get(key) for sub_key in merchant_data.keys(): if sub_key in keys_to_change: reserve_data[key].pop(sub_key) reserve_data[key][values_to_change.get(sub_key)] = merchant_data.get(sub_key) print(initial_data) As you can see, I am not changing initial_data, but it changes anyway #before {'22': {'domain': 'cashier.random.io', 'salt': 'ewrwerwe', 'active': 1, 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}}} #after {'22': {'salt': 'ewrwerwe', 'separate_cashier': '', 'additional_hosts': {}, 'tradingroom_url': '', 'crm': {'login': '', 'secret': '', 'url': ''}, 'currencies': ['USD', 'EUR'], 'payment_methods': {'12': {}}, 'processors': {}, 'host': None, 'is_active': None}} Is there a way to avoid this? Thanks everybody -
Why celery task can not create record in django postgres database?
I use Django to run a web server and I installed celery and rabbitmq to deal with async tasks. Everything works fine however, celery tasks seem not to be able to create record in database. api/tasks.py from celery import shared_task from .models.event import Event @shared_task def test(): Event.objects.create(name='test') return '' api/views/test.py from api.tasks import test @api_view(['GET']) @authentication_classes([]) @permission_classes([]) def test(request): test.delay(); return Response(status=status.HTTP_200_OK, data='ok') api/celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api.settings') app = Celery('api') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() api/settings.py CELERY_BROKER_URL = 'amqp://localhost' Could you please help me out? Thank you! -
Django forms.select
I'm new with Django. I am creating a form with multiple Select fields. I would like my select to be able to display several fields, for example: ID - Group Name - Description This is my code forms.py `class EssenceForm(forms.ModelForm): readonly_fields = ('created', 'updated', 'created_by', 'updated_by') class Meta: model = essences fields = ['Essence','Classe','IdGroupe'] widgets = { 'Essence': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Saisissez une Essence'}), 'Classe': forms.Select(attrs={'class':'form-select', 'placeholder':'Saisissez une Classe'}), 'IdGroupe': forms.Select(attrs={'class':'form-select', 'placeholder':'Saisissez un Groupe'}), }` In the model.py I have declared the field like this: IdGroupe = models.ForeignKey('essence_groupe', on_delete=models.DO_NOTHING, blank=True, null=True, db_column='IdGroupe',verbose_name='Groupe') The problem is that in my Dropdown List only the "Group" appears. The "ID" and "Description" do not appear. What I'm doing wrong? Thanks -
How to download pdf from huge data in efficient way in django?
How can we download or generate pdf from huge data in Django in an efficient way? I'm having huge records like in millions and I want to generate pdf from data,As of now pdf is generating but it takes time to download, does an one know the efficient way or any alternative way to download pdf in more faster -
Django Filter based on 2 fields
I have a model where I can set expire_date_1 and expire_date_2. And 2 filters like this. filter_1 = Q(expire_date_1__isnull=False) & Q(expire_date_1__lte=after_30days) filter_2 = Q(expire_date_2__isnull=False) & Q(expire_date_2__lte=after_30days) I want to filter the model that if expire_date_2 is not null then using filter_2 else use filter_1 I tried it to do with Case and When but I can't filter in a When function, can I? -
CORS issue in django
settings.py INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True ajax request $.ajax({ type: "POST", url: `https://example.com/requestlink/`, crossDomain: true, data: { link: link, csrfmiddlewaretoken: csrf, }, success: function (data) { if (data) { data.forEach(src => { createresult(src); }) } icon.classList.replace('loading', 'search'); }, error: function (data) { icon.classList.replace('loading', 'search'); } }) Now when i do ajax post request, I got this in console tab Status 403 Forbidden Version HTTP/1.1 Transferred 1.53 KB (2.50 KB size) Referrer Policy no-referrer-when-downgrade and this in backend Forbidden (Referer checking failed - https:// anotherexample.com / does not match any trusted origins.): /requestlink/ Why so? -
Django - Compare Queryset with JSON data to make update operations
I have a dynamic form as JSON. When input added, JSON data has more items than Queryset. When input deleted, JSON data has less items than Queryset. My code as below: selectedUserForm = UserMeta.objects.filter(user=selectedUser, isDeleted = False) for form in selectedUserForm: if getJson['Id'] == form.id: formData = UserMeta.objects.filter(id=form.id).update(metaVal=getJson['Input'].title(), metaKey=getJson['Label']title()) elif getJson['Id'] == 0: formData = UserMeta(user = selectedUser, metaVal=getJson['Input'].title(), metaKey=form.Label.title()) try: formData.full_clean() formData.save() output.append({'Dynamic Form: Added! ': str(formData)}) except ValidationError as e: output.append({'Error': e}) return HttpResponse(e) elif getJson['Id'] != form.id: formData = UserMeta.objects.filter(id=form.id).update(isDeleted = True) It won't work because there is no iteration for JSON variable but when I add counter to iterate JSON data it gives error as "JSON data out of index" if JSON data has less items. Also, if JSON has more data, iteration cannot reach to those items. What is the proper approach to make update operation? -
Django: Prefetch Related multiple reverse relationships
I have the following models: class Animal(models.Model): name = models.CharField(max_length=256, blank=True, null=True) class Carnivore(models.Model): name = models.CharField(max_length=256, blank=True, null=True) animal = models.ForeignKey(Animal) testing_params = models.ForeignKey(TestParams, blank=True, null=True) class TestParams(models.Model): params_1 = models.CharField(max_length=256, blank=True, null=True) params_2 = models.CharField(max_length=256, blank=True, null=True) class Metrics(models.Model): carnivore = models.ForeignKey(Carnivore, null=True, blank=True) Now I want to prefetch carnivore animal, metrics for TestParams filter objects. So I am doing the following: test_params = TestParams.objects.filter(**filters) test_params_data = test_params.prefetch_related("carnivore_set", "carnivore_set__animal", "carnivore_set__metrics_set") But I am only getting carnivore_set in _prefetched_objects_cache parameter when I loop over the test_params_data and print each instance's __dict__. So how can I get multi level reverse relationships in prefetch_related? -
Css & Js not loading in Django cpanel
I just upload django project to cpanel but css & js not loading. this my path <link rel="stylesheet" type="text/css" href="/static/css/forms/switches.css%20"> my static folder is in public_html STATIC_URL = '/static/' -
How Do I Accept Nested JSON Data in django REST framework
I need to accept a user data via API in a django app using django-rest-framework, but the problem is that my server returns this error each time I make a POST request. My server always returns the error { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 1 (char 2)" } After a few research, I realized that this request data couldn't be parsed as a result of the presence of the square bracket in the JSON data value. Here is my serializers classes: app/serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = ProfileModel fields = ['age', '', 'reputation', 'date', 'confirmation'] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = UserModel fields = '__all__' Here is also an example of my JSON request data: { "user": "John Doe", "profile": [ { "age": 28, "reputation": "https://www.example.com", "date": "2021-02-27 15:05:02", "confirmation": 1 } ], "last_updated_date": "2021-09-27 15:05:02" } The question is how do I make the REST framework ignore the structure of the nested data or make it accept the square bracket([]) int the JSON data?. -
Using select_related in django for a specific use case?
I have these two models and I am trying to build up the logic of given the combination of days ( e.x., Mon-Tue 2-3 pm) I want to find out all the instructor names. I am unable to do that. I have tried using select_related but I am not able to use it properly I think. :) class TimeSlot(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) day = models.CharField(max_length=10, choices=WEEKDAYS) start_time = models.TimeField() end_time = models.TimeField() class Instructor(models.Model): name = models.CharField(max_length=50, validators=[validate_instructor_name]) -
django-smart-selects not working properly with jquery.formset.js django
I am a beginner in django. I have created a form using inlineformset_factory with jquery.formset.js library for increasing rows. The price field uses django-smart-selects where depending on the product selected, the available prices are populated in the price field. Everything works fine for the first row but for any other new row added, the django-smart-selects price field no longer works. Also, when I delete the first row and re-add it, the django-smart-selects no longer works. I want the price field to keep working on each row depending on what product is selected. Below are my codes: urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url(r'^chaining/', include('smart_selects.urls')), ] models.py class InventoryItem(models.Model): date = models.DateField(default=timezone.now) product_name = models.TextField(blank=False, unique=True) sales_price = models.DecimalField(_(u'Selling Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))]) objects = models.Manager() class Price(models.Model): product_id = models.ForeignKey(InventoryItem, on_delete=models.DO_NOTHING, verbose_name='Item Name') selling_price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))], blank=False, default=0) objects = models.Manager() class Invoice(models.Model): customer_name = models.TextField(blank=False, unique=True) objects = models.Manager() class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(blank=False) product_id = models.ForeignKey(InventoryItem, on_delete=models.DO_NOTHING, verbose_name='Item Name') price = ChainedForeignKey(Price, chained_field="product_id", chained_model_field="product_id", show_all=False, auto_choose=True, sort=True, default=0) objects = models.Manager() forms.py class InvoiceItemForm(ModelForm): … -
AttributeError: 'FileUploadSerializer' object has no attribute 'create_df'
class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer @method_decorator(name='post', decorator=swagger_auto_schema( operation_id='Import operatives from csv', operation_description="Requires key 'csv' in form-data" )) def create(self, request, *args, **kwargs): serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): errors = serializer.create_df(request.files.get("csv")) if errors: return Response(errors, status=status.HTTP_400_BAD_REQUEST) serializer.prepare_df() serializer.validate_duplicate_emails() data = serializer.df.to_dict('records') file_serializer = FileUploadSerializer(data=data, many=True) file_serializer.is_valid() serializer.add_error_messages(file_serializer.errors) if serializer.error_messages: return Response(serializer.error.messages, status=status.HTTP_409_CONFLICT) else: file_serializer.save() return Response(file_serializer.data, status=status.HTTP_200_OK) return Response(serializere.errors, status=status.HTTP_400_BAD_REQUEST) It looks like your post is mostly code; please add some more details. -
How to sort table in columns using Django?
I have some tables in html like this: ... <th> <div class="d-flex align-items-center"> <p class="fw-normal size-12 text-label mb-0 d-inline-block"></p> <i class="fas fa-arrow-down ms-2 text-gray-dark size-12"></i> </div> </th> ... I want to sort them using an arrow, but I have to use Django here. I didn't find much materials online. Any suggestion?