Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3: Customizing Textfield in admin
I am trying to customise the admin textfield in admin class PostAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': AdminMarkdownxWidget (attrs={'rows': 5, 'cols': 100, 'style': ' font-size: 1.5em; font-family: HelveticaNeue;'})}, } admin.site.register( Post, PostAdmin) In this example both rows and style is applied correctly but cols: parameter is ignored. I suspect this is bug in Django 3 but I am not sure. How would I customise the standard textfield in admin (no AdminMarkdownxWidget as in the above example) ? -
Attribute to override generic class based form and use a custom form?
I have the following form in forms.py: class JobForm(ModelForm): class Meta: model = Job fields = ['title', 'description'] widgets = {'title': TextInput(attrs={'class':'form-control'}), 'description': Textarea(attrs={'class':'form-control'}) } is there a way I can tell this view (and the CreateView) to use the form above: class JobUpdateView(UpdateView): model = Job fields = ['title', 'description'] template_name = 'job/edit_job.html' I'm just getting into using class-cased views and feel like this should have been easy to find with a quick search. Am I missing the point here, are you supposed to not have to define a custom for in forms.py if you are using class-based views? -
how to get sub string in django template
I have following list which i need to parse in django template. ['000.223.4.00/24|Network a', '000.000.00.0/25|Network b', '10.000.1.0/24|Network c'] Basically, i want to separate network and network name part already separated by '|'. Any idea of how to achieve it in django. I had been doing it with indexof() and substring methods in jquery. looking for a similar thing. -
How to validate field with django autocomplete light
I'm using django autocomplete light to let the user either search for an existing badge_id or create a new badge with the specified badge_id. My models: class User(models.Model): badge = models.ForeignKey(Badge, on_delete=models.CASCADE) first_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=_('first name')) last_name = models.CharField(max_length=20, blank=True, null=True, verbose_name=_('last name')) class Badge(models.Model): badge_id = models.CharField( primary_key=True, max_length=6, validators=[ RegexValidator( regex='^[0-9]{6}$', message="Badge id must be 6 digits.", code='nomatch' ) ], ) My UserForm: class UserForm(forms.ModelForm): class Meta: model = User fields = ( 'badge', 'first_name', 'last_name', ) widgets = { 'badge': autocomplete.ModelSelect2( url='badge-autocomplete', forward=["badge"], ) } My view for dal: class BadgeAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return Badge.objects.none() qs = Badge.objects.all() badge = self.forwarded.get('badge_id', None) if badge: qs = qs.filter(badge_id=badge) if self.q: qs = qs.filter(badge_id__istartswith=self.q) return qs With this in place, validation is not working and this leads to two problems: I can create a badges with less than 6 digits (despite my model validator) Entering more than 6 digits raises a DataError server side but nothing shows on the frontend Any idea how to fix that? -
Rename django custom permissions
I'm working with django 2.0 app and going to update django version to 3.0. But in my project there are few custom permissions named like view_modelname. class MyConcreteModel(models.Model): model_field_1 = models.CharField(max_length=100, blank=False) # other fields class Meta: permissions = ( ("view_myconcretemodel", "Can see available device interfaces"), ) In django 3 (since v 2.1) such kind of permissions are default. So I got conflict with permission names. Now I'm trying to rename custom permissions before updating django version. class MyConcreteModel(models.Model): model_field_1 = models.CharField(max_length=100, blank=False) # other fields class Meta: permissions = ( ("user_view_myconcretemodel", "User can see available device interfaces"), ) After migration 'new' (with new names) permissions were created in DB. But old permissions still there and all users have old permissions (with old names like view_myconcretemodel). Obviously I need 'new' permissions for all users. Is there possibility simple to rename permissions or give 'new' permissions to relevant users (according to 'old' permissions), and do it automatically? -
Django Jwt: Can we use multiple secret keys while encoding and decoding jwt
I am trying to create a Jwt token when user logs in Token = jwt.encode( payload, secret, algorithm) Here I want to pass two secrets while encoding. So how to do that. The reason is thats the way i can check some of my multiple conditions are met. Is concatenating of two or three UUIDS is possible. can i concatenate multiple secret UUID's and pass it as the secret key. -
Django : How can I update my views? url problem
Like below code, I made update view but it doesn't work. after I click the , it doesn't work an just "GET /moneylogs/update/7/ HTTP/1.1" 200 6243 console log printed. the page remain like just refresh. How can I update my moneylog? views.py class moneylog_update(UpdateView): model = moneylog_models.Moneylog form_class = forms.UpdateMoneylogForm template_name = "moneylogs/update.html" def form_valid(self, form): moneylog = form.save(commit=False) moneybook = moneybook_models.Moneybook.objects.get( pk=self.kwargs["pk"]) moneylog.save() form.save_m2m() return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk})) urls.py app_name = "moneylogs" urlpatterns = [ path("create/<int:pk>/", views.moneylog_create.as_view(), name="create"), path("update/<int:pk>/", views.moneylog_update.as_view(), name="update"), path("<int:moneybook_pk>/delete/<int:moneylog_pk>/", views.moneylog_delete, name="delete"), ] moneylog_form_update.html <div class="input {% if field.errors %}has_error{% endif %}"> <div class="flex"> <div class="w-1/4"> {{form.memo.label}} </div> <div class="w-3/4 border-b my-2 py-3"> {{form.memo}} </div> </div> {% if form.memo.errors %} {% for error in form.memo.errors %} <span class="text-red-700 font-medium text-sm">{{error}}</span> {% endfor %} {% endif %} </div> <a href="{% url 'moneylogs:update' moneylog.pk %} "> <div class="px-2 py-1 rounded bg-red-500 text-white">{{cta}}</div> </a> -
How to render django formset in a grid layout
I have the following forms that will display several forms from a formset. <form method="POST" enctype="multipart/form-data" style="margin-left: 40px; margin-right: 40px"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors }} {% for forma in formset.forms %} {{ forma }} {% endfor %} <input class="btn bg-success" type="submit" value="Update" /> When I use this layout all the forms in the formset are displayed vertically: Form 1 Form 2 Form 3 Form 4 ... ... ... Form n Instead of have the forms laid out vertically, I would something like this: Form 1 Form 2 Form 3 Form 4 ... ... Form n ie there should be a max of 3 forms in each row. -
Django 3.0 + Channels + ASGI + TokenAuthMiddleware
I upgraded to Django 3.0 and now I get this error when using websockets + TokenAuthMiddleware: SynchronousOnlyOperation You cannot call this from an async context - use a thread or sync_to_async. -
Django: validate_date() missing 1 required positional argument: 'value'
I try to implement validators for Django project I've defined a file validators.py in myapp I add validators=[validate_test] for my ran_num field but got an error I have another question: is it possible to control field BEFORE form submission? validators.py from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_test(self, value): if value == 'PPP': # just test raise ValidationError( _("Test"), code='Test', params={}, ) forms.py from .validators import validate_date class EditForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): super(EditForm, self).__init__(*args, **kwargs) self.request = request self.fields["asp_ent_loc"] = forms.ChoiceField(label = _("Site concerned by the operation"), widget=forms.Select, choices=SITE_CONCERNE) self.fields["med_num"] = forms.CharField(label = _("Trial bacth number"), required=True,validators=[validate_test] ) self.fields["asp_ent_dat"] = forms.DateField( label = _("Entry date"), required = True, initial = datetime.datetime.now(), ) self.fields["asp_ent_pro_pay"] = forms.ChoiceField(label = _("Country of treatment origin in case of entry"), widget=forms.Select, choices=PAYS) self.fields["asp_ent_pro_sit"] = forms.ChoiceField(label = _("Processing source site in case of entry"), widget=forms.Select, choices=SITE_PROVENANCE) def clean(self): cleaned_data = super(EditForm, self).clean() class Meta: model = Entree fields = ('asp_ent_loc','med_num','asp_ent_dat','asp_ent_pro_pay','asp_ent_pro_sit',) def clean_med_num(self): data = self.cleaned_data['med_num'] if len(data) != 3: raise forms.ValidationError(_("Error on Batch number format (3 letters)")) if not Medicament.objects.filter(med_num = data).exists(): raise ValidationError(_('Batch number does not exist')) return data def clean_asp_ent_dat(self): data = self.cleaned_data['asp_ent_dat'] entrydate = datetime.datetime.strptime(str(data), "%Y-%m-%d") currentdate = … -
Nginx and Django: how to ignore request error
I have a website using Django and Nginx. We use some integrated services (like Mautic) using API requests. But eventually this services stops and the requests throws 502 Bad Gateway error due to a timeout. Some applications depend on the operation of these requests for the flow to complete correctly. How can I register the log and continue the proccess? -
FileHandler doesn't write into the file
I need a logger in Django which writes to logs/realestates/realestate.pk/info.log. To be able to do this I'm creating logger dynamically. def get_realestate_logger(realestate): logger = logging.getLogger(f'engine.realestate.{realestate.pk}') logpath = realestate.get_log_path() # checked, it's ok logdir = os.path.dirname(logpath) if not os.path.exists(logdir): os.makedirs(logdir) handler = RotatingFileHandler(filename=logpath, backupCount=0, maxBytes=1024 * 1024) handler.setLevel(logging.INFO) handler.setFormatter(logging.Formatter(fmt=settings.LOGGING_VERBOSE_FORMAT, style='{')) logger.addHandler(handler) return logger And in realestate def save(self, refresh_status=True, **kwargs): super().save(**kwargs) logger = self.get_logger() logger.info('Created') def get_logger(self): return get_realestate_logger(self) The problem is that it doesn't write anything into the info.log file. Since propagation=True, it writes Created into the main log file. Just info.log doesn't contain anything. Where is the problem? -
Append values to serializer data
I am fetching some customer credit cards from an API. The data does not indicate the customers 'default' card, although another API can do this. I would like to filter over the first data set and add a value indicating if the card matches the default card. customer = Customer.objects.get(subscriber=request.user.organization_id) default_payment_method = customer.default_payment_method.organization_id cards = PaymentMethod.objects.filter(customer=customer.djstripe_id) serializer = PaymentMethodSerializer(cards, many=True) # something like this, although I know this is not right for card in cards: if card.id == default_payment_method: set card.default=True return Response(cards) cards = [{"id":"pm_1G6u80AFXbZqlwaURe8swF23","billing_details":{"address":{"city":null," -
How to make the path connection in django template?
Whenever I just run index.html, it shows me the page with a proper style which I have given links of them. But whenever I run this code in Django, links don't work. It shows me just text with no style. app URL from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] project url from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app1.urls')), path('admin/', admin.site.urls) ] views.py from django.shortcuts import render from django.http import HttpResponse def index(request): return render(request, 'index.html'); index.html <!DOCTYPE html> <html> <head> <title></title> <link rel="shortcut icon" href="favicon.ico"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="css/icomoon.css"> </head> <body> <header role="banner" id="fh5co-header"> <div class="fluid-container"> <nav class="navbar navbar-default navbar-fixed-top js-fullheight"> <div id="navbar" class="navbar-collapse js-fullheight"> <ul class="nav navbar-nav navbar-left"> <li class="active"><a href="#" data-nav-section="home"><span>Home</span></a></li> <li><a href="#" data-nav-section="services"><span>Services</span></a></li> <li><a href="#" data-nav-section="explore"><span>Project</span></a></li> <li><a href="#" data-nav-section="pricing"><span>Pricing</span></a></li> <li><a href="#" data-nav-section="team"><span>Team</span></a></li> </ul> </div> </nav> </div> </header> </body> </html> -
How should I be implementing user SSO with AAD in a Django application (using the Django Microsoft Authentication Backend module)?
I'm developing a Django (2.2.3) application with Django Microsoft Auth installed to handle SSO with Azure AD. I've been able to follow the quickstart documentation to allow me to log into the Django Admin panel by either using my Microsoft identity, or a standard username and password I've added to the Django user table. This all works out of the box and is fine. My question put (really) simply is "What do I do next?". From a user's perspective, I'd like them to: Navigate to my application (example.com/ or example.com/content) - Django will realise they aren't authenticated, and either automatically redirect them to the SSO portal in the same window, or redirect them to example.com/login, which requires them to click a button that will open the SSO portal in a window (which is what happens in the default admin case) Allow them to sign in and use MFA with their Microsoft Account Once successful redirect them to my @login_required pages (example.com/content) Currently, at the root of my navigation (example.com/), I have this: def index(request): if request.user.is_authenticated: return redirect("/content") else: return redirect("/login") My original idea was to simply change the redirect("/login") to redirect(authorization_url) - and this is where my problems start.. … -
Filtering many-to-many relationthip
I make api with rest-framwork for django 3 I have a model which has many-to-many relationship. then, now I want to use filter for many-to-many in models.py class Text(models.Model): t_id = models.CharField(unique=True,null=False,max_length=20) t_text = models.TextField(null=True) issues = models.ManyToManyField(Issue) # It is many-to-many relationship pub_date = models.DateTimeField('date published') def __str__(self): return self.t_id in serializer.py class TextFilter(filters.FilterSet): t_text = filters.CharFilter(lookup_expr='contains') # it works issues = filter.***Filter # How should I do here?? class Meta: model = Text fields = ('t_text','issues') -
Dajango cannot find database when using docker-compose
this is my Dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 ENV WORKDIR /usr/src/app WORKDIR ${WORKDIR} RUN pip install --upgrade pip && pip install pipenv COPY ./Pipfile* ${WORKDIR}/ RUN pipenv lock --requirements > requirements.txt RUN pip install -r requirements.txt ADD . ${WORKDIR}/ And this is my docker-compose.yml version: '3' services: database: image: postgres:latest environment: POSTGRES_PASSWORD: development POSTGRES_USER: development POSTGRES_DB: dev_db ports: - 5432:5432 backend: build: . command: python /usr/src/app/manage.py runserver 0.0.0.0:8000 volumes: - .:/usr/src/app ports: - 8000:8000 depends_on: - database my django database configurations: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'dev_db', 'USER': 'development', 'PASSWORD': 'development', 'HOST': 'database', 'PORT': 5432, } } however every time docker compose srats it gives the following message: Is the server running on host "database" (172.29.0.2) and accepting TCP/IP connections on port 5432? is there some reason why this is not working, as far as I know both services are inside the same network -
How can i access custom decorator from the module in the django app view
This is my project directory. Api is an app in this structure where as mappingdecorator is a python package that i created. It has a file mappingdecorator which has a decorator. I want to make this decorator available in api app. Below is the code i wrote to access it in the api file. from proj.proj.mappingdecorator.mappingdecorator import mapping_the_fields @api_view(['GET']) @mapping_the_fields def user_view(request, id=None): #code I am purposely omitting the code inside mappingdecorator file and my api_view since i tested both of them in the same file and they were working but separtion made a mess and throwed an exception on execution. This is the runtime error i am getting: from proj.proj.mappingdecorator.mappingdecorator import mapping_the_fields ModuleNotFoundError: No module named 'proj.proj' -
Django: can we load dict directly to the database using django ORM
I have lot of dict data like {{'title':'stackoverflow'}} where the keys are similar to the table column names. i want to load all the dict directly to the database using the django ORM. -
Capture the NTLM username and pass as a parameter to a Stored Procedure
I have created a simple Django website which outputs the result of executing a Stored Procedure. Is there anyway I can capture the NTLM username of the user accessing the website and pass that as parameter to the Store Procedure before it is executed? P.S be gentle I am new to coding and have been learning and playing with Python Django on the fly. Below is the code I have for executing the Stored Procedure. def sql_results(request, query): sql_query = { 'results': 'SET NOCOUNT ON; EXEC [StoredProcedureName]', } sql = sql_query.get(query, None) with connection.cursor() as cursor: cursor.execute(sql) desc = [ name[0] for name in cursor.description] data = cursor.fetchall() return render(request, 'results.html', {'data': data, 'desc': desc}) -
What is the difference between the request and self?
Same as the title. What is the difference between the request and self in Django? i'd try class based view and function view. and copy well-made code. but I don't know whay is the difference between self in fomr_valid and request in moneylog_delete definition. class moneylog_update(UpdateView): model = moneylog_models.Moneylog form_class = forms.UpdateMoneylogForm template_name = "moneylogs/update.html" def form_valid(self, form): moneylog = form.save(commit=False) moneybook = moneybook_models.Moneybook.objects.get( pk=self.kwargs["pk"]) moneylog.save() form.save_m2m() return redirect(reverse("moneybooks:detail", kwargs={'pk': moneybook.pk})) def moneylog_delete(request, moneybook_pk, moneylog_pk): user = request.user try: moneybook = moneybook_models.Moneybook.objects.get(pk=moneybook_pk) models.Moneylog.objects.filter(pk=moneylog_pk).delete() return redirect(reverse("moneybook:detail", kwargs={"pk": moneybook.pk})) except models.Moneylog.DoesNotExist: return redirect(reverse("cores:home")) -
Social login with Django: How to interact with frontend(jQuery)?
I have configured Github social login with Django(django_restframework + social_django) as guided here. And I created login template inside Django and it's successful. But if I redirect to frontend(jQuery) after social login, auth information is not preserved. This is the scenario; User clicks [login with github] button from frontend(jQuery). It redirects to DRF login page and auth procedure with Github started. Authentication is successful in DRF side. Django login page redirects to frontend. The frontned can't get user's authentication. How can I cache the credentials from frontend side? GET http://127.0.0.1:8000/profile/ 401 (Unauthorized) -
Django csrf follow up ajax requests not working
I have an ajax type request veing triggered from javascript, but my django app is throwing an error "Forbidden (csrf token missing or incorrect)". It works on the intial post request, but fails on the follow up ones. I'm using UIKit so my request looks like this: UIkit.upload('.js-upload', { url: '', multiple: true, mime: "image/*", name: "sketches", type: "json", params: { "csrfmiddlewaretoken": Cookies.get('csrftoken'), }, completeAll: function (e) { console.log('completeAll', e.response); } }); I've also tried doing loading the csrf by setting: params: { "csrfmiddlewaretoken": {{ csrf_token }}, }, And get the same result; works with the first upload, and fails on subsequent uploads. Does django rotate the csrf_token with each request? Can I access the new token in my views to pass it via json back to the frontend for the next request? -
How to deploy Django
I was able to get a Django web app running by typing python manage.py runserver server-name, but what is the command to deploy it on the server so that it keeps running even if I’m no longer connected to the server via ssh, or if I close the terminal window? -
reverse url link within list view template
i created methods within my model class to handle my redirects all work except for the one i created for a link in my list view(go_to_create method ) im using class based views class Todo(models.Model): name = models.CharField(max_length=100, default='unamedTodo') description = models.CharField(max_length=200) Todo_date = models.DateTimeField('Todo Date') pub_date = models.DateTimeField('Date Published') def get_absolute_url(self): return reverse('ToDo:detail', kwargs={'id': self.id}) def get_back_home(self): return reverse('ToDo:todos', kwargs={}) def go_to_update(self): return reverse('ToDo:update', kwargs={'id': self.id}) def go_to_create(self): return reverse('ToDo:create', kwargs={}) from django.urls import path from .views import ( TodoListView, TodoDetailView, TodoCreateView, TodoUpdateView, TodoDeleteView, ) app_name = "ToDo" urlpatterns = [ path('Todos/', TodoListView.as_view(), name='todos'), path('Todos/<int:id>/', TodoDetailView.as_view(), name='detail'), path('Todos/create/', TodoCreateView.as_view(), name='create'), path('Todos/<int:id>/update/', TodoUpdateView.as_view(), name='update'), path('Todos/<int:id>/delete/', TodoDeleteView.as_view(), name='delete') ] <h1>ToDo's</h1> <ul> {% for object in object_list %} <li> <p> {{ object.id }} - <a href="{{ object.get_absolute_url }}">{{ object.name }}</a> </p> </li> {% endfor %} <p>Create new Todo <a href="{{ object.go_to_create }}">here</a></p> </ul> my link to create new todo does not work