Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django ajax call from template
I have a model: class ok(models.Model): name = models.CharField(max_length=255) project = models.CharField(max_length=255) story = models.CharField(max_length=500) depends_on = models.CharField(max_length=500, default='') rfc = models.CharField(max_length=255) I have model form. class okForm(ModelForm): class Meta: model = ok fields='__all__' I am getting first 3 fields: name, project, story user manual entry. Now I want to populate the last two fields with respect to third field using AJAX call from views function that will query to mysql database. I have a fucntion in views.py def get(self, request): name = request.GET.get('name') project = request.GET.get('project') story = request.GET.get('story') if name and project and story: try: obj = ok.objects.get(name=name, project=project, story=story) return JsonResponse(data={ 'depends_on': ok_obj.depends_on, 'rfc': ok_obj.rfc}, status=200) except ok.DoesNotExist: pass return JsonResponse(data={'error': 'bad request'}, status=400) How i will make the ajax call with the third value the user just filled, as he has not submitted the form yet . Kindly help. -
How to serializer the openstack.compute.v2.server.ServerDetail?
How to serializer the openstack.compute.v2.server.ServerDetail ? I use the openstacksdk for develop my own openstack app. But when I get the generator of my connection: user_conn = UserOpenstackConn() openstack_servers_gen = user_conn.conn.compute.servers() I can use the list() to convert the openstack_servers_gen to list: : [openstack.compute.v2.server.ServerDetail(OS-EXT-AZ:availability_zone=, key_name=None, hostId=, os-extended-volumes:volumes_attached=[], OS-SRV-USG:launched_at=None, OS-EXT-STS:vm_state=error, flavor={'id': '5c5dca53-9f96-4851-afd4-60de75faf896', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/flavors/5c5dca53-9f96-4851-afd4-60de75faf896', 'rel': 'bookmark'}]}, updated=2017-11-27T10:29:50Z, accessIPv4=, image={'id': '60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/images/60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'rel': 'bookmark'}]}, created=2017-11-27T10:29:49Z, metadata={}, links=[{'href': 'http://controller:8774/v2.1/233cf23186bf4c52afc464ee008cdf7f/servers/3db46b7b-a641-49ce-97ef-f17c9a11f58a', 'rel': 'self'}, {'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/servers/3db46b7b-a641-49ce-97ef-f17c9a11f58a', 'rel': 'bookmark'}], OS-DCF:diskConfig=MANUAL, id=3db46b7b-a641-49ce-97ef-f17c9a11f58a, user_id=41bb48ee30e449d5868f7af9e6251156, OS-SRV-USG:terminated_at=None, name=123456, config_drive=, accessIPv6=, OS-EXT-STS:power_state=0, addresses={}, OS-EXT-STS:task_state=None, status=ERROR, tenant_id=233cf23186bf4c52afc464ee008cdf7f), openstack.compute.v2.server.ServerDetail(OS-EXT-AZ:availability_zone=, key_name=None, hostId=, os-extended-volumes:volumes_attached=[], OS-SRV-USG:launched_at=None, OS-EXT-STS:vm_state=error, flavor={'id': '5c5dca53-9f96-4851-afd4-60de75faf896', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/flavors/5c5dca53-9f96-4851-afd4-60de75faf896', 'rel': 'bookmark'}]}, updated=2017-11-27T10:27:42Z, accessIPv4=, image={'id': '60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'links': [{'href': 'http://controller:8774/233cf23186bf4c52afc464ee008cdf7f/images/60f4005e-5daf-4aef-a018-4c6b2ff06b40', 'rel': 'bookmark'}]}, created=2017-11-27T10:27:41Z, metadata={}, links=[{'href': 'http://controller:8774/v2.1/233cf23186bf4c52afc464ee008cdf7f/servers/721467ac-440f-4784-b825-f6155c65abee', 'rel': 'self'}, {'href': 'http://controller:8774/233cf23186bf4c52afc464ee008 ....... But how can I make it to be serializable in my project? -
Create password protected zip file Python
I'm using following code to create password protected zip file, from a file uploaded by user, in my Python34 application using zipFile. But when I open the zip file from windows, it doesn't ask for the password. I will be using the same password to read zip files from python later on. What am I doing wrong? Here's my code: pwdZipFilePath = uploadFilePath + "encryptedZipFiles/" filePath = uploadFilePath if not os.path.exists(pwdZipFilePath): os.makedirs(pwdZipFilePath) #save csv file to a path fd, filePath = tempfile.mkstemp(suffix=source.name, dir=filePath) with open(filePath, 'wb') as dest: shutil.copyfileobj(source, dest) #convert that csv to zip fd, pwdZipFilePath = tempfile.mkstemp(suffix=source.name + ".zip", dir=pwdZipFilePath) with zipfile.ZipFile(pwdZipFilePath, 'w') as myzip: myzip.write(filePath) myzip.setpassword(b"tipi") -
Python suddenly stopped when matplot image was drawn
Python suddenly stopped when matplot image was drawn. I wanna show matplot image's table in index.html.Now I wrote in views.py def past_result(request): return render(request, 'index.html', {'chart': _view_plot(request)}) def _view_plot(request): dates = [20150805,20160902,20170823] heights = [5,6,3] df = pd.DataFrame() df['DATE'] = dates df['SCORE'] = heights col_width = 3.0 row_height = 0.625 font_size = 14 header_color = '#40466e' row_colors = ['#f1f1f2', 'w'] edge_color = 'w' bbox = [0, 0, 1, 1] header_columns = 0 ax = None if ax is None: size = (np.array(df.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height]) fig, ax = plt.subplots(figsize=size) ax.axis('off') mpl_table = ax.table(cellText=df.values, bbox=bbox, colLabels=df.columns) mpl_table.auto_set_font_size(False) mpl_table.set_fontsize(font_size) for k, cell in six.iteritems(mpl_table._cells): cell.set_edgecolor(edge_color) if k[0] == 0 or k[1] < header_columns: cell.set_text_props(weight='bold', color='w') cell.set_facecolor(header_color) else: cell.set_facecolor(row_colors[k[0] % len(row_colors)]) plt.show() return ax in index.html <img src="data:image/png;base64,{{ chart }}" width="700px" height="500px" alt="RESULT"/> When I read past_result method,Python suddenly stopped .I do not know why.Why does such a error happen? I read this url as reference How to save the Pandas dataframe/series data as a figure? .How should I fix this? -
YAML Exception . Invalid Yaml
I am trying to upload my Django rest framework application in AWS elasticbeanstalk. I followed the steps from here http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I did exactly what is mentioned there and ended up in an error on creating environment. WARNING: You have uncommitted changes. Creating application version archive "app-989c-171129_120334". Uploading TestApi/app-989c-171129_120334.zip to S3. This may take a while. Upload Complete. ERROR: InvalidParameterValueError - The configuration file .ebextensions/packag s.config in application version app-989c-171129_120334 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token found character '\t' that cannot start any token in "<reader>", line 6, column 1: ^ , JSON exception: Invalid JSON: Unexpected character (p) at position 0.. Update the configuration file. My files contains exactly same info as mentioned in the docs. .ebextensions\django.config :- option_settings: aws:elasticbeanstalk:container:python: WSGIPath: ebdjango/wsgi.py Where am I going wrong ? -
How can I get values checkbox django
How to get values from database in checkbox and then insert selected values in database MySQL . How can create my views form template ? Any help is greatly appreciated -
get_thumbnailer renders different image than source image
I'm using get_thumbnailer from the sorl-thumbnail package and the cached image that is rendered in the key value store (used in conjunction with S3 storage pointing to a bucket) is different image than the source (ie: image = ImageField(upload_to='images')) My use case is that I have images being uploaded from camera on mobile via a HTML5 <input type="file" accept="image/*" capture="camera">. For each image, a thumbnail is being produced via the get_thumbnailer method. From desktop and android uploads I have no issues, but apparently on iOS the image upload and generation via the get_thumbnailer is not consistent, for some mysterious reason which I have yet to determine. The url attribute that get_thumbnailer renders from one of the uploads from an iOS is a different image than the source image. I don't expect answers, but if you can give me some idea then that's good enough. Just say something and I will give you an up-vote. -
How to fix error on python django_auth_ldap
I have a problem! When I try to install django_auth_ldap on Windows x64, python 2.7 64. I get this error: C:\Program Files (x86)\Microsoft Visual C++ Build Tools>pip install D:\django_auth_ldap-1.3.0b3-py2.py3-none-any.whl Processing d:\django_auth_ldap-1.3.0b3-py2.py3-none-any.whl Collecting python-ldap>=2.0; python_version < "3.0" (from django-auth-ldap==1.3.0b3) Using cached python-ldap-2.5.2.tar.gz Requirement already satisfied: django>=1.8 in c:\python27\lib\site-packages (from django-auth-ldap==1.3.0b3) Requirement already satisfied: setuptools in c:\python27\lib\site-packages (from python-ldap>=2.0; python_version < "3.0"->django-auth-ldap==1.3.0b3) Installing collected packages: python-ldap, django-auth-ldap Running setup.py install for python-ldap ... error Complete output from command c:\python27\python.exe -u -c "import setuptools, tokenize;file='c:\users\dmisss\appdata\local\temp\pip-build-rle0oc\python-ldap\setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record c:\users\dmisss\appdata\local\temp\pip-wl8mnc-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py file Lib\ldap.py (for module ldap) not found file Lib\ldap\controls.py (for module ldap.controls) not found file Lib\ldap\extop.py (for module ldap.extop) not found file Lib\ldap\ldapobject.py (for module ldap.ldapobject) not found file Lib\ldap\schema.py (for module ldap.schema) not found creating build\lib.win-amd64-2.7 copying Lib\ldapurl.py -> build\lib.win-amd64-2.7 copying Lib\ldif.py -> build\lib.win-amd64-2.7 copying Lib\slapdtest.py -> build\lib.win-amd64-2.7 creating build\lib.win-amd64-2.7\ldap copying Lib\ldap__init__.py -> build\lib.win-amd64-2.7\ldap copying Lib\ldap\async.py -> build\lib.win-amd64-2.7\ldap creating build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls__init__.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\deref.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\libldap.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\openldap.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\ppolicy.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\psearch.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\pwdpolicy.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\readentry.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\sessiontrack.py -> build\lib.win-amd64-2.7\ldap\controls copying Lib\ldap\controls\simple.py -> build\lib.win-amd64-2.7\ldap\controls copying … -
How to combine django-modeltranslation and django-reversion apps?
Question: how to combine django-modeltranslation and django-reversion apps? I have next problem: in models.py file I registered Slide model which has head field. This field has several other fields for translation like head_ru, head_kz, head_en. I set these fields in translation.py and settings.py files. In Slide table in DB has all this fields. Also I show all this fields I show in form where user can edit data. When user submit the form django-reversion create version only for head field and ignore other fields. How to fix this problem? models.py: from django.db import models import reversion @reversion.register() class Slide(models.Model): head = models.CharField(verbose_name='Title', max_length=200, blank=False,) translation.py: from modeltranslation.translator import TranslationOptions from modeltranslation.translator import translator from .models import Slide class SlideTranslationOptions(TranslationOptions): fields = ('head',) translator.register(Slide, SlideTranslationOptions) settings.py: LANGUAGES = ( ('ru', 'Russian'), ('en', 'English'), ('kz', 'Kazakh'), ) -
Getting ValueError While Trying to Create Category in Django
I am a beginner in Django. I am trying to add an option for adding category in my Django blog. However, I am getting this error: ValueError: invalid literal for int() with base 10: 'category' Here the codes that I have used in models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse #from tinymce import HTMLField #from froala_editor.fields import FroalaField from redactor.fields import RedactorField class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Category(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) title = models.CharField(max_length=250, verbose_name="Title") class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts') content = RedactorField(verbose_name=u'Text') publish = models.DateTimeField(default=timezone.now) category = models.ForeignKey(Category, verbose_name="Category", default='category') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # The Dahl-specific manager. class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') name = models.CharField(max_length=80) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = … -
Facebook Messenger Bot - Invalid URL button fields for List Template
I have been working to send a list to user containing some data. I am following facebook's doc to setup my request payload. However, I am getting the following error: {'error': { 'message': '(#100) Invalid URL button fields provided. Please check documentation for details.', 'type': 'OAuthException', 'code': 100, 'error_subcode': 2018125, 'fbtrace_id': 'GZFFcM+j5e/'}} Here is my JSON Payload: {'recipient': {'id': 'MY_MESSENGER_ID'}, 'message': {'attachment': {'type': 'template', 'payload': {'template_type': 'list', 'top_element_style': 'compact', 'elements': [{'title': 'Hello 1', 'subtitle': 'Subtitle 1', 'buttons': [{'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}], 'default_action': {'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}}, {'title': 'Hello 2', 'subtitle': 'Subtitle 2', 'image_url': 'https://cdn-images-1.medium.com/1*Vkf6A8Mb0wBoL3Fw1u0paA.jpeg', 'buttons': [{'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}], 'default_action': {'title': 'View', 'type': 'web_url', 'url': 'https://www.medium.com/', 'messenger_extensions': 'false', 'webview_height_ratio': 'full', 'fallback_url': 'https://www.medium.com/'}}]}}}} I have checked, re-checked it multiple times. PLUS, I have sent the facebook's example json from the doc but I have got the same reply. Please take a look and let me know where I am stuck! This is my end url: "https://graph.facebook.com/v2.6/me/messages?access_token=" Thanks in advance! -
Add field to model dynamically and still work with migrations Django >= 1.10
Using Django v1.10 I found this comprehensive answer regarding having dynamic model and fields in Django https://stackoverflow.com/a/7934577/80353 As the answer is starting to show its age, I am hoping to garner some more updated answers. At the same time, my scope is slightly different from the original poster of the question which that answer belonged to. I will state my scope as below: Right now, I have models and fields defined by me the developer. But the user wants to be able to add new fields when they need to. I have been using django-migrations as a way to propagate changes. I prefer to continue to use postgres and continue to still have migrations for these user-defined fields. So that it's easy for me to troubleshoot in case the user did something wrong. Not all models will allow users to dynamically add fields. Only a select few models which I deem okay will allow dynamic fields. By default, when the user defines the field, there are only 4 kinds: integer, decimal, text, varchar. All are default nullable and blankable. The length will also be set default. Essentially, the user cannot define the length or the nullable, blankableness. The user also … -
Django File Upload ,can't add file field using form from instance object
I need to save a file upload object, but in two views... First views can save without problem, but the second i get nothing change in my object I have a models.py class file_upload(models.Model): x= models.FileField() y = models.FileField() I have forms.py class form_upload(ModelForm): class Meta: model = file_upload widgets={ 'x': FileInput(attrs={'class': 'form-control'}), class form_upload_2(ModelForm): class Meta: model = file_upload widgets={ 'y': FileInput(attrs={'class': 'form-control'}), I have created an objects, also have uploaded a file on "x", i need to add file on "y" using form_upload_2 this is my views.py data_upl_instance = file_upload.objects.get(id=1) form = form_upload2(request.FILES,request.POST,instance=data_upl_instance) if request.method == "POST": if form.is_valid(): print(form.cleaned_data['y']) form.save() mydata['form'] = form return render(request, "status.html", mydata) this is my status.html <form action="" method="post" enctype="multipart/form-data" class="form-horizontal">{% csrf_token %} <div class="alert alert-danger"> {{ form }} </div> <button type="submit" class="btn red">Upload</button> </div> </form> After i clicked submit, the result is Printed "None" on terminal Form is valid but nothing change, file cant be uploaded -
django 1.11 html "href" doesn't work with template url
My urls.py urlpatterns = [ url(r'^index', views.index, name='index'), my views.py def index(request): return render(request, 'index.html', {}) index.html <ul> <li><a href="{% url 'all_contacts' %}"></a>All Contacts</li> </ul> My page with the href hyperlink not working The source: So I had a look at https://www.w3schools.com/tags/att_a_href.asp and it indicates that relative paths only work if it's pointing to a file. Not sure what I'm missing here? -
Django: How to use audit-log as decorator using cassandra
**models.py** class Mydata(DjangoCassandraModel): name = columns.Text(primary_key=True) email = columns.Text() password = columns.Text() creation_date = columns.DateTime(default=datetime.datetime.today()) modified_on = columns.DateTime(default=datetime.datetime.now) **views.py** class UsersViewSet(viewsets.ViewSet): def list(self, request): queryset = Mydata.objects.all() if request.GET.get('name'): queryset = queryset.filter(name=request.GET.get('name')) serializer = CheckSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): serializer = CheckSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) I am new to django and I want to know how could I make a function of auditing in views.py to use that function as decorator on list and create function. Please help. -
python django: views, models and forms in directories
django 1.11 python 3.x I have been trying to breakout models, views and forms into folders. I started out with models and it seemed to work. Changing views.py to views/index.py is stumping me. I have seen posts on this and I think that I am setting the __init__.py files correctly but makemigrations still yells at me about views/Profile.py. File "/home/me/AppBase/MyApp/Members/urls.py", line 3, in <module> from . import views File "/home/me/AppBase/MyApp/Members/views/__init__.py", line 1, in <module> from .Profile import * File "/home/me/AppBase/MyApp/Members/views/Profile.py", line 7, in <module> from MyApp.Members.models.Profile import * ImportError: No module named 'MyApp.Members' the file structure MyApp |-- Members | |-- __init__.py | |-- account_adapter.py | |-- admin.py | |-- apps.py | |-- forms | | |-- ProfileForm.py | | |-- __init__.py | |-- models | | |-- Profile.py | | |-- __init__.py | |-- tests.py | |-- urls.py | `-- views | |-- Profile.py | |-- __init__.py views/__init__.py is: from .Profile import * views/Profile.py is: from django.contrib import messages from django.core.exceptions import * from django.shortcuts import redirect from django.shortcuts import render from MyApp.Members.models.Profile import * def create_profile(user): pass def profile(request): if not request.user.is_authenticated: return redirect('/account/login') try: profile = Profile.objects.get(user=request.user) messages.add_message(request, 1, "have profile") except ObjectDoesNotExist: messages.add_message(request, 1, "create profile") … -
404 error when filtering URL for key arguments with django rest framework generic views
Basically I'm following a tutorial on how to filter for results through url regular expressions for my rest api. I'm looking to go to /api/v1/users/1/goals to get a list of the goals associated with a user. I've scoured the django rest framework docs and numerous tutorials and can't get this to work. I'm getting a 404 error that the url I'm requesting does not exist. myapp.views.py class ListCreateUser(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = serializers.UserSerializer class RetrieveUpdateDestroyUser(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = serializers.UserSerializer class ListCreateGoal(generics.ListCreateAPIView): queryset = Goal.objects.all() serializer_class = serializers.GoalSerializer def get_queryset(self): return self.queryset.filter(user_id=self.kwargs.get('user_pk')) class RetrieveUpdateDestroyGoal(generics.RetrieveUpdateDestroyAPIView): queryset = Goal.objects.all() serializer_class = serializers.GoalSerializer urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/v1/users', include('dataStoreApp.urls', namespace='users')), ] myapp.urls.py urlpatterns = [ url(r'^$', views.ListCreateUser.as_view(), name='user_list'), url(r'(?P<pk>\d+)/$', views.RetrieveUpdateDestroyUser.as_view(), name='user_detail'), url('r^(?P<user_pk>\d+)/goals/$', views.ListCreateGoal.as_view(), name='goals_list'), url('r^(?P<user_pk>\d+)/goal/(?P<pk>\d+)/$', views.RetrieveUpdateDestroyGoal.as_view(), name='user_goal_detail'), ] myapp.serializers.py class GoalSerializer(serializers.ModelSerializer): class Meta: model = Goal fields = ('id', 'user_id', 'name', 'amount', 'start_date', 'end_date', ) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'id', 'password') read_only_fields = ('id', ) extra_kwargs = {'password': {'write_only': True}} myapp.models.py class Goal(models.Model): class Meta: verbose_name_plural = 'Goals' user_id = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) NAME_CHOICES = ( ("Goal 1", "Goal 1"), ("Goal 2", "Goal 2"), ("Goal 3", "Goal 3"), ) name = models.CharField(max_length=100) … -
Django Dyanmic form: presentation and information collections
I have a complex form: <<forms.py>> class AttributeOptionForm(forms.Form): option_name = forms.CharField(label="Attribute Option") class AttributeForm(forms.Form): attr_name = forms.CharField(max_length=100, label="Attribute Name") attr_options_list = [AttributeOptionForm(), AttributeOptionForm()] class ProjectForm(forms.Form): name = forms.CharField(max_length=250, label="Name") attr_form_list = [AttributeForm()] ProjectFrom holds at least one AttributeForm (which may grow on runtime) and each AttributeForm holds at least two AttributeOptionForm (which may also grow on runtime). You may think of any AttributeForm as a question with multiple answers (AttributeOptionForm), which I want the user to fill in. This is how I present the ProjectForm. <<project_form.html>> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ form.name.errors }}</span> </div> <label class="control-label col-sm-2">{{ form.name.label_tag }}</label> <div class="col-sm-9">{{ form.name }}</div> </div> {% for attr_form in form.attr_form_list %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ attr_form.att_name.errors }}</span> </div> <label class="control-label col-sm-2">{{ attr_form.attr_name.label_tag }}</label> <div class="col-sm-9">{{ attr_form.attr_name }}</div> {% for option in attr_form.attr_options_list %} <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ option.option_name.errors }}</span> </div> <label class="control-label col-sm-2">{{ option.option_name.label_tag }}</label> <div class="col-sm-9">{{ option.option_name }}</div> {% endfor %} </div> {% endfor %} </form> In the form, in addition, there are an 'add_attribute_option' buttons (per attribute), 'add_attribute' button, and 'submit' button. How do I collect the data in my views.py file? … -
I am not able to initialize selectpicker in my vue js?
$('.selectpicker').selectpicker('refresh') This is done to initialize the selectpicker. When I run this is in console of chrome.. the dropdown list appears. So, in vuejs I added this code in mount(). But nothing is happening.. I have asked another question regarding the same and did not got an answer. Is there any way to initialize the same. My front end is html and vuejs and backend in python Django.. I am stuck or last two days and did not get anything new. Is there any way to initialize the same? -
Django-Leaflet Map not appearing in detailview
I am trying to use leaflet to display a map on one of my detail view pages on my django website. I am not receiving any errors when loading the page but the map does not appear. Settings: """ Django settings for crowdfunding project. Generated by 'django-admin startproject' using Django 1.11.6. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '_=@ti6j%*!5fcg-c#=f29yy7-unusuk*)oi7neew#k8==8rgz8' # 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', 'application.apps.ApplicationConfig', 'leaflet' ] 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 = 'crowdfunding.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['./templates',], '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 = 'crowdfunding.wsgi.application' LEAFLET_CONFIG = { 'DEFAULT_CENTER': (0, 0), 'DEFAULT_ZOOM': 16, 'MIN_ZOOM': 3, 'MAX_ZOOM': 18, } # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES … -
Auto populate custom user model if field exists in another table/model
As a newbie if my logic or thought process is incorrect please help direct me. I'm attempting to auto populate a field in my custom user model with a 1 or a 0 if the formattedusername exists in another model/pre-existing database table with the following signal, but i can't seem to get it to work correctly: @isthisflag def is_this(self, is_this): if cfo.ntname is user.formattedusername: return 1 else: return 0 I have a custom User model like the following: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) is_this = models.BooleanField(default=False) USERNAME_FIELD = 'username' I then have another model we'll call cfo that has a list of formattedusernames with the ntname field as a FK to formattedusernames. class cfo(models.Model): ntname = models.OneToOneField(settings.AUTH_USER_MODEL,db_column='CFO_NTName',primary_key=True, serialize=False, max_length=11) class Meta: managed = False db_table = 'cfo' If ntname exists as the User who logs with their LDAP authentication I want to place a 1 in the User.is_this field. -
How can I know where the request.user from?
How can I know where the request.user from ? I have a TestRequestUserAPIView: class TestRequestUserAPIView(View): def dispatch(self, request, *args, **kwargs): result = super(TestRequestUserAPIView, self).dispatch(request, *args, **kwargs) return result def get(self, request): user = request.user # this line I get the user (who access the API) return HttpResponse("ok") When it execute this line user = request.user. I can get the request user(who request this API). I want to know how the user generate in request, why I request this API in browser like Chrome, I the request will have the user property? Does it through the cookie ? or some token (In my test project, I logined. But I did not put the token to the request when access the API, still get the user in backend reqest.user)? -
'NoneType' object has no attribute 'rsplit'
I'm not sure how to track down this error: I'm running a django app on Python 3.4 in AWS. I re-deployed a couple of hours ago and discoverd this error while trying to fix an error with environmental variables. I'm not sure where to start, or where I could have gone wrong. It seems to have something to do with mail, and while I did recently mess around with some mail code, commenting out such code did nothing to resolve the problem or change the error. [Wed Nov 29 01:34:08.382512 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] Traceback (most recent call last): [Wed Nov 29 01:34:08.382537 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/handlers/exception.py", line 42, in inner [Wed Nov 29 01:34:08.382541 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] response = get_response(request) [Wed Nov 29 01:34:08.382559 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/utils/deprecation.py", line 136, in __call__ [Wed Nov 29 01:34:08.382562 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] response = self.get_response(request) [Wed Nov 29 01:34:08.382579 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] File "/opt/python/run/venv/local/lib/python3.4/site-packages/django/core/handlers/exception.py", line 44, in inner [Wed Nov 29 01:34:08.382582 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] response = response_for_exception(request, exc) [Wed Nov 29 01:34:08.382599 2017] [:error] [pid 8768] [remote 172.31.5.39:46384] File … -
Django Queryset : Remove 'u'
how to remove 'u' from Django Queryset. Let say i have result from my QuerySet <QuerySet [u'MANAGER']> Hot to remove the <QuerySet [u' ']> so that i got the result as MANAGER only. -
custom authenticate function does not accept third argument
trying to write my own custom authentication backend using the following as a guideline: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#writing-an-authentication-backend I want to implement the authenticate function with the following elements: username password verification_code I define the function as follows: def authenticate(self, username=None, password = None, verification_code = None): ... I however only get a value for username and password not however for verification_code. The login form looks as follows: <form id="login-form" method="POST"> {% csrf_token %} ... <input id="user_name" type="text" class="form-control" name="username" placeholder="Email Address" required="" autofocus="" /> <input id="password" type="password" class="form-control" name="password" placeholder="Password" required=""/> <input id="verification_code" type="text" class="form-control" name="verification_code" placeholder="Verification Code" required=""/> <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button> </form> Any help would be much appreciated :)