Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Retrieve the attribute list of records during querying process
I have model table so Tag and Article, class Tag(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=50) ... class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) ... I intent to retrieve the tags of a specified article and convert them to string: 1, Fetch the latest article: In [26]: articles = Article.objects.all() In [27]: len(articles) Out[27]: 41 In [29]: a = articles[40] In [30]: a Out[30]: <Article: Test new tags> 2, get it's tags queryset In [32]: tags = a.tags.all() In [32]: tags Out[32]: <QuerySet [<Tag: python>, <Tag: django>, <Tag: git>, <Tag: javascript>]> 3, convert queryset to a stringset In [36]: str_tags = ",".join([tag.name for tag in tags]) In [36]: str_tags Out[36]: 'python,django,git,javascript' Could I get the str_tags directly by making an query? -
How to edit user profile in Django
I'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email(to be checked if email already exisit), Name, user type, and password. below is the code for forms.py class ProfileForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'active', 'admin','email','user_type') def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(ProfileForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) # user.active = False # send confirmation email if commit: user.save() return user code for views.py def profile(request): user = User.objects.filter(email = request.user) # form = ProfileForm(user.values().first()) if request.method == 'POST' : form = ProfileForm(request.POST) if form.is_valid(): form.save(commit=True) form = ProfileForm(user.values().first()) # print(user) context = { 'object_list': user, 'form': form } return render(request, 'userpanel/profile.html',context) Thanks in advance -
How to count the distinct of model_set in Django?
I've looked into this question, but I think it's different. Let me explain a bit further. I have a serializer called DetailTrackSerializer to serialize my Track model, and I've nested a TaggedSerializer in DetailTrackSerializer. class DetailTrackSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(max_length=120) link = serializers.URLField(max_length=120) tagged_set = TaggedSerializer(many=True) artist = ArtistSerializer() class Meta: model = Track fields = ('id', 'artist', 'title', 'link', 'tagged_set',) class TaggedSerializer(serializers.ModelSerializer): tag = TagSerializer() class Meta: model = Tagged fields = ('tag',) class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('name',) Currently, this DetailTrackSerializer is returning a json like this { "tracks": [ { "id": 168, "artist": { "id": 163, "name": "Gob" }, "title": "Face the Ashes", "link": "", "tagged_set": [ { "tag": { "id": 1356, "name": "punk rock" } }, { "tag": { "id": 1356, "name": "punk rock" } }, { "tag": { "id": 1356, "name": "punk rock" } }, ... The list goes on, if there are 100 "punk rock" tag in this track, it will shows up 100 times. What I need is something like this { "tracks": [ { "id": 168, "artist": { "id": 163, "name": "Gob" }, "title": "Face the Ashes", "link": "", "tagged_set": [ { "tag": { "id": 1356, β¦ -
How to add table in Django admin without migrate command
I am using Django 1.10 , when I use Django admin but I can not find my table in admin setting , because I just add my table by SQL but not use Django migrate what should I do to add some table in Django admin -
Pandas from Django Aggregate Query
How do I convert aggregate qs into a DataFrame? for i in a: qs = Cashflow.objects.filter ( acct = i.id ).aggregate(Min('month'), Max('month'), Avg('value'), Count('month')) df = pd.DataFrame.from_records ( qs ) I get this error: If using all scalar values, you must pass an index Thank you. -
Update a table when other tables changed in Django ORM
Models.py # store the number of new Videos that added to a Album class Badge(models.Model): user_id = models.IntegerField() # the user you wanna inform album_id = models.IntegerField() count = models.IntegerField(blank=True, null=True) update_time = models.DateTimeField(blank=True, null=True) # a Album has several videos in it, and will be updated class Album(models.Model): title = models.CharField(max_length=100, default='', null=True) update_time = models.DateTimeField(blank=True, null=True) class Video(models.Model): title = models.CharField(max_length=100, default='', null=True) aid = models.ForeignKey(Album, on_delete=models.CASCADE, default='') update_time = models.DateTimeField(blank=True, null=True) Suppose in the database: Album table: 357 Learning_Django 2018-07-02 12:40:03.041558 Video table: 1 Install_Python 357 2018-07-02 12:40:03.041558 2 Install_pip 357 2018-07-02 12:40:03.041558 3 Install_Django 357 2018-07-02 12:40:03.041558 Now, two new video has been insert into the Video table: 1 Install_Python 357 2018-07-02 12:40:03.041558 2 Install_pip 357 2018-07-02 12:40:03.041558 3 Install_Django 357 2018-07-02 12:40:03.041558 4 Create_Django_Project 357 2018-07-13 08:40:03.041558 5 Define_Django_Models 357 2018-07-13 08:40:03.041558 What should I do to let this update reflect on Badge table (insert/update a record), like this: 1 001 357 2 2018-07-13 08:40:03.041558 It means that the Album #357 has been updated with 2 videos, and it will inform the user #001. Thanks for your help. -
Passing multiple arguments into Django's filter()
Based on user input I need to pass custom arguments into Django filter. Something along the lines of the following: q = Question.objects.all() a = q.filter(O_Stat__icontains = "Active", Ll_Name__icontains = "fruit") I tried setting the arguments to string: f = 'Operating_Status__icontains = "Active", Legal_Name__icontains = "fruit"' a = q.filter(f) Get a stack trace error. Is there a better solution then to pass every possible field into the filter ? #Like This a = q.filter(O_Stat__icontains = UserIn1, Ll_Name__icontains = UserIn2) Regards. -
run pipenv shell after moving to mac
I am new to macs, so maybe this is a mac os thing, I do pip3 install pipenv mkdir django I get: Installing collected packages: pytz, django Successfully installed django-2.0.7 pytz-2018.5 Adding django to Pipfile's [packages]... Pipfile.lock not found, creating... Locking [dev-packages] dependencies... Locking [packages] dependencies... Updated Pipfile.lock (85c883)! Installing dependencies from Pipfile.lock (85c883)... π ββββββββββββββββββββββββββββββββ 2/2 β 00:00:00 To activate this project's virtualenv, run pipenv shell. Alternatively, run a command inside the virtualenv with pipenv run. *********************** but when i pipenv install django pipenv shell results a8206602016e:test billybob$ pipenv shell Launching subshell in virtual environmentβ¦ Traceback (most recent call last): File "/Users/billybob/.pyenv/versions/3.6.5/bin/pipenv", line 11, in <module> sys.exit(cli()) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 722, in __call__ return self.main(*args, **kwargs) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 697, in main rv = self.invoke(ctx) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 1066, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 895, in invoke return ctx.invoke(self.callback, **ctx.params) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 535, in invoke return callback(*args, **kwargs) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/cli.py", line 664, in shell three=three, python=python, fancy=fancy, shell_args=shell_args, pypi_mirror=pypi_mirror File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/core.py", line 2163, in do_shell shell.fork_compat(*fork_args) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/shells.py", line 107, in fork_compat self.cmd, ['-i'], dimensions=(dims.lines, dims.columns), File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/pexpect/pty_spawn.py", line 204, in __init__ self._spawn(command, args, preexec_fn, dimensions) File "/Users/billybob/.pyenv/versions/3.6.5/lib/python3.6/site-packages/pipenv/vendor/pexpect/pty_spawn.py", line 276, in _spawn 'executable: %s.' % self.command) β¦ -
Django - looking for architectural advice for my project
First of all, I want to say that I'm really a novice with Django, and looking for some architectural advice for my project. I have a front-end template that looks like this: When a user clicks "Save" button, the information in the input fields needs to be saved into the database. I don't want my page to be refreshed when I click "Save" button, because only the information that belongs to the section will be sent. (however, if this needs some AJAX plugin, I can give it up on that for now. Primary importance for now is just connecting this front-end with PostgreSQL database) Ex: clicking Save in "Overall BHA" section will only save inputs in the "Overall BHA" into the database without refreshing the page. And the same process for "Drill Bit" section too. First, I need advice on models.py models.py from django.db import models # Create your models here. class BHA_overall(models.Model): drill_str_name = models.CharField(max_length=256) depth_in = models.IntegerField() depth_out = models.IntegerField() drilled = models.IntegerField() # ....... class BHA_drill_bit(models.Model): BIT_OPTIONS = ( ('PDC Drag'), ('Roller Cone'), ('other')) color = models.CharField(max_length=256, choices=BIT_OPTIONS, default='other') size = models.CharField(max_length=256) wob_max = models.CharField(max_length=256) # ....... I'm not sure if this is the best way to β¦ -
Pandas from Django .last() query
I can not create a dataframe when using only a single row - in this case using the .last() record for all the users. I am trying to get the very last row information. for i in a: qs = Cash.objects.filter ( id = i.id ).order_by ( 'month' ).last() df = pd.DataFrame.from_records ( qs ) or something like df = read_frame ( qs ) I get the following error: object of type 'Cash' has no len() Thank you very much. -
best web technolgies for a travel agency web app ?
The user will check radio buttons and select options that will be stored in the database. Front Techs ? Back-end Techs ? MySql , Postgresql or Firebase ? -
Django: DetailView URL with PK Issue
I'm new to Django and I am trying to build a church directory application to manage users (sheep) in churches (flocks). Everything seems to work until I add a CBV - DetailView for a model named ChurchMembers. I want to use the pk of the ChurchMember to create a DetailView for the member to have a profile. I get the following error message in the Debug: NoReverseMatch at /flock/members/ Reverse for 'view_member_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['flock/members/(?P<member_pk>\\d+)/$'] Here is my views.py (only displaying the DetailView in question): class view_member_detail(DetailView): model = models.ChurchMember template_name = 'flock_app/member_profile.html' context_object_name = 'member_detail' pk_url_kwarg = 'member_pk' I have a hunch that this is related to the way my urls.py file is setup. Maybe incorrect regex, or possibly bad ordering. urls.py below: app_name = 'flock_app' urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.user_login, name='user_login'), url(r'^logout/$', views.user_logout, name='user_logout'), url(r'^add_church/$', views.add_church, name='add_church'), url(r'^add_member/$', views.add_member, name='add_member'), url(r'^members/$', views.view_members_list.as_view(), name='view_members_list'), url(r'^members/(?P<member_pk>\d+)/$', views.view_member_detail.as_view(), name='view_member_detail'), url(r'^churches2/$', views.view_churches_list.as_view(), name='view_churches_list'), url(r'^(?P<pk>[-\w]+)/$', views.view_churches_detail.as_view(), name='view_churches_detail'), url(r'^update/(?P<pk>\d+)/$', views.update_church_detail.as_view(), name='update_church_detail'), url(r'^delete/(?P<pk>[-\w]+)/$', views.delete_church.as_view(), name='delete_church'), url(r'^home', views.home, name='home') ] Here is my call the DetailView from the HTML: <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" href="{% url 'flock_app:view_member_detail' pk=mem.member_pk %}">Sheep Profile</a> <a class="dropdown-item" β¦ -
Django Get Auth User pk to be saved in model after form submission
I am currently implementing Django's Auth Users. I am now attempting to create a form with two simple fields with the User's pk as the foreign key. For the model I have the following code for the ForeignKey: user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I then have a form class (forms.ModelForm) where I set the fields. I do not list the user field from the above model because I want that to be completed automatically when the user submits them form. Finally, I have a view with the following post method: def post(self, request): form = self.form_class(request.POST) if form.is_valid(): sub = form.save(commit=False) sub.save() return render(request, self.template_name, {'form': form}) Any input is greatly appreciated! -
Configure the records of model as unique not duplicate with each other
I have a tag model which relate to articles with many-to-many relationship: class Tag(models.Model): owner = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return self.name class Meta: ordering = ("id",) class Article(models.Model): tags = models.ManyToManyField(Tag, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) ... I want to make sure the tags are unique and not duplicate,but found it's difficult In [39]: article.tags.create(name="django", owner=article.owner) Out[39]: <Tag: django> In [40]: article.tags.create(name="django", owner=article.owner) Out[40]: <Tag: django> In [41]: article.tags.create(name="django", owner=article.owner) Out[41]: <Tag: django> In [42]: article.tags.all() Out[42]: <QuerySet [<Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>]> In [43]: Tag.objects.all() Out[43]: <QuerySet [<Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, '...(remaining elements truncated)...']> How to configure the recodes of Tag as unique? -
Django OAuth Toolkit error: duplicate key value violates unique constraint "oauth2_provider_accesstoken_pkey"
I'm trying to run a React Native app using a Django backend in a simulator. However, when I try to log in on the app, I get the following error from the Django development server: [17/Jul/2018 16:46:17] "GET /dashboard/login?next=/api/2/me/apn/ HTTP/1.1" 200 4588 (0.001) SELECT typarray FROM pg_type WHERE typname = 'citext'; args=None (0.004) SELECT "oauth2_provider_application"."id", "oauth2_provider_application"."client_id", "oauth2_provider_application"."user_id", "oauth2_provider_application"."redirect_uris", "oauth2_provider_application"."client_type", "oauth2_provider_application"."authorization_grant_type", "oauth2_provider_application"."client_secret", "oauth2_provider_application"."name", "oauth2_provider_application"."skip_authorization", "oauth2_provider_application"."created", "oauth2_provider_application"."updated" FROM "oauth2_provider_application" WHERE "oauth2_provider_application"."client_id" = '1rZrEiL8UpKI8wQjUrvDS3i4h536DdS9YbFwIhPq'; args=('1rZrEiL8UpKI8wQjUrvDS3i4h536DdS9YbFwIhPq',) (0.005) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" = 'kurt@hicleo.com'; args=('kurt@hicleo.com',) (0.050) INSERT INTO "oauth2_provider_accesstoken" ("user_id", "token", "application_id", "expires", "scope", "created", "updated") VALUES (2018, '77km8bPCu1iyDyMsZI2cDsi3vkmFb6', 1, '2018-08-16T23:46:37.800702+00:00'::timestamptz, 'read write', '2018-07-17T23:46:37.801418+00:00'::timestamptz, '2018-07-17T23:46:37.801431+00:00'::timestamptz) RETURNING "oauth2_provider_accesstoken"."id"; args=(2018, '77km8bPCu1iyDyMsZI2cDsi3vkmFb6', 1, datetime.datetime(2018, 8, 16, 23, 46, 37, 800702, tzinfo=<UTC>), 'read write', datetime.datetime(2018, 7, 17, 23, 46, 37, 801418, tzinfo=<UTC>), datetime.datetime(2018, 7, 17, 23, 46, 37, 801431, tzinfo=<UTC>)) Internal Server Error: /o/token/ Traceback (most recent call last): File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "oauth2_provider_accesstoken_pkey" DETAIL: Key (id)=(1042) already exists. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/kurtpeek/.local/share/virtualenvs/lucy-web-CVxkrCFK/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File β¦ -
django url without pk
I have been trying for too long now to get my urls working with my simple models and view. There is something I am definitely not understanding. I wish to create a url similar to: .../department/team, where I do not use the PK of department object but the name instead. My model looks like: class Department(models.Model): name = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return 'Department: ' + self.name class Hold(models.Model): name = models.CharField(max_length=50, blank=True, null=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) my view looks like: class IndexView(generic.ListView): template_name = 'index.html' context_object_name = 'departments_list' def get_queryset(self): return Department.objects.all() class DepartmentView(generic.DetailView): model = Department template_name="depdetail.html" lookup_url_kwarg = "name" my url looks the following: urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('(?P<name>)', views.DepartmentView.as_view(), name='depdetail') ] and finally my html: <h1> Hello there {{ object.text }} student</h1> </br> <b> Choose your team:<b> </br> however i keep getting page not found or must be slug or pk.. I hope someone can help me out so I can wrap my head around this. -
Validate username entered and user logged in are same django
User is Logged in and fills the form. user enters the username in a form. If the entered username doesn't match with username of logged in user raise error forms.py class iffc_one(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(iffc_one, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() fieldentered_username = self.cleaned_data['current_user'] if self.user != fieldentered_username: raise forms.ValidationError('Invalid user') class Meta: model = bookings_modelform models.py class bookings_modelform(models.Model): current_user = models.CharField(max_length=200) What am I doing wrong here! -
django - PIL handling jpg and png files
I have a function that handles uploaded jpg file but crashes when user upload png. How can I tweak (if possible) my function to also handle png files appropriately? from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile from sys import getsizeof image = self.cleaned_data.get("image") if not image: image = '' return image size = (145,145) im = Image.open(image) output = BytesIO() im.thumbnail(size) im.save(output, format='JPEG', quality=100) output.seek(0) image = InMemoryUploadedFile(output,'ImageField', "%s.jpg" %image.name.split('.')[0], 'image/jpeg', getsizeof(output), None) return image -
One combined model vs Two separated models with similar purpose
In my case, one User can subscribe to another User or Community. And, I can't decide, should a Subscription model be combined for both or should it be separated UserSubscription and CommunitySubscription Combined model will look like that: class Subscription(models.Model): date_subscribed = models.DateTimeField(default=timezone.now) date_unsubscribed = models.DateTimeField(null=True) subscriber = models.ForeignKey(User, related_name='subscriptions') author = models.ForeignKey(User, related_name='subscribers', null=True) community = models.ForeignKey(Community, related_name='subscribers', null=True) is_active = models.BooleanField(default=True) Two separated models will look the same except they'll contain only one of two fields author or community. Not both. The hardest and the most frequent query about Subscription is a subscriber's feed-page which displays Posts based on user`s subscriptions combined: class Post(models.Model): title = models.CharField(max_length=255) text = models.TextField() communities = models.ManyToManyField(Community) # NOTE: THIS IS M2M! author = models.ForeignKey(User) And, I just want to make it right in terms of performance and potential things that I do not see now but can face in future. So, Is there any pros and cons about separated UserSubscription and CommunitySubscription or combined Subscription model? How would you do and why? -
how to deal with two model forms (combined in one form in html) in Django
I have tow model forms (combined in one form in html). The following are those two model forms : class PostsForm(forms.ModelForm): class Meta: model = Posts fields = ['post_category', 'post_sub_category', 'post_title', 'post_detail', ] class CarsForm(forms.ModelForm): class Meta: model = Cars fields = ['price','year', 'odometer', 'car_make', 'car_model','car_image' ] the following is the view function: def post_ad(request): form_class = [PostsForm(), CarsForm(), ] template_name = 'path/to/template.html' if request.method == 'POST': form_class[0] = PostsForm(request.POST) form_class[1] = CarsForm(request.POST) if form_class[0].is_valid() and form_class[1].is_valid(): post_form = form_class[0].save(commit=False) car_form = form_class[1].save(commit = False) post_form.user = request.user post_form.save() # function to deal with multiple images def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('car_image') if form.is_valid(): # image section for f in files: instance= Cars(car_image=request.FILES['file']) instance.save() return self.form_valid(form) else: return self.form_invalid(form) car_form.save() return redirect('index') return render(request, template_name, {'form_class':form_class }) in the template I could display both forms in one html form and both of them have one single button. with no errors. However, when I submit the form I got the following error: kages/django/core/validators.py", line 349, in compare return a > b TypeError: '>' not supported between instances of 'int' and 'datetime.datetime' the error came from this line : if form_class[0].is_valid() and form_class[1].is_valid(): can β¦ -
Django - ManyRelatedManager object is not iterable when returning Object
I'm having problems to return my object after I add some items into my "countries" ManytomanyField. I can see my data being saved class CompanyProfileManager(models.Manager): @transaction.atomic def register_company(self, name, description, tag_name, email, is_private, uses_credits, pays_subscription, pool, facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title, countries, **kwargs): tag = Tag(name=tag_name, description=tag_name, is_active=True) tag.save() company = self.create_instance(name, description, email, is_private, uses_credits, pays_subscription, pool, facebook, twitter, web, country, videocall_doctor_to_patient, micro_type, can_move, fixed_percentage, fixed_price, fixed_tariff, instagram, subdomain, banner_description, banner_title) company.tag = tag company.save() for item in countries: company.countries.add(item) return company #Using Debug Mode, My project breaks right here I'm really lost, the only thing I've seen so far related to my problem is using .all() to get as a queryset -
Range for models.TextField() in Django
Will there be any range or something like how many characters will be stored in the models.TextField() in Django models? Looks like there is no particular range mentioned in documentation. Will the size just increases as we use the field? -
Allowing user to skip multi-factor authentication for 30 days from a device
I've inherited an app at my company (ReactJS/Django), and they've asked me to implement multi-factor authentication. I've got it wired up with django-mfa, and the authentication works great. Now, they've requested that if a user logs in with MFA, they will not be asked for MFA again on THAT device for 30 days. At first, I thought no problem. You can do it with a cookie or whatever as you would any persistent session, and instead of using that to keep the user logged in, you can use it to determine whether or not to ask for MFA verification. The obvious oversight I made in my haste is that theoretically you could have multiple users logged in to that same device. User A could log in with MFA. If you store a cookie with session information that allows User A to skip MFA, what happens when User B logs in? I don't really know any obvious way around this. Is there a straight-forward or conventional way to manage multiple user sessions in a browser, or an alternative approach to this problem I'm missing? -
Django - election of lesson year with election
When making a lesson selection, I would like to make a choice to show which year this lesson belongs to (eg 2011-2012, 2012-2013, 2014-2015). I want it to be automatically calculated instead of writing this selection field by hand. YEAR = ( (2011-2012, _(2011 - 2012)), (2012-2013, _(2012 - 2013)), (2013-2013, _(2013 - 2014)), ) models.py class Lesson(models.Model): department = models.ForeignKey(Department,on_delete=models.CASCADE) academician = models.ManyToManyField(Academician) l_code = models.CharField(verbose_name=_('Ders Kodu'), max_length=7) l_name = models.CharField(verbose_name=_('Ders AdΔ±'), max_length=45) e_year = models.CharField(verbose_name=_('EΔitim YΔ±lΔ±'), max_length=50,) def __str__(self): academician = '-'.join( [str(academician.a_fullname) for academician i self.academician.all()]) return '{department} - {academician} - {l_code}'.format(department=self.department.d_name, academician=academician,l_code=self.l_code) this selection field will be made in admin.py -
Call another model field in url django
My problem is have two models job and company and i want to get all jobs in this company My urls.py: url(r'^jobs/(?P<slug>[\w-]+)/$', views.job_at_company, name='job_at_company'), My views.py: def job_at_company(request, slug): return render(request, 'jobs.html') My models.py: class Company(models.Model): title = models.CharField(max_length=100, blank=False) slug = models.SlugField(blank=True, default='') city = models.CharField(max_length=100, blank=False) contact_info = models.CharField(max_length=100, blank=False, default=0) facebook = models.CharField(max_length=100, blank=True) twitter = models.CharField(max_length=100, blank=True) linkedin = models.CharField(max_length=100, blank=True) logo = models.ImageField(upload_to="logo", default=0) class Jobs(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(blank=True, default='') company = models.ForeignKey(Company, on_delete=models.CASCADE) price = models.IntegerField(default='') Description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) job_type = models.CharField(max_length=100, choices=(('Full Time', 'Full Time'),('Part Time', 'Part Time')),default='Full Time')