Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to solve Incorrect padding error in django
Traceback: Traceback (most recent call last): File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 199, in _get_session return self._session_cache During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\pranil\web_projects\mon_amie\onlyapp\views.py", line 11, in home if request.user.is_authenticated: File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 224, in inner self._setup() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 360, in _setup self._wrapped = self._setupfunc() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\middleware.py", line 24, in request.user = SimpleLazyObject(lambda: get_user(request)) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user request.cached_user = auth.get_user(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth_init.py", line 173, in get_user user_id = get_user_session_key(request) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth_init.py", line 58, in _get_user_session_key return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 64, in getitem return self._session[key] File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 204, in _get_session self._session_cache = self.load() File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\db.py", line 44, in load return self.decode(s.session_data) if s else {} File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\sessions\backends\base.py", line 110, in decode encoded_data = base64.b64decode(session_data.encode('ascii')) File "C:\Users\Pranil.DESKTOP-TLQKP4G.000\AppData\Local\Programs\Python\Python37-32\lib\base64.py", line 87, in b64decode return binascii.a2b_base64(s) Exception Type: Error at / Exception Value: Incorrect padding My views function of the page which is giving error: def home(request): if request.user.is_authenticated: return redirect('user') else: return render(request, 'home.html') What could have possibly gone wrong cause … -
Setting a default value for model fields in Django
I want to create a model in Django with two fields {initial price, current price} .. is there a way in Django to set the default value for the current price field to be the same as the initial price field value? -
Django: How to parse slug from url typed in address bar?
I am trying to simulate Google's behavior where the user types something on the address bar of the browser and the Django server checks for any exact matches in the database. If so, a detailview of the object is rendered. If not an exact match, then a list of matches on substrings are rendered with ListView. This behavior works fine when the user types into a search form. For instance, when the user just types the letter 'j' in the search form and hits submit, the Django server matches on 3 objects in the data base 'Django, Java, node.js' and renders this list through ListView. If there is an exact match, say the user typed 'java', then the Django server renders details about the object 'java' in a Detail view. The relevant segments of the html form, urls.py, and views.py are displayed below <form method="GET" action="{% url 'searchwiki' %}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> urls.py : from django.urls import path from . import views urlpatterns = [ path("", views.EntryListView.as_view(), name="index"), path("entries/",views.EntryListView.as_view(),name='entries'), path("entry/<int:pk>",views.EntryDetailView.as_view(),name="entry_detail"), path("<int:pk>", views.EntryDetailView.as_view(), name="path_entry-detail"), **# path("<slug:subject>",views.get_obj_orlist), path("<slug:subject>",views.EntryDetailView.as_view()),** path("random/",views.randompage,name="randompage"), **path("searchwiki/",views.searchwiki,name="searchwiki"),** ] views.py : def searchwiki(request): searchtoken = request.GET.get('q') try: entry = Entry.objects.get(subject=searchtoken) except Entry.DoesNotExist: entries = Entry.objects.filter(subject__icontains=searchtoken) print("Inside … -
add serial number in a row automatically in django-model?
i want to create customer data table as such i want to create customer id- as unique id code - i did the following - class customer(models.Model): def number(self): no = customer.objects.aggregate(Max('customerid')) if no == None: return 1 else: return no + 1 customerid = models.IntegerField(_('Code'), unique=True, \ default=number) customername=models.CharField(max_length=1000) def __str__(self): return self.customername the code is giving me error-undefined variable:'_' i want to know- can this be a primary key? if i have 10 customers later i deleted one then will the id change or it will keep on adding as 11? i want a fixed unique id even if its deleted later DO I have to use any other Code? Please Help -
How to test CSRF protected sites using gatling?
I am testing a django powered site using gatling. My forms are protected by a CSRF token: <input type="hidden" name="csrfmiddlewaretoken" value="EqFQPv1fdfJjAfq4wFcWkVsecmWSisQzQU0ee1utyOEpJd7edxk3DMhAQNMpI2DK"> How can I test my forms using Gatling testing framework? -
Python decorator not calling intermittenly
decorator.py file: ========================= class Decorator1: def __init__(<params>): <code snippet1> <code snippet2> example.py file: ====================== from decorator import decorator class Example1: @Decorator1(<args, kwargs>) def method1: <method code snippet> @Decorator1(<args, kwargs>) def method2: <method code snippet> def method3: <method code snippet> All three functions are part of different API execution flows, intermittently decorators are not executing and not throwing any exception. Is this because of multiple usages in a single class/file with only one-time importing decorator class? -
Django Logging per user
I have an application in Django in witch I have logging... My problem is, that if two users are using an application at the same time, logs are mixed. That way, I can't see where the application stuck if there is a bug... How to add a user to a log file (maybe in formatters) or to do different files for each user... Right now I have logging set: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters' : { 'standard': { 'format': '%(asctime)s %(levelname)s %(name)s %(message)s' }, }, 'handlers': { -
Django error: name 'LOGIN_REDIRECT_URL' is not defined
I am trying to take advantage of the global variable LOGIN_REDIRECT_URL in the settings.py file in my Django project to avoid duplicating URLs everywhere. In my settings.py I have redefined LOGIN_REDIRECT_URL like so: LOGIN_REDIRECT_URL = "my_app_name:index" I am trying to use LOGIN_REDIRECT_URL in my login_view in views.py as follows: def login_view(request): form = LoginForm(data=request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse(LOGIN_REDIRECT_URL)) else: ... However, when I log in I get the following error message: name 'LOGIN_REDIRECT_URL' is not defined I thought about importing LOGIN_REDIRECT_URL from settings.py but that feels wrong since other variables from there do not need to be imported anywhere. What am I doing wrong? -
Error when deploying an application with django in apache
Hello please anybody help me please ( I am new with this environment ) please see the code: AND WHEN YOU GO TO THE URL, IT APPEARS IN THE INDEX OF THE WEB SERVER PANEL, NORMALLY I HAVE A CONSTRUCTION INDEX, BUT NOW, NOT EVEN MY PROJECT COMES OUT. IT ONLY SHOWS THE INDEX THAT I MENTIONED ABOVE(SER SERVER PANEL). APACHE SERVER http <VirtualHost *:80> ServerName mydomain.com ServerAlias www.mydomain.com ServerAdmin webmaster@mydomanin.com DocumentRoot /home/admin/public_html UseCanonicalName Off ScriptAlias /cgi-bin/ /home/admin/public_html/cgi-bin/ #CustomLog /usr/local/apache/domlogs/mydomain.com.bytes bytes #CustomLog /usr/local/apache/domlogs/mydomain.com.log combined ErrorLog /usr/local/apache/domlogs/mydomain.com.error.log # Custom settings are loaded below this line (if any exist) # IncludeOptional "/usr/local/apache/conf/userdata/admin/mydomain.com/*.conf" <IfModule mod_setenvif.c> SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on </IfModule> <IfModule mod_userdir.c> UserDir disabled UserDir enabled admin </IfModule> <IfModule mod_suexec.c> SuexecUserGroup admin admin </IfModule> <IfModule mod_suphp.c> suPHP_UserGroup admin admin suPHP_ConfigPath /home/admin </IfModule> <IfModule mod_ruid2.c> RMode config RUidGid admin admin </IfModule> <IfModule itk.c> AssignUserID admin admin </IfModule> WSGIScriptAlias / /home/admin/public_html/myproject/myfolder/wsgi.py <Directory "/home/admin/public_html/myproject"> <Files wsgi.py> Require all granted </Files> </Directory> <IfModule proxy_fcgi_module> <FilesMatch \.php$> SetHandler "proxy:unix:/opt/alt/php-fpm72/usr/var/sockets/admin.sock|fcgi://localhost" </FilesMatch> </IfModule> </VirtualHost> https <VirtualHost *:443> ServerName mydomain.com ServerAlias www.mydomain.com ServerAdmin webmaster@mydomain.com DocumentRoot /home/admin/public_html UseCanonicalName Off ScriptAlias /cgi-bin/ /home/admin/public_html/cgi-bin/ #CustomLog /usr/local/apache/domlogs/mydomain.com.bytes bytes #CustomLog /usr/local/apache/domlogs/mydomain.com.log combined ErrorLog /usr/local/apache/domlogs/mydomain.com.error.log # Custom settings are loaded below this line (if any exist) # … -
How to put an IntegerField and a Text into the same line in a survey using CSS / Django?
I do a survey and would love to put my IntegerField into the same line as my text. Right now, it is displayed vertically (InputField under the sentence) as seen in the picture (How it looks right now) but I would like to have a small IntegerField within the same line or the same sentence. Anybody has an idea on how to do it? I am not really familiar with css. Maybe the css_class could help there. Thanks! forms.py class SurveyPolicy(forms.Form): policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.desc = "example" self.helper.layout = Layout( Fieldset( "<hr><h6 style='color: #2D2D2D; font-family: Arial;'>Die Maßnahmen sollten zu</h5>", Div('policy6b', css_class='form-group row-ml-0 mb-0'), ), Fieldset( "<h6 style='color: #2D2D2D; font-family: Arial;'>% durch eine Abgabe auf konventionelle Energieträger wie z.B. Erdgas finanziert werden - schließlich sollten Leute, die mehr CO2-Ausstoß verursachen auch mehr bezahlen.</h5>", ), [...] -
AttributeError at / 'str' object has no attribute 'get' in Danjo
Exception Value:'str' object has no attribute 'get' Exception Location: C:\Python\Python38-32\Scripts\myenv\lib\site-packages\django\forms\models.py, line 346, in _get_validation_exclusions models.py from django.db import models class HomePageModel(models.Model): first_name = models.CharField(max_length = 20) last_name = models.CharField(max_length = 20) password = models.CharField(max_length = 12) confirm_password = models.CharField(max_length = 12) phone_number = models.CharField(max_length = 10) gender = models.CharField(max_length = 6) city = models.CharField(max_length = 20) def __str__(self): return self.first_name forms.py from django import forms from .models import HomePageModel from django.core.exceptions import ValidationError import re class HomePageForm(forms.ModelForm): class Meta: model = HomePageModel fields = "__all__" def clean(self): super(HomePageForm, self).clean() first_name = self.cleaned_data.get('first_name') try: regex = re.compile('[@_!#$%^&*()<>?/\|}{~:]') flag_decimal = 0 flag_alpha = 0 if len(first_name) > 20: raise ValidationError('Fisrt Name can not be more than 20 characters') if (regex.search(first_name) != None): raise ValidationError('Fisrt Name can not have a special character') else: for char in first_name: if char.isdecimal(): flag_decimal = 1 if char.isalpha(): flag_alpha = 1 if flag_decimal == 1 or flag_alpha == 0: raise ValidationError('Fisrt Name can not have a number') return first_name except ValidationError as e: print(e) .... #rest validation views.py from django.shortcuts import render from django.http import HttpResponse from .forms import HomePageForm def home_page(request): if request.method == 'POST': form = HomePageForm(request.POST) if form.is_valid(): form.save() return HttpResponse('Successful') else: return render(request, … -
django.db.utils.DataError: invalid input syntax for type json, (Token "add" is invalid., JSON data, line 1: add...)
I'm using django as my backend and it was working very fine, but after I tried to rplace text = models.JSONField(blank=True, null=True) with text = models.TextField(blank=True, null=True)and also after a ranpython manage.py migrate` I got this err: return self.cursor.execute(sql, params) django.db.utils.DataError: invalid input syntax for type json DETAIL: Token "add" is invalid. CONTEXT: JSON data, line 1: add... models.py class elements(models.Model): tag = models.CharField(blank=True, null=True, max_length=20) // it was text = models.TextField(blank=True, null=True) // now it is text = models.JSONField(blank=True, null=True) src = models.TextField(blank=True, null=True) # problem: styles replace spaces with slashes (/) # I tried: json field but did'nt work. style = models.JSONField(blank=True, null=True) main = models.ForeignKey( 'self', null=True, blank=True, related_name="sub", on_delete=models.PROTECT) def __str__(self): return "<elements: {} {}>".format(self.tag, self.text, self.src, self.style) def __repr__(self): return self.__str__() note: when I run python manage.py runserver every thing work just fine but it says You have 3 unapplied migration(s). -
Django dynamic card redactor / processor showing on landing page
My goal is to have my website’s home page appear like this where only the form block element is present (marked by the large red “A”). After the website visitor enters their card number on that landing page, Django should redact it and render the same home page but the form should be gone and only the field divider with the processed output showing (marked by the large red “B”) as it appears in this pic on imgur. How do I achieve this? These two pics are kind of like a ‘mock up’, meaning I just commented out the form and divider sections. When only A shows when B is commented out, I lose the functionality. For the functionality to work, ‘A’ and ‘B’ shows at the same time as shown here, which is not what I want. I need to modify the template (perhaps by adding conditional logic?). I’m not sure how to tell Django to serve the template so that only ‘A’ shows first and then, after the site visitor enters their 12 digit card number, remove ‘A’ and only show ‘B’. Here is the template that I am working with showing the card processor form/divider elements: <div … -
ValidationError not display for MultiSelectField in Django
According to Django's doc, we can raise the ValidationError inside Form class using clean_<Fieldname> function. In my model I have a field called teacher_department which is a MultiSelectField from third party (django-multiselectfield). I gave blank=True to that field for some reasons. Now I want to check the field if user fill it or not and if not then raise an error. Before I checked it by doing a condition inside views.py and gave the error message but now I want to do it inside Form class by raising the ValidationError. Other fields such as email or password or first_name works just fine except teacher_department field. here is my models.py class CustomUser(AbstractUser): email = models.EmailField(_('Email Address'), unique=True) teacher_department = MultiSelectField(choices=department_choice, blank=True) forms.py and how I raise the ValidationError class TeacherRegisterForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = ['email', 'teacher_department', ...] def __init__(self, *args, **kwargs): super(TeacherRegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update(email_attr) def clean_email(self): email = self.cleaned_data.get('email') email_check = CustomUser.objects.filter(email=email).exists() if email_check: raise forms.ValidationError(_('Email is already taken!'), code='invalid') def clean_teacher_department(self): teacher_department = self.cleaned_data.get('teacher_department') if teacher_department is None: raise forms.ValidationError(_("Department required"), code='invalid' template <form method="POST" id="#teacher_register_form"> {% csrf_token %} <div class="md-form pt-2"> <label>Email Address</label> {{ form.email }} <small style="color: red;">*{{ form.email.errors|striptags }}</small> </div> <div class="row mt-3"> … -
Unable to migrate with django and sqlite (django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table)
I'm filling a SQLite Database and want to use it in my django project. Previously that worked fine but now when I want to migrate I get the following error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Traceback (most recent call last): File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: None The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\migrations\recorder.py", line 67, in ensure_schema editor.create_model(self.Migration) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\schema.py", line 34, in __exit__ self.connection.check_constraints() File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 311, in check_constraints (rowid,), File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 99, in execute return super().execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Daten\Software\venv_SQLdatabase\lib\site-packages\django\db\backends\sqlite3\base.py", line 383, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, … -
Django read tsv and save data to db
I am a beginner to django and i am facing an issue in reading data . Example my file contains 400 rows which needs to be saved in the database . when i run the functionality locally i am able to add the data to db , but when i push the same functionality to heroku . i am not able to add the data to db , i keep getting an error . Thanks in Advance for your suggestions . -
Get Data from Inline with Admin.User Model
I am trying to use an 'augmentation' table with the Admin.User Model to store additional data related to that user/login. Here is my admin.py class UserProfileInline(admin.StackedInline): model = AppUserProfile can_delete = False verbose_name_plural = 'profile' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (UserProfileInline,) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) Here is my models.py class AppUserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.DO_NOTHING) usr_tpid = models.CharField(max_length=20) usr_cstid = models.CharField(max_length=20) db_table = 'app_user_profile' Here is my views.py where I'm trying to get the usr_cstid from the login value. def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): print(request.POST) username = form.cleaned_data['userName'] password = form.cleaned_data['password'] userInfo = AppUserProfile.objects.all().filter(user=username) However I'm getting the following error: ValueError: invalid literal for int() with base 10: 'supplier_ad' I am not sure what I have wrong, or how to link back to those values. -
Django FormView manually set session data lost after redirect
I am using FormView to get some input from the user. I then try to set some of that data into the session to be used after the form validates and the user is redirected. The data is however lost. The view: class SomeFormView(FormView): template_name = 'something.html' form_class = SomeForm def form_valid(self, form): self.request.session['some_key'] = 'some value' # According to manual, this should work self.request.session.modified = True # Hail Mary self.request.session.save() return super().form_valid(form) If I look at the self.request.session contents prior to the redirect, it will have the value I've set as: '_session_cache': {'some_key': 'some_value'} But when I arrive at the redirect, the data is nowhere to be found. I tested this on Django 3.1.1 and Django 2.2.16, with both acting the same -
Block invalid HTTP_HOST headers in Apache in AWS ElasticBeanstalk
I have several websites running Django/Apache in AWS ElasticBeanstalk. My only problem is the hundreds of emails I receive every day with this subject: [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: WHATEVER. You may need to add WHATEVER to ALLOWED_HOSTS. That's because I have properly configured the ALLOWED_HOSTS variable in my Django configuration, but I need Apache to block all invalid HTTP_HOST headers so they don't even reach Django and get rid of these hundreds of emails every day. There are dozens of examples of how to do that in Apache here and there, I know, but I haven't found a single example of how to do it when deploying in AWS ElasticBeanstalk. The main difference when deploying there is that I can't add a configuration that only works within a <VirtualHost> block. I need something that works properly outside of a <VirtualHost> block, allowing me to put it in a standalone Apache config file. Here there is a really nice explanation of all this: https://stackoverflow.com/a/38751648/1062587, however, that question was asking about RewriteRules and not blocking invalid hosts. What I would need is the proper configuration for a file similar to this one: files: "/etc/httpd/conf.d/require_valid_hosts.conf": mode: "000644" owner: root group: … -
Django url parameters confusion
Hi: I have the hope you can helpme with my "django existential doubt". Every time Im ask google for this the same thing happens to me (english is not my mother tongue), I have this doubt, this confusion: Whats is the name of this things??? "my/happy/int:year/" this is called "url parameter" but "my/happy/year?y=2020" also is called "url paramenter" or not?? Thank you for your ilumination! -
My demo django project doesn't start server after a restarting command prompt
I have created demo django project, now I cant run the server. I'm getting "ImportError: Couldn't import Django" I dont know what I'm missing. -
How to use Angular Datatables with Django Backend
I'm trying to use Datables with Django but I couldn't figure out how to get data in the correct form. Django's rest API is returning an object but the Angular Datatables want a JSON file, so how can I achieve this result? Here's what I've tried: HTML: <table datatable class="row-border hover"> <thead> <tr class="header"> <th class="date">Id</th> <th class="date">Nom</th> <th class="societe">Email</th> <th class="evenements">Date d'inscription</th> <th class="facturePDF">Actif</th> </tr> </thead> <tbody *ngIf="persons?.length != 0"> <tr *ngFor="let item of Users;let index=index"> <td class="text-monospace pt-3 pl-4"> {{item?.id}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.name}} {{item?.lastname}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.email}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.date_joined.slice(0,10)}} </td> <td class="text-monospace pt-3 pl-4"> {{item?.is_active}} </td> </tr> </tbody> <tbody *ngIf="Users?.length == 0"> <tr> <td colspan="3" class="no-data-available">No data!</td> </tr> <tbody> </table> admin.component.ts: ngOnInit() { this.dtOptions = { pagingType: 'full_numbers', pageLength: 2 }; this.GetUsers(); } GetUsers(){ this.ApiService.list_users(this.page).subscribe( data => { this.Users = this.Users.concat(data); }, error=>{ console.log(error); } ) } The "list_users" function call Django to retrieve data from the database: @api_view(['GET','POST','DELETE']) def list_annonces(request): if request.method == 'GET': annonces = Annonces.objects.all().order_by('-id') count = Annonces.objects.count() try: page = int(request.GET.get('page')) except Exception: page = 1 limit = count offset = (page-1) * 10 annonces_data = AnnonceSerialize(annonces.all()[offset:limit], many=True) return Response(annonces_data.data, status.HTTP_200_OK) ``` -
how to use LOGIN_REDIRECT_URL in that case
LOGIN_REDIRECT_URL doesn't work when setting URL with arguments. urls.py urlpatterns = [ path('user/<str:username>', views.UserTaskListView.as_view(),name='user-tasks') ] settings.py LOGIN_REDIRECT_URL='user-tasks' #<===== doesn't work error message enter image description here -
Autogenerate ID field in Django models combining multiple fields
I am trying to design a web-app for task management. In my Task model there is column Task ID other than AutoField ID. I was trying to populate this field in such a way that it reflects content of different fields. For eg: I have multiple organizations, multiple departments, so what I am trying to achieve is to generate a Task ID which reflects Organization, Department and sequence number like TSK(01)(02)01 where (01) represents a particular organization (02) represents department and rest is an auto incrementing serial number. So any ideas?? -
Django filtering on related models attributes
class Count(models.Model): start_time = models.DateTimeField(null = True, blank = True) end_time = models.DateTimeField(null = True, blank = True) class AccessRecord(models.Model): user = models.ForeignKey(get_user_model(), related_name = 'accesses', on_delete = models.CASCADE) count = models.ForeignKey(Count, related_name = 'accesses', on_delete = models.CASCADE) With this model scheme, how can i filter on a Count queryset based on the user? For example, i want every count object that has the first Access Record with a certain user id. user_id = 2 all_counts = Count.objects.all() list(filter(lambda x: x.accesses.first().user.pk == user_id, all_counts)) ^^ This would work. However i get a list instead of a query set (i still need to order_by, etc..) What's the best alternative here?