Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use Django as backend and Javascript as frontend for web development? What limitation will it be?
I am very new to web development. I've some experience in Python but not in web development. Also, I've learned the basics, i.e. syntax etc, about Javascript, Html, CSS. I want to develop a website some sort like a forum. So I am wondering can I do it with only Javescript (maybe using Angular) as frontend and Python (Django) as backend. Is this achievable? What kind of limitation may I encounter? Or can I just use Node.js as backend instead of Django? I really don't wanna spend extra time to learn PHP. Appreciated! -
How to Set Initial Data as list For Inline Model Formset in Django
Friends, a big help please I have a formset that is created in the CreateView function CartItemFormset = inlineformset_factory(Cart, CartItem, can_order = True, fields = '__all__') Now I need to transfer data to this formset as the initial data before saving this formset. But this data is a list of values. First of all, we create a copy of the main form, check it and save it. self.form = CartForm(request.POST) if self.form.is_valid(): self.new_cart = self.form.save() items = Item.objects.filter(slug__in=cart_items.keys(), is_visible=True, price__gt=0) Now we create a copy of the formset and it’s necessary to transfer the initial data to the formset. This is a reference to the record of the main model and the values of the list of items. Thus, in each form of the formset, there must be a reference to the record of the main model and one of the elements of the list of items. But how to do that??? self.formset = CartItemFormset(request.POST, instance = self.new_cart, initial = [{‘cart’: self.new_cart, ‘item’: items}]) But it does not work! Maybe there should be something to sort out in a cycle or something like. Please, help me. -
Integrate Paypal IPN with Django
I have integrated Paypal IPN payment method in my Django project. I am using django-paypal django package. I am able to make payments using sandbox and it goes well but I don't get the transaction details back in my application for future reference (i.e. transaction ID, date, reference details etc.). I am sending below parameters while initiating payment. paypal_dict = { "business": "xxxxxxxx@mail.com", "amount": subscriptions.price, "item_name": subscriptions.name, "invoice": subscriptions.invoice_no, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return_url": request.build_absolute_uri(reverse('subscriptions:return_url')), "cancel_return": request.build_absolute_uri(reverse('subscriptions:cancel_return')), "custom": "premium_plan", # Custom command to correlate to some function later (optional) # "landing_page": "billing", "paymentaction": "authorization", "first_name": company_profile.company_name, "last_name": "", "address1": company_profile.address_1, "address2": company_profile.address_2, "city": company_profile.city, "country": company_profile.country, "state": company_profile.state, "zip": company_profile.zip_code, "email": company_profile.email, "night_phone_a": company_profile.work_phone } I read that IPN keeps sending response but not sure if I have missed to set any parameter. Your valuable input will help us a lot. Thanks in Advance!!!!! -
Why can't I make DateTimeField data?
I wrote in models.py from django.db import models import uuid import random class User(models.Model): uu_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.IntegerField(null=True) regist_date = models.DateTimeField(auto_now=True) random_id = random.randint(1000,9999) @property def composite(self): return ''.join([str(self.uu_id), '_', str(self.regist_date), '_', str(self.random_id)]) in views.py def response(request): user = User() composite_id = user.composite print(composite_id) When I print out composite_id in print(composite_id),it is like f07c164e-2ce1-43aa-8bbf-75342b69c88d_None_8727 .I cannot understand why DateTimeField is None because UUIDField can be gotten. I wanna use DateTimeField 's data in composite_id.So how should I fix this?What should I write it? -
Django Form Field name Changing- Class Based View
In order to change the name in the form label in Django class-based view, I have to write this code into get_context_data ctx['form'].fields['dob'].label = 'Date of Birth' This changes dob to Date of Birth in form. Suppose there are 10 fields like this in the model. Is there a better way to change the name of all the form fields instead of writing 10 line of code? -
How save User data in OneToOneField | Django?
I have two models(User and Profile). In Profile model as you can see I have idx field which I use for sorting. In my project I show list of profiles and admin can sorting them by drag and drop. For thats why I use idx. Also this field is invisible and admin dont change its value manually. Question: How edit User data by profile id. As I said before I show list of profiles. Right now I have edit form where I show user data by profile id. Problem raise when I try to submit form after changes. models.py: # -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.dispatch import receiver from django.db.models.signals import post_save, post_delete class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) idx = models.IntegerField(verbose_name='Field for sorting, default=0, blank=True,) class Meta: ordering = ['idx', 'pk'] db_table = 'user_profile' @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() @receiver(post_delete, sender=Profile) def delete_user(sender, instance=None, **kwargs): try: instance.user except User.DoesNotExist: pass else: instance.user.delete() forms.py: from django import forms from django.contrib.auth.models import User class UserForm(forms.ModelForm): class Meta: model = User fields = '__all__' views.py: class UserEditView(UpdateView): template_name = 'users/edit_user.html' form_class = UserForm model = User def get(self, … -
Sending mail works in manage.py shell, but not in running app
I'm attempting to send an email to the site admins using django.core.mail.mail_admins when a comment is submitted via a view. I have a method on my Comment model called send_notification_email: from django.db import models from django.core.mail import mail_admins class Comment(models.Model): comment = models.TextField() time_received = models.DateTimeField() def send_notification_email(self): mail_admins( f'New Comment (id = {self.id})', f'Comment {self.id}, received at {self.time_received}: {self.comment}', ) The view creates an instance of Comment, saves it to the database, then calls send_notification_email(). When that happens, I get the following error: Traceback (most recent call last): File "/home/conda/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/conda/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/conda/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/conda/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/radio-website/main/views.py", line 56, in comments ) File "/home/radio-website/main/models.py", line 33, in send_notification_email [settings.SERVER_EMAIL], File "/home/conda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 56, in send_mail fail_silently=fail_silently, File "/home/conda/lib/python3.6/site-packages/django/core/mail/__init__.py", line 36, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND) File "/home/conda/lib/python3.6/site-packages/django/utils/module_loading.py", line 20, in import_string module = import_module(module_path) File "/home/conda/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked … -
Django: login link to appear only when a user is logged in
I am making an app in django in which i have used the django built in authentication system. Both login and logout links are present in the navbar. I want to make the logout link appear only when the user has logged in and not at all times. How do i do that? code snippet of project/urls.py: urlpatterns = [ url(r'^login/$', views.login, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.logout, {'next_page': '/home'}), ] code snippet of login.html; <div class="container"> <section id="content"> {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form action="{% url 'login' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <h1>Login Form</h1> <div class="imgcontainer"> <img src="{% static 'student/patient.jpg' %}" alt="Avatar" class="avatar"> </div> <div class="username"> {{ form.username.label_tag }} {{ form.username }} </div> <div class="password"> {{ form.password.label_tag }} {{ form.password }} </div> <div class="submitb"> <input type="submit" value="Log In" name="mybtn"> </div> <div class="resetb"> <input type="submit" value="Reset"> <a href="#forgotpwd">Forgot password?</a> </div> <input type="hidden" name="next" value="{{ next }}" … -
Unknown field specified for Model - datetime
I have this model: class Schedule(models.Model): name = models.Charfield(max_length=250) due_date = models.DateTimeField() I have also tried providing a default value for the due date but it also produces the error. I have this generic view: class ScheduleCreate(CreateView): model = Schedule fields = ['name', 'due_date'] PS: I have tried to changed due_date to CharField and it worked propely. I think the cause of the problem is the date time. How can this be solved? -
Django templates iterate model fields with indices
I have the follow model: class UserProfile(...): ... photo1 = models.URLField() photo2 = models.URLField() photo3 = models.URLField() photo4 = models.URLField() photo5 = models.URLField() And in the Create/Update template, I have to write five copies of the following div for file1 to file5: <div> Photo 1: {% if userProfileForm.instance.file1 %} <a href="{{ userProfileForm.instance.file1 }}" target=_blank>View</a> {% endif %} <input type=file name=file1> {% if userProfileForm.instance.file1 %} <a href="{% url 'account:deletePhoto' userProfileForm.instance.id %}">Delete</a> {% endif %} </div> Is there a way to iterate field file<i>? {% for i in '12345' %} <div> Photo {{ forloop.counter }}: ... </div> {% endfor %} -
Django - display all products created by a user
I have built a product app where a logged in user can create products by filling out a form. There is a products page that lists all products created by all users. When a user clicks on the profile link they will see a list of products they have created. When a user is logged in their username appears in the nav bar (this will be relevant further down this post). I want to create a page where visitors can can view products by user. I created this view: def designs_by(request, username): user = get_object_or_404(User.objects, username=username) products = Product.objects.filter(user=user) return render(request, 'designs_by.html', {'user':user,'products': products}) with this url: url(r'^designs_by/(\w+)/$', views.designs_by, name='designs_by'), which works, for the most part, but when a visitor clicks on the link to view the products by a user, the users profile link appears in the nav bar. The link won't work but I have no clue why it appears. Yeah, an odd one. -
Error Dockering Django with Webpack_Loader
Getting a stack of errors concluding to "ImportError: No module named webpack_loader". I have a Django app created that I'm trying to Docker using Gunicorn. My Dockerfile and start.sh are in a root directory alongside another directory called approot. In approot is everything you'd expect to see from running django-admin startproject. My wsgi.py file is in a directory called app inside of approot. Here is my... requirements.txt: Django>=1.8 gunicorn==19.6.0 Dockerfile: #Dockerfile # FROM directive instructing base image to build upon FROM python:2-onbuild # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 # CMD specifies the command to execute to start the server running CMD ["/start.sh"] start.sh: #!/bin/bash echo Starting Gunicorn. cd approot exec gunicorn app.wsgi:application \ --bind 0.0.0.0:8000 \ --workers 3 My settings.py includes: INSTALLED_APPS = [ ..., 'webpack_loader' ] WSGI_APPLICATION = 'app.wsgi.application' WEBPACK_LOADER = { 'DEFAULT': { 'CACHE': not DEBUG, 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': join(PROJECT_ROOT, 'webpack-stats.json'), 'POLL_INTERVAL': 0.1, 'TIMEOUT': None, } } error stack is $ docker run -it -p 8000:8000 app Starting Gunicorn. [2017-10-31 02:23:31 +0000] [1] [INFO] Starting gunicorn 19.6.0 [2017-10-31 02:23:31 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) [2017-10-31 02:23:31 +0000] [1] … -
How to represent value which have same field name in Django?
How to represent two columns which have the same name in Django? I have designed views and template below. However, the second and third column didn't show. Here is the my raw query cursor = connection.cursor() query = str("SELECT\n" " MG.valData,\n" " MG0.valData as value1,\n" " MG1.valData as value2,\n" " FROM\n" " T_USER AS TU\n" " LEFT JOIN M_GENERAL AS MG\n" " ON MG.Cd='002'\n" " LEFT JOIN M_GENERAL AS MG0\n" " ON MG0.Cd='001'\n" " LEFT JOIN M_GENERAL AS MG1\n" " ON MG1.Cd='001'\n") cursor.execute(query) row = dictfetchall(cursor,) return row Here is template {% for item in table_data %} <tr> <td>{{ item.MG.valData|default_if_none:"" }}</td> <td>{{ item.MG0.valData|default_if_none:"" }}</td> <td>{{ item.MG1.valData|default_if_none:"" }}</td> </tr> {% endfor %} I also tried used the alias like item.value1 and item.value2 in template. But it still showed blank values. Does anyone knows the mistakes? Thank you in advance. -
'str' object is not callable Am I wrong to assign User to method wrong?
I wanna print out composite_id in views.py. I wrote in response method like from django.shortcuts import render from .models import User def response(request): user = User() composite_id = user.composite(User) print(composite_id) return render(request, 'response.html') in models.py from django.db import models import uuid import random class User(models.Model): uu_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.IntegerField(null=True) regist_date = models.DateTimeField(auto_now=True) random_id = random.randint(1000,9999) @property def composite(self): return ''.join([str(self.uu_id), '_', str(self.regist_date), '_', str(self.random_id)]) I really cannot understand why this error happens because I do not think I assign string somewhere. But I think ,maybe am I wrong to assign User to method wrong? But I think argument of views.py's composite method should be User bacause models.py's self = User.How should I fix this?What should I write it? -
Call A Django View Without Refreshing The Page
Here's the view that updates the timestamp of a model in database whenever it's called, def data(request): new = Data.objects.filter(user=request.user) new.update(timestamp=timezone.now()) return HttpResponse('') This view is related to this URL, url(r'^go/$', views.data, name='data') Everything is fine, but how can I call this view & update the database without refreshing the page? -
Django Rest Framework: Filtering in Read/Write Related Field
I have Users and Groups, where Groups are a PrimaryKeyRelatedField on Users. When retrieving a User, I only want to show the Groups that it has in common with the current users. For example, suppose user_1 belongs to group_1, and user_2 belongs to group_2. If user_1 pings my LIST USERS endpoint I want to get: [{'groups': [1], 'username': 'user_1'}, {'groups': [], 'username': 'user_2'}] Note that although group_2 exists, it is not listed under user_2's groups, because user_1 is not in it. Thoughts so far: Overloading to_representation seems like it will just change how the group is shown in the list of groups, not whether it is shown at all There are some guides about how to filter the writable group choices here, meaning that user_1 couldn't, for instance, add itself to group_2 There are some guides about how to filter for a read-only field I could combine the above two and do a read-only field and a write-only field, as suggested here for a different problem, but I'd rather not. I don't see any guides on how have a single read/write RelatedField filtered by the current user. Any ideas? My code: # serializers.py, vanilla from django.contrib.auth.models import User, Group from … -
Translation instructions in Wagtail don't work
trying to create multiple language fields in wagtail based on the instructions. My base.py file contains: MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware', ] USE_I18N = True My blog/models.py file looks like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import RichTextField from wagtail.wagtailadmin.edit_handlers import FieldPanel from wagtail.wagtailsearch import index from django.utils import translation class TranslatedField(object): def __init__(self, en_field, es_field): self.en_field = en_field self.es_field = es_field def __get__(self, instance, owner): if translation.get_language() == 'es': return getattr(instance, self.es_field) else: return getattr(instance, self.en_field) class BlogIndexPage(Page): intro = RichTextField(blank=True) content_panels = Page.content_panels + [ FieldPanel('intro', classname="full") ] subpage_types = ['blog.BlogPage'] class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) #body_en = RichTextField(blank=True) #body_es = RichTextField(blank=True) body = TranslatedField( 'body_en', 'body_es', ) search_fields = Page.search_fields + [ index.SearchField('intro'), #index.SearchField('body'), ] content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('intro'), #FieldPanel('body', classname="full"), ] parent_page_types = ['blog.BlogIndexPage'] When I run ./manage.py makemigrations it runs fine, but when I run ./manage.py migrate, I get the error: django.db.utils.ProgrammingError: column "body_es" of relation "blog_blogpage" already exists How do I resolve this error? -
django-auth-ldap AUTH_LDAP_FIND_GROUP_PERMS not working
Problem As far as I can tell, django-auth-ldap is doing everything I need given my configuration. Except that it's unable to establish a mapping from ldap groups to django groups. I have a group in ldap called dev, i.e., cn=dev. I also have a group in django called dev. When I login with my user in Django (uid=fkilibarda), django-auth-ldap is able to get my firstname, lastname, and email, but it fails to add me to the dev group. Debugging django_auth_ldap.backend line: 203 def get_group_permissions(self, user, obj=None): if not hasattr(user, 'ldap_user') and self.settings.AUTHORIZE_ALL_USERS: _LDAPUser(self, user=user) # This sets user.ldap_user if hasattr(user, 'ldap_user') and (user.ldap_user.dn is not None): return user.ldap_user.get_group_permissions() else: return set() I've found that hasattr(user, 'ldap_user') is always false. Thus, user.ldap_user.get_group_permissions() never runs, which is why the group mapping is never established. I just don't understand the significance of the above. Why doesn't user have the ldap_user attribute? Configuration AUTH_LDAP_SERVER_URI = "example_server" AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=group,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=posixGroup)', ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_USER_FLAGS_BY_GROUP = { 'is_active': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_staff': 'cn=dev,ou=group,dc=example,dc=example,dc=com', 'is_superuser': 'cn=dev,ou=group,dc=example,dc=example,dc=com', } AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=people,dc=example,dc=example,dc=com', ldap.SCOPE_SUBTREE, '(uid=%(user)s)' ) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_ALWAYS_UPDATE_USER = True Version django-auth-ldap==1.2.14 python3 -
Determining IsAuthenticated in DRF Using DRF-JWT to retrieve a list testing with Postman
So I'm using DRF JWT for my authentication. User submits credentials, and if valid, responds with a JWT that is stored in sessionStorage. Any time the user navigates the protected routes, the JWT /api/auth/refresh to refresh the token if it is still valid. Anyway, moving on from authentication and onto protected routes where data is retrieved based on if the user is IsAuthenticated according to DRF. The problem is I am having difficulty figuring out how to determine IsAuthenticated in DRF without having the user supply credentials again. I should mention right now I am testing with Postman. API URL: /api/help/questions I have the view as: class GetQuestionsAPIView(ListAPIView): queryset = Help.objects.all() serializer_class = GetQuestionsSerializer permission_classes = [IsAuthenticated,] The serializer is: class GetQuestionsSerializer(ModelSerializer): class Meta: model = Help fields = '__all__' def validate(self, data): return data I have a valid token from /api/auth/signin/. I'm trying to pass it on to the /api/help/questions/ route to retrieve the list of questions. GET /api/help/questions/ doesn't work because it wants credentials. Authentication credentials were not provided. GET /api/help/questions/ with Content-type: application/json and 'Authorizationand the token in the header also saysAuthentication credentials were not provided.` Thought maybe it should be POST since I submitting credentials and … -
how to I log the subaddress of HTTP request
I am trying to make a simple webserver. For example, when try to visit website wordpress/mywebsite/thisiswhatIwanttorecord the backend will record the thisiswhatIwanttorecord part in a db or even just txt file and return a standard error page no matter what the suburl is. Does anyone know how to do this in Python Django? Seems like it could be as easy as changing a config file for example in Tomcat. Log all HTTP requests of Tomcat Server? -
Django Model Form: data query from selected primary key
This is my models.py file from django.db import models # Create your models here. class SchoolInfo(models.Model): school_name=models.CharField('School Name', max_length=100) built_date=models.DateTimeField('Built Date') def __str__(self): return self.school_name class TeacherName(models.Model): schoolinfo=models.ForeignKey(SchoolInfo, on_delete=models.CASCADE) teacher_name=models.CharField('Teacher Name', max_length=100) teacher_subject = models.CharField('Subject Name', max_length=100) teacher_contact_number = models.CharField('Phone Number', max_length=100) date_published = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.schoolinfo class Student(models.Model): std_name=models.CharField('Student Name ', max_length=200) CLASS_NAME=( ('6','SIX'), ('7','SEVEN'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ('Ex-10','EX-Ten'), ) std_class_name=models.CharField('Class Name', max_length=7, choices=CLASS_NAME) std_roll_number=models.IntegerField('Roll Number') GENDER=( ('Male','Male'), ('Female','Female'), ) std_gender=models.CharField('Gender', max_length=7, choices=GENDER) GROUP=( ('Science','Science Group'), ('B.Studies','Business Group'), ('Arts and Humatics','Arts and Humatics'), ('General','General'), ) std_group=models.CharField('Group', max_length=17, choices=GROUP) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.std_name class ExaminationName(models.Model): examination_name=models.CharField('Examination Name ', max_length=100) exam_date=models.DateTimeField('Exam Date: ') pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.examination_name class MainSubject(models.Model): main_subject_name = models.CharField('Main Subject Name', max_length=100) main_subject_code=models.DecimalField('Main Subject Code', decimal_places=0, default=0, max_digits=10) subject_full_marks = models.DecimalField('Subject Full Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.main_subject_name class SubjectName(models.Model): mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subject_name=models.CharField('Subject Name', max_length=100) subject_full_marks=models.DecimalField('Subject Full Marks',max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) def __str__(self): return self.subject_name class SubjectPart(models.Model): #mainsubject = models.ForeignKey(MainSubject, on_delete=models.CASCADE) subjectname = models.ForeignKey(SubjectName, on_delete=models.CASCADE) subject_part_name=models.CharField('Subject Part', max_length=100) subject_part_full_marks = models.DecimalField('Full Marks', max_digits=6, decimal_places=0, default=100) subject_part_pass_marks = models.DecimalField('Pass Marks', max_digits=6, decimal_places=0, default=100) pub_date = models.DateTimeField('Published', auto_now_add=True) … -
Save Data Without Refreshing The Page
I have a view that refresh the time of a model in database whenever it's called. def data(request): new = Data.objects.filter(user=request.user) if new: new.update(timestamp=timezone.now()) This view is related to the URL, url(r'^data/$', views.data, name='data') So, how can I call this view & update the time in database when user click a URL or a button without refreshing the page? -
Query for Many to Many Fields in Django
I have these classes - class DocumentType(models.Model): type_id = models.AutoField(primary_key=True) name = models.CharField('type name', max_length=200) class MetaData(models.Model): metadata_id = models.AutoField(primary_key = True) name = models.CharField('metadata name', max_length=200, unique=True) description = models.TextField('description') class DocumentTypeMetaData(models.Model): documentType_id = models.ManyToManyField(DocumentType,) metadata_id = models.ManyToManyField(MetaData,) required = models.BooleanField(default=False) For example, a DocumentType value of 'Photo' would have Required Metadata of 'Decade' and 'Orientation'. In the DocumentTypeMetaData class I would like to have a def __str__(self) function that returns something like the following in the admin page - Photo: (Decade, Photo Type) required The format is not critical, I just want to know which metadata is required. Currently, all that is displayed is DocumentTypeMetaData object on the admin page. I am struggling with how to write the queries for this function. Thanks! Mark -
javascript increment value of hidden input and pass it to django view
I am trying to increment the number of inputs in a form when a user clicks on a map. It should pass coordinates of the clicked spot to the input. There are two options to add an input to the form: 1. By clicking on 'Add' button (then we receive an empty input). 2. By clicking on the map (then we receive an input with coordinates). To increment the number of inputs I use a hidden input which stores the value of additional points. When I use the 'Add' button, everything works correctly. I get the empty input and when I reload the page I am able to see just created fields. But when I add this inputs by clicking on a map, after reloading the page I lose all of the inputs. However I see that the value of hidden input was incremented but the fields don't show up on the page. I have tried using ajax to solve it but it didn't work... or I don't know how to use it properly. This is my code: <h2> New Trip: </h2> <form action="{% url 'trips:new' %}" method="post"> {% csrf_token %} <div id="trip-form"> {% for field in trip_form %} {{ … -
OAuth2 Client (Python/Django)
I'm creating a single sign-on (SSO) service using Python, Django, Django Rest Framework and Django OAuth Toolkit (https://github.com/evonove/django-oauth-toolkit). The SSO service will be a central, stand-alone application providing user identity services (granting access to user information as an OAuth2 Protected Resource). Django OAuth Toolkit helps to implement the OAuth2 Authorisation Server. Is there a similarly good quality Django or Python library that can help in implementing the OAuth2 Client (see following diagram snippet taken from https://tools.ietf.org/html/rfc6749#section-1.2)? +--------+ +---------------+ | |--(A)- Authorization Request ->| Resource | | | | Owner | | |<-(B)-- Authorization Grant ---| | | | +---------------+ | | | | +---------------+ | |--(C)-- Authorization Grant -->| Authorization | | Client | | Server | | |<-(D)----- Access Token -------| | | | +---------------+ | | | | +---------------+ | |--(E)----- Access Token ------>| Resource | | | | Server | | |<-(F)--- Protected Resource ---| | +--------+ +---------------+ (I expect the main use case wouldn't be a problem to implement myself, but if a good library provides handling of corner cases, errors, retries and is well tested, then it would be a shame to reinvent.) Thanks, Paul.