Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django single sign on between different ports
thank you for taking a look at this question. I have 2 separate Django projects and host the two project through nginx as such: http://xxx.xx.x.xxx:8080/ => Django Project A http://xxx.xx.x.xxx:8000/ => Django Project B The 2 projects are integrated in such a way that the projects share the same user table of PostgreSQL. Each of the projects has its own login page but I can use the same login credentials on the both login pages. The thing is, the projects cannot share login sessions(or cookies?) with each other. So I need to sign in on the project A first and sign in on the project B once more(or vice versa) with the same credential. I've heard that I need to use SSO(Single Sign On) to solve this problem but none of solutions below could solve it. django-simple-sso django-cas-provider/consumer MamaCAS Tried to tweak session options on settings.py (e.g. SESSION_COOKIE_DOMAIN) Maybe there could be some lack of my understanding on one of those solutions above but most of the solutions were outdated or not fit for this case. How could I deal with this issue? Have you solved any similar issues? -
why does it say "module does not exist" despite multiple installations
I am running the following steps in Mac Terminal: (1) sudo easy_install pip (2) sudo pip install virtualenv (3) virtualenv NameOfFolder (4) cd NameOfFolder (5) source bin/activate (6) sudo pip install django (7) django-admin startproject NameOfFolderSub1 (8) cd NameOfFolderSub1 (9) python manage.py runserver At this last steps, it communicates this msg occurred: Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 14, in import django ModuleNotFoundError: No module named 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Attempted to check the Django version using this command in Terminal: python -m django --version it confirmed that django is not there with the following msg: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3: No module named django What did I do wrong int he step-by-step installation above ? Appreciate the help. The code in manage.py is … -
Saving on a Model that has foreign and M2M relation
I have 3 models, say, Fruits, Season, and FruitSeason class Fruit(models.Model): fruit_name = models.CharField(max_length=30) class Season(models.Model): season_name = models.CharField(max_length=30) country = models.CharField(max_length=30) class FruitSeason(models.Model): season = models.ForeignKey(Season, on_delete=models.CASCADE) fruit = models.ManyToManyField(Fruit) I have a form that lets me add Season and (multiple)Fruit details class FruitSeasonForm(forms.ModelForm): season_name = forms.CharField(max_length=30) fruit = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Add comma separated values'})) class Meta: model = FruitSeason exclude('fruit', 'season') I tried saving the list of fruits as individual records in the Fruit Model as well as season details in Season on Form post. views.py class seasonal_fruit(request): if request.method == 'POST': form = FruitSeasonForm(request.POST) if form.is_valid(): fruit_season_form = form.save(commit=False) season=Season.objects.create(season_name=form.cleaned_data['season_name'], country=form.cleaned_data['country']) fruit_season_form.save_m2m() form.save() form post does not save on both the models. How do I work around with it? Not sure where am I going wrong. Is it the modelling of those 3 models or something else. -
How to annotate a queryset with the difference between today & a DateField using ExpressionWrapper
I'm trying to do an annotation of the queryset based on a DateField as shown. I am using Django version 1.8.12 and MYSQL version 5.6.40. Tried following How to annotate a queryset with number of days since creation, but here its a DateTimeField. The comments below says "Changing it to Value(now.date(), DateField()) - F('creation_date__date'), doesn't work" The Model code is shown below: class Holding(models.Model): trans_date = models.DateField(_("Trans. Date"), null=False) ... And the annotate query that gives the wrong duration is shown below: today = timezone.now().date() testqs = Holding.objects.filter(id=1) myqs = testqs.annotate(duration = ExpressionWrapper( Value(today, DateField()) - F('trans_date'), output_field=DurationField())) And when i try to print, all I get is None for the duration. Difference printed for reference. for i in myqs: print i.duration, '-', today-i.trans_date None - 1224 days, 0:00:00 None - 1206 days, 0:00:00 None - 1144 days, 0:00:00 None - 1051 days, 0:00:00 None - 1045 days, 0:00:00 I expect the duration to be a timedelta values with the difference between today and trans_date and not None. -
Connect django project with mongodb
I am not getting any migrations for mongodb(no changes made when i am done with python manage.py migrate commmand) while i am using djongo in settings.py file of my django project. DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'student_db', #database_name } } -
Set up a redirect
There is a mixin in the view, where a slash is added to the url. It is necessary that when you open a non-existent page (for example, example.com/index), immediately throw 404, without 301 (so as not to add a slash at the end). Only a check on 404 status comes to mind, if there is one. Like if there is a page, then do not need to add a slash. If there is no such page, then to formally add a slash at the end (without a redirect). And if the status is 200, then okay, and if not, then throw 404. def is_normal_slash_count(url): temp_url = url slash_count = 0 while temp_url.endswith('/'): slash_count += 1 temp_url = temp_url[:-1] return (slash_count == 1, slash_count) def replace_bad_slash(url, slash_count): if slash_count == 2: return url.replace('//', '/') return url.replace('/'*(slash_count-1), '') def normalize_url(url): if len(url) > 1: if not url.endswith('/'): return url + '/' # replace the url like /contacts//// to /contacts/ good_slash, slash_count = is_normal_slash_count(url) if not good_slash: url = replace_bad_slash(url, slash_count) return url def is_bad_url(url): if len(url) > 1: good_slash, slash_count = is_normal_slash_count(url) if not good_slash: return True return False class RedirectMixinView: def dispatch(self, *args, **kwargs): url = self.request.path redirect_setting = RedirectSettings.objects.filter(url_from=url).first() if … -
Passing class to label from forms.py in ChoiceField/MultipleChoiceField
How can I pass a class to label in the field MultipleChoiceField in forms.py to my template. For example, I want my check box to look like this: <div class="custom-control custom-checkbox"> [...] <input type="checkbox" class="custom-control-input" id="customCheck1"> <label class="custom-control-label" for="customCheck1">Option 2</label> [...] </div> So I create a form that looks like this: class Form(forms.Form): field = forms.MultipleChoiceField(choices=MY_OPTION, widget=CheckboxSelectMultiple(attrs={'class': 'custom-control-input', 'label': 'custom-control-label'})) But in my template the form looks like this: <div class="custom-control custom-checkbox"> [...] <input type="checkbox" class="custom-control-input" label="custom-control-label" id="customCheck1"> <label for="customCheck1">Option 2</label> [...] </div> So the label goes to the input field, not the label. How can I add a label to the label field(<label></label>)? Any help will be appreciated. -
ModelForm has no model class specified. (value Error)
from django import forms from .models import Topic class NewTopicForm(forms.ModelForm): message = forms.CharField(widget=forms.Textarea(), max_length=4000) class meta: model = Topic fields = ['subject', 'message'] -
ModelForm validation in Django
I'm trying to validate two forms on one page with single submit button. I don't really mind using either forms.Form or forms.ModelForm knowing the difference. However, when I submit the form for validation all data is being discarded and I get This field is required shouting at me from all fields except the timeout field as that one is optional and defaults to 10. Please see my files: this view I'm using when trying to make it work with ModelForm class. When I'm trying to use just Form class I uncomment the lines and comment out the .save() lines: def index(request): if request.method == 'POST': form_tc = TestCaseForm(request.POST) form_ts = TestCaseSuiteForm(request.POST) if form_tc.is_valid() and form_ts.is_valid(): # TestCase.objects.create( # name=form_tc.cleaned_data['name'], # documentation=form_tc.cleaned_data['documentation'], # steps=form_tc.cleaned_data['steps'], # tags=form_tc.cleaned_data['tags'], # setup=form_tc.cleaned_data['setup'], # teardown=form_tc.cleaned_data['teardown'], # template=form_tc.cleaned_data['template'], # timeout=form_tc.cleaned_data.get('timeout', 10), # ) # # TestSuite.objects.create( # name=form_ts.cleaned_data['name'], # documentation=form_ts.cleaned_data['documentation'], # setup=form_ts.cleaned_data['setup'], # teardown=form_ts.cleaned_data['teardown'], # force_tags=form_ts.cleaned_data['force_tags'], # timeout=form_ts.cleaned_data.get('timeout', 10), # ) form_tc.save() form_ts.save() return redirect('/list') forms.py: class TestCaseForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Name'}), label='') documentation = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Documentation'}), label='') steps = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Steps'}), label='') tags = forms.CharField(widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter Tags'}), label='') setup = forms.CharField(widget=forms.TextInput(attrs={ … -
Filter select field in ModelForm by participant in tournament
i want to create game using forms like this siteaname.com/tournament/creategame. And then i have 2 select field team1 and team2. i have lots of team (500+) but a tournament include 10-16 teams so i want the teams participating in the tournament appear in the team selection section.Sso I can easily select team1 and team2 from only teams participating in the tournament instead of all teams. what do you suggest I do? forms.py class GameForm(models.ModelForm): ... def __init__(self, *args, **kwargs): super(GameForm, self).__init__(*args, **kwargs) self.fields["team1"].queryset =Team.objects.filter(tournament=tournamentslug)#this code is wrong views.py def creategame(request,tournamentslug): form=GameForm() ... context={ 'form':form, } return render(request,'gamecreateform.html',context) urls.py path('<str:tournamentslug>/creategame',creategame,name='create_game'), models.py class Team(models.Model): name=models.CharField(max_length=120,verbose_name="Takım ismi") class Game(models.Model): team1=models.ForeignKey(Team,on_delete=models.CASCADE,verbose_name='Team1',related_name='t1',null=True,blank=True) team2=models.ForeignKey(Team,on_delete=models.CASCADE,verbose_name='Team2',related_name='t2',null=True,blank=True) tournament = models.ForeignKey('Tournament', on_delete=models.CASCADE,related_name="gametournament",verbose_name="Tournament") class Tournament(models.Model): teams = models.ManyToManyField(Team,blank=True,related_name='t_teams',verbose_name="Teams") -
Django calculate percentage for population pyramid
I have a data set with population by gender and age groups, 0-4 men population, 0-4 women population etc. I tried calculate percantage in views.py but it didn't work well. so i want to it calculate one time in models.py and save it in my database. class Pyramid(models.Model): city = models.CharField(max_length=15) year = models.IntegerField(default=0) men_population_0_4 = models.IntegerField(default=0) women_population_0_4 = models.IntegerField(default=0) men_population_5_9 = models.IntegerField(default=0) women_population_5_9 = models.IntegerField(default=0) . . . men_population_90_over = models.IntegerField(default=0) women_population_90_over = models.IntegerField(default=0) def __str__(self): return '%s %s' % (self.city, self.year) so firstly i need calculate total men and women population then calculate percentage according to each of gender and age group in models.py and storage it to database. -
How to show category to user
I practice coding with html and django and I have a project "Movie Reviews" and I have some question. how to show category for user who often click that category? e.g You often like to chose Romantic category.Website should show romantic category to you when you come to this website again.(already login) sorry for my English.I'm beginner for English and Coding. Thankyou -
Django update form for users: set current user's group by default to the group choice in the form
In my website, Staff members can modify user's fields, and change their permission group. However, the group choice field is not set by default to the current user's group. I searched and tried something using init in the form but I get 'ManyToManyDescriptor' object has no attribute 'all'. N.B: User is assigned to only one permission group. views.py # Update status of user @login_required @group_required('Staff') def updateUserView(request, id): i = User.objects.get(id=id) if request.method == 'POST': form = UpdateForm(request.POST, instance=i) if form.is_valid(): user = form.save() user.groups.clear() if form.cleaned_data['group_name'] == 'Staff': user.is_staff = True else: user.is_staff = False # remove staff status is user is no longer a Staff member group = Group.objects.get(name=request.POST.get('group_name')) user.groups.add(group) user.save() messages.success(request, "User has been updated!") return redirect('accounts:users') else: form = UpdateForm(instance=i) return render(request, 'accounts/update_user.html', {'form': form, 'username': i, 'i': i.id})``` forms.py class UpdateForm(UserChangeForm): is_active = forms.BooleanField(required=False) Group = [('Viewers', 'Viewers'), ('Editors', 'Editors'), ('Creators', 'Creators'), ('Staff', 'Staff'), ] group_name = forms.ChoiceField(choices=Group) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'group_name', 'is_active', 'password',) def __init__(self, *args, **kwargs): super(UpdateForm, self).__init__(*args, **kwargs) self.initial['group_name'] = [User.groups.all()[0].name] -
Django Model error: Related model cannot be resolved
I'm creating a simple Django Model to use with Django Rest Framework. Suppose this model: from django.db import models class DeviceInfo(models.Model): device_id = models.IntegerField(primary_key=True) def __str__(self): return str(self.device_id) class CenterCommands(models.Model): device_object = models.ForeignKey( DeviceInfo, on_delete=models.CASCADE) command = models.CharField(max_length=512) def __str__(self): return str(self.device_object.device_id) class CenterCommandsRawData(models.Model): center_command = models.OneToOneField( CenterCommands, on_delete=models.CASCADE, primary_key=True) data = models.CharField(max_length=512) def __str__(self): return str(self.center_command.device_object.device_id) But whenever I'm trying to run python manage.py makemigrations deviceApp and python manage.py migrate, I get the following error: (myDjangoEnv) F:\Work\Vehicle Tracking System\Codes\Server\OVTSServer>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, deviceApp, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying deviceApp.0001_initial...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\Masoud\Anaconda3\envs\myDjangoEnv\lib\site-packages\django\core\management\base.py", line 83, in … -
Django: Trying to return sum of objects between two dates, instead returns sum of all objects
I have a Django table containing events, each marked with a timestamp. For testing purposes I put in some future dates (2020), but instead of returning the count of events between the two dates (0), this returns the sum of all of the events since the beginning of the DB (5). The Django request is as follows: queryset = queryset.annotate( value=aggregate_operation( f"{MESSAGEMODEL_ATTRIBUTE_NAME_IN_DEVICEMODEL}__press_count", filter=timestamp_filter ) ).values(DEVICE_REFERENCE_ATTRIBUTE_NAME, "value") I printed all of the variables involved: filter = (OR: ('messages__timestamp__gte', datetime.datetime(2020, 1, 2, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619ed0c18>)), ('messages__timestamp__lte', datetime.datetime(2020, 8, 30, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619e9bf60>))) value = Sum(F(messages__press_count), filter=(OR: ('messages__timestamp__gte', datetime.datetime(2020, 1, 2, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619ed0c18>)), ('messages__timestamp__lte', datetime.datetime(2020, 8, 30, 16, 9, 5, tzinfo=<django.utils.timezone.FixedOffset object at 0x7fe619e9bf60>)))) queryset = <QuerySet [{'name': '001 - CHANTIER1 - LIVRAISONS', 'value': 5}]> Why isn't this request behaving as expected? -
Couldn't find WSGI module deploying Heroku
Trying to deploy my app with this tutorial. Have a ModuleNotFoundError: No module named 'radio.wsgi' message. 2019-08-21T08:08:21.409841+00:00 app[web.1]: __import__(module) 2019-08-21T08:08:21.409849+00:00 app[web.1]: ModuleNotFoundError: No module named 'radio.wsgi' 2019-08-21T08:08:21.409960+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [10] [INFO] Worker exiting (pid: 10) 2019-08-21T08:08:21.441211+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [4] [INFO] Shutting down: Master 2019-08-21T08:08:21.441415+00:00 app[web.1]: [2019-08-21 08:08:21 +0000] [4] [INFO] Reason: Worker failed to boot. In some other questions people recomends python manage.py run_gunicorn but I have Unknown command: 'run_gunicorn' Procfile: web: gunicorn radio.wsgi --log-file - wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'radio.settings') application = get_wsgi_application() In only those files WSGI is mentioned. requirements.txt dj-database-url==0.5.0 Django==2.2.4 gunicorn==19.9.0 lxml==4.4.1 psycopg2-binary==2.8.3 pytz==2019.2 sqlparse==0.3.0 whitenoise==4.1.3 This is project structure ├── radio │ ├── db.sqlite3 │ ├── manage.py │ ├── player │ ├── radio │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── setup.py │ └── static ├── README.md ├── .gitignore ├── requirements.txt ├── runtime.txt └── Procfile -
How to add username in admin page who logged in when withdrawing an amount?
I have made a form to give an option for user to withdraw money. That data is saving in admin page but the problem is I have owner variable also, which I want that as the amount data is going to be saved in admin page the owner username should also be saved in admin, which shows who is desiring this amount? models.py from django.contrib.auth.models import User class Balance(models.Model): amount = models.DecimalField(max_digits=12, decimal_places=2) owner = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Balance' views.py @login_required def withdraw(request): if request.method == 'POST': form = WithdrawBalance(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, f'Your request has been submitted.') return redirect('index') else: form = WithdrawBalance() context = {'form': form} return render(request, 'nextone/withdraw.html', context) forms.py class WithdrawBalance(forms.ModelForm): class Meta: model = WithdrawPayment fields = ['payment'] -
Can't find static file in specified dir Django?
Here's my project tree: project1 ├─app1 ├─views.py ├─gg_task.py └─urls.py ├─static ├─1.json └─2.yaml ├─templates └─project1 ├─settings.py ├─urls.py And main codes below, I want to use 1.json in gg_task.py: project1.settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] import sys sys.path.append(os.path.join(BASE_DIR, "static")) app1.urls.py urlpatterns += [ re_path( r'^authenticate_gg/', AuthenticateGgView.as_view(), name='AuthenticateGg'), ] app1.views.py from .gg_task import GgManager class AuthenticateGgView(View): def get(self, request): manager_id = request.GET.get("manager_id", "5851848752") auth_url = GgManager(manager_id).get_auth_url() return redirect(auth_url) app1.gg_task.py class GgManager(object): _SCOPES = ['https://www.googleapis.com/auth/adwords'] def __init__(self, manager_id): self.manager_id = manager_id print(sys.path) # /path/to/static already in sys.path self.yaml_file_name = "{}.yaml".format(self.manager_id) self.json_file = "{}.json".format(self.manager_id) self.client = (google.ads.google_ads.client.GoogleAdsClient .load_from_storage(self.yaml_file_name)) I think I've already set /path/to/static in settings.py at start of django set-up, and I can directly use file 1.json and 1.yaml in gg_task. But I always get No such file or directory: '1.yaml', can you help me about this error? -
Django field clash with multiple abstract base clases
I am trying to define entity architecture that, if simplified, can be expressed like this: class M(models.Model): field_m = models.CharField(max_length=255) class Meta: abstract = True class A(M): field_a_1 = models.CharField(max_length=255) field_a_2 = models.CharField(max_length=255) class Meta: abstract = True class B(A): class Meta: abstract = True class C(A): class Meta: abstract = True class D(A): class Meta: abstract = True class DD(D): class Meta: abstract = True class X(B, C, DD): pass As you can see, X has some mixins (abstract entitites). Each of the mixin has their own custom logic implemented inside them. But ultimately all of them have 1 common parent- abstract class A. As far as I understand, this should work. And MRO resolution, indeed, works. However, when starting the project I get 2 errors per each field field A (that are inherited in X): X.field_a_1 : (models.E006) The field 'field_a_1 ' clashes with the field 'field_a_1 ' from model 'X'. X.field_a_1 : (models.E006) The field 'field_a_1 ' clashes with the field 'field_a_1 ' from model 'X'. X.field_a_2 : (models.E006) The field 'field_a_2 ' clashes with the field 'field_a_2 ' from model 'X'. X.field_a_2 : (models.E006) The field 'field_a_2 ' clashes with the field 'field_a_2 ' from model … -
Not able to run django for cache
I am not able to run django even any command like migrate, makemigrations. I am facing this below error ValueError: Related model 'blog.User' cannot be resolved I don't have any app with name 'blog'. Don't know where this app coming from. This is my settings.py file """ Django settings for pushnoty project. Generated by 'django-admin startproject' using Django 2.2.4. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '6rr$mj_@+*^5a#w=2-#koxj2nv2kpeb&0#jw0%-71fr@9@y)qc' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'pushnoty.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'pushnoty.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': … -
Variable form action="/"
There is a web application that collects data from different sites. The form on the home page is presented in the form of two fields where you can choose from several variants of languages and cities. When you press the search button, the result is displayed only for one pair of languages and cities, regardless of the selected variant in the form, as there is only one url in the form action='''. How to make a dynamic change of form action='' depending on the choice of variant in the form on the main page. I hope I have explained it clearly. Thank you for any help! https://ibb.co/VNcQqDp screenshot models.py from django.db import models class Page(models.Model): language = models.CharField(max_length=100) city = models.CharField(max_length=100) def __str__(self): return self.language views.py from django.shortcuts import render, redirect from .forms import PageForm from page.parsers.kiev_python_parser import * from page.parsers.kiev_javascript_parser import * from page.parsers.kiev_java_parser import * from page.parsers.kiev_c_parser import * def index_page(request): form = PageForm() return render(request, 'page/index_page_form.html', context= {'form':form}) def kiev_python(request): kiev_python_main() return render(request, 'page/kiev_python_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_javascript(request): kiev_javascript_main() return render(request, 'page/kiev_javascript_result.html', context={'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_java(request): kiev_java_main() return render(request, 'page/kiev_java_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) def kiev_c(request): kiev_c_main() return render(request, 'page/kiev_c_result.html', context= {'workua_data': workua_data, 'rabotaua_data':rabotaua_data}) … -
Resize a textfield in Django Admin
I'm trying to change the size of a TextField inside my Admin Panel. I've read this: Resize fields in Django Admin but no matter the number of cols and rows I choose for my models.TextField this just get smaller than the default size and doesn't change. admin.py : class FileOTRSAdmin(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'rows': 5000, 'cols': 400})}, } admin.site.register(tmodels.FileOTRS, FileOTRSAdmin) models.py : class FileOTRS(models.Model): content = models.TextField(_(u"Contenu")) -
How to reset mongo session ttl on each request in django?
I'm working on a django project and using mongo_sessions.session as SESSION_ENGINE. I want to set an expiration time to session but when I use MONGO_SESSIONS_TTL, it doesn't reset session on each request of user. How can I fix this? -
Salesforce as Idp unable to logout (django + pysaml2)
Related question: SP-initiated Single Logout not working with SalesForce I'm implementing single-sign-on service using Salesforce as identity provider. My app is now working well with single login. My goal is to make logout from my app (service provider) initiate log out in the identity provider (salesforce). For this purpose I send SAML2 request to Salesforce, however, I always get "We are unable to log you out." error. I searched logs of salesforce to find the cause of the error but didn't find any. In my app i use django, to generate saml I use pysaml2 lib. This is my code to generate logout request: req_id, request = saml2_client.create_logout_request( destination,"<entity-id>",name_id=NameID(text=request.user.email, format=NAMEID_FORMAT_TRANSIENT), expire=soon) # request = saml2_client.sign(request) rstate = saml2_client._relay_state(req_id) msg = http_redirect_message(request, destination, rstate) headers = dict(msg['headers']) location = headers['Location'] return HttpResponseRedirect(location) Generated xml: <ns0:LogoutRequest Destination="<logout_endpoint>" ID="<id>" IssueInstant="2019-08-21T06:44:29Z" NotOnOrAfter="2019-08- 21T06:49:29Z" Version="2.0" xmlns:ns0="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:ns1="urn:oasis:names:tc:SAML:2.0:assertion"> <ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid- format:entity">https://localhost:8000/saml2_logout/</ns1:Issuer> <ns1:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid- format:transient">username</ns1:NameID> </ns0:LogoutRequest> I'm not sure if params I pass to create_logout_request are correct, but I couldn't find any guide on what they have to be, currently entityid value is the url of my salesforce identity provider. -
How to grant temporary permissions to user?
In my application I want the user to re-enter their password before being able to complete a sensitive action such as editing their subscription. After successfully re-authenticating the permissions would be time-limited. I can't find django functionality that enables this, but since django seems to do just about everything else I thought it worth asking - can django do this or can it be configured to do this?