Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form is not submitting (submit button not working)
I am using djnago form with angular and django fields but submit button is not working. What corrections are needed? plz help... <body ng-app="angNewsApp"> <form method='POST' action='' enctype='multipart/form-data'> {% csrf_token %} <div ng-controller="demoCtrl"> <h2>Multiple</h2> <input id="inputImage" name="file" type="file" accept="image/*" ng-model="imageList" image="imageList" resize-max-height="800" resize-max-width="800" resize-quality="0.7" resize-type="image/jpg" multiple="multiple" ng-image-compress/> <div> <img ng-src="{% verbatim %}{{item.compressed.dataURL}}{% endverbatim %}" ng-repeat="item in imageList" /> </div> <!-- just do a console.log of {{image1}} to see what other options are in the file object --> </div> <button type="submit">Submit</button> </form> </body> -
Data not getting inserted in db in django
Hi I am trying to select data from a dropdown list and then save it in Category model.There is no problem in retrieving the data but when i check it using Category.objects.all(), I get this <QuerySet [<Category: Category object>, <Category: Category object>, <Category: Category object>, <Category: Category object>]> models.py: from future import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): user = models.ForeignKey(User) category= models.CharField(max_length=100) views.py: def get_category(request): cname = request.POST.get("dropdown1") user = request.session.get('user') obj=Category(user_id=user,category=cname) obj.save() return HttpResponse("Registeration succesfull") With get_category i am trying to save entry selected from dropdown.It works fine but i guess nothing is being stored in the db. I tried running this Category.objects.get(category = "abc") I get this error: DoesNotExist: Category matching query does not exist. Can someone tell if this is not the right way to insert data in db. -
How to properly call a url that came from an object ID in django
I want to make a checkout page and also want to call a url which came from an object ID in Django. The products app has its own urls.py, My question is How do you properly call an object ID? . This is the url http://localhost:8000/products/1. I attempt to call it but it return some error. <button type="button" class="btn btn-primary"><i class="fa fa-shopping- cart"> </i> <a href="{% url 'products/1' %}"> Add To Cart </a> </button> urls.py-products url(r'^$', ProductListView.as_view(), name='products'), url(r'^cbv/(?P<pk>\d+)', ProductDetailView.as_view(), name='product_detail'), url(r'^(?P<id>\d+)', 'products.views.product_detail_view_func', name='product_detail_function'), main urls.py url(r'^products/', include('products.urls')), this is the error **Reverse for 'products/1' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []** -
Check user is active or not by using username and password
In recent Django version, authenticate() from django.contrib.auth will return None to non-active user. However, I wish to check if the user is active or not with only username and password. Any possible way to do so? -
Json Request from Node js to Django
I have code in node js const request = require('request-json'); var dataSend = {'data': "TESTS"} var client = request.createClient('http://127.0.0.1:8000/'); client.post('report/', dataSend, function(err, res, body) { return console.log(body['status']) }); and code in python in django 1.11. def report(request): print(request.POST.get('data')) return JsonResponse({'status': True}) When i send request Django receive it and return JsonResponse({'status': True}) and request code is 200. The problem is I can't receive and get {'data': "TESTS"} in python /django. Thx for help -
DJANGO - filter date range and each date by a time range
django model - class Readings(models.Model): val = models.FloatField(default=0) created_dt = models.DateTimeField() Now i want to select the rows between 2 date range , start date and end date and for each date i want to select rows only in a time range ( like 04:00 - 10:00), i tried created_dt__hour__gte but it doesnt seem to work. -
Get userID in django.dispatch.receiver
I am trying to use the ID of the django user for an action when a model is saved. For that I have a receiver as follows: @receiver(post_save, sender=ServersModel) def create_zabbix_host(sender, instance=None, created=False, **kwargs): if created: print(instance.name) print(kwargs) I can get the ServersModel name but I am unable to get the ID of the User am connected with. Is there a way to get the connected user id in the ServersModel receiver? I have tried the following solutions but in vain: Get current user log in signal in Django -
What is the role of __deepcopy__ in Python class and Django widgtet
First, I know how copy and deepcopy from copy module work for a list. I'm interested the role of __deepcopy special method inside a class. I need to create custom widgets in Django and I try to understand the python code behind. class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True # for data and time values def __init__(self, attrs=None): if attrs is not None: self.attrs = attrs.copy() else: self.attrs = {} def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj What is happening with deepcopy_ when I make an instance of Widget, or and instance of a subclass of Widget ? Looks like is making a shallow copy of attributes and the object itself , but what is the purpose ? -
Display messages from Django view during it's execution via Ajax
I'm working on a Django(1.10) project, I'm handling some forms via ajax to Django views.But my views are doing some executions in various steps for example authentication with a third party service => validate the user's added code => upload that code Now, I need to display some messages during execution to my template like when authentication has been done I want to display a message to the end user "Auth success" and same for other steps. I have googled a lot but couldn't find any solution. Any resource or library? Help me, please! Thanks in advance! -
Django Cannot load a template in the template path of INSTALLED_APPS
I'm using python 3.5.2 and django 1.11.6. My OS is win10. I cannot load my template in the installed_app path. I've created a file at "polls/template/polls/index.html". I've also add the app, polls, into INSTALLED_APPS and set APP_DIRS in TEMPLATES to True. I cannot figure out why django won't load the template in the INSTALLED_APPS template folder as the tutorial told me. I used the following code snippet to load the template in my view. def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) I got this TemplateDoesNotExist. I'm wondering that why django doesn't search the path, "polls/template". The paths searched by django are as following. django.template.loaders.app_directories.Loader: C:\Users\XXX\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\admin\templates\polls\index.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\XXX\AppData\Local\Programs\Python\Python35\lib\site-packages\django\contrib\auth\templates\polls\index.html (Source does not exist) My INSTALLED_APPS is as following. INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] My TEMPLATES setting is as following. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Should a function in a models.py ever reside outside of a class?
In my models.py, I have a couple classes, and a couple manager classes. I have some methods that are general methods used by the model, but not necessarily a part of it. For example: def profile_photo_upload_loc(instance, filename): return "profile_photo/%s/%s" % (instance.user, filename) class Profile(models.Model): profile_photo = models.ImageField( upload_to=profile_photo_upload_loc, null=True, blank=True, width_field='width_field', height_field='height_field', verbose_name='Profile Image', ) Is it okay to have standalone functions outside of classes in the models file? When is it appropriate and when should the functions be inside the class? -
Calculation in django models within certain field of certain item type
I have a table which has a field called first_year_estimate_total and second_year_estimate_total which needs calculation. The calculation is done with all items first_year_estimate and second_year_estimate based on the category(land_capital_items_type) class LandCapital(models.Model): land_capital_items_type = models.ForeignKey( LandCapitalItem, blank=True, null=True, related_name='land_capital') land_item = models.CharField(max_length=200, blank=True, null=True) first_year_estimate = models.DecimalField( decimal_places=2, max_digits=20, default=100.00) second_year_estimate = models.DecimalField( decimal_places=2, max_digits=20, default=100.00) first_year_estimate_total = models.DecimalField( decimal_places=2, max_digits=20, default=100.00) second_year_estimate_total = models.DecimalField( decimal_places=2, max_digits=20, default=100.00) Here first_year_estimate and second_year_estimate has to be filled by the user but first_year_estimate_total and second_year_estimate_total should be based on the calculation. For example if I have the following data land_capital_items_type with item1 CapitalItem1(land_capital_items_type) item1 100 200 item2 500 700 CapitalItem2(land_capital_items_type) item1 400 200 item2 600 300 Now the first_year_estimate_total of CapitalItem1 should be 600(100 of item1 and 500 of item2 first_year_estimate) and second_year_estimate_total of CapitalItem1 should be 900(200 of item1 and 700 of item2 second_year_estimate) Similarly with CapitalItem2 How can I do it so? -
Post action not working in form inside bootstrap popover
I am trying to save a url from an input field(form is inside bootstrap popover)but nothing happens when i click save button. This is my html code: <form name ="bform" method = "post" action = "{% url 'savebookmark' %}" class ="form-inline"> {% csrf_token %} <div class="form-group"> <input placeholder = "http://..." name = "url" class = "form-control" type = "text"> <button type = "button" class = "btn btn-danger">Save</button> </div> </form> This is views.py def save_bookmark(request): bmark = request.POST.get("url") user = user obj = UserBookmark(user_id=user,bookmark=bmark) obj.save() return HttpResponse("Data saved") This is urls.py urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$',views.register, name='register'), url(r'^login/$',views.login_view, name='login'), url(r'^register/success/$',views.register_success, name='register_success'), url(r'^category/$',views.get_category,name='getcategory'), url(r'^#/$',views.save_bookmark,name='savebookmark'), ] Please gide me on what am i doing wrong in this? -
Signin with django authentication from frontend
I have created a view which allows user to sign in. def signin(request): email = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=email, password=password) if user is not None: login(request, user) How should I verify the user is signed in when the user is accessing API that is needed user to be logged in first? The documentation shows that we can use request.user.is_authenticated is true or not to verify. However, I am not using django template but reactJS to send POST request. How should I do it? Should I include a User attribute in json body in POST request? -
Django: changes on css files doesn't load in heroku
I made a web page using Django and uploaded it in Heroku. I've encountered some minor setback on loading the css, js files in heroku for a while, now I've already fixed them(css/js are now loaded). Now the issue that I have encountered is that when updating my navbar styles in my scss file and compiled without any errors(local) and the changes I've made are showing. Now I've pushed my changes to my heroku app, it doesn't change at all. I've researched about the problem and took some of the solution but it doesn't work. In my local: enter image description here In my prod: enter image description here Here is my production.py: PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' My wsgi.py: from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.production") application = get_wsgi_application() application = DjangoWhiteNoise(application) I've followed this: https://devcenter.heroku.com/articles/django-assets#collectstatic-during-builds and also Two-scoops-of-Django-1.11 for best practices. -
What is the difference between AWSCLI and AWSEBCLI?
What is the difference between "AWS Command Line Interface" and "AWS Elastic Beanstalk Command Line Interface"? Do I need both to deploy a Django project through AWS Elastic Beanstalk? Thank you! -
Categories and SubCategories in Django
I was reading the code available in: Filter a "drop-down" django-form element based on a value selected before I was wondering to understand if I need also to select Fleet as a drop-down. How should I do? What are the changes to be done in this code? Lets say that we need to add another level like Location that will have to select the brand, the car and the fleet. -
Moving existing django app into django-tenant-schemas
I tried to find any docs on how to add existing simple django app into a django-tenant-schemas app, but I couldn't find one. could you please give me any url on docs on how to do it ? Sincerely -bino- -
Django with Postgresql Full Text Search Date and Time Input Type Error
Here is my current code: class EntryManager(models.Manager): def with_documents(self): vector = SearchVector('title', weight='A') + \ SearchVector('slug', weight='B') + \ SearchVector('content', weight='C') + \ SearchVector('category', weight='D') + \ SearchVector(StringAgg('tags__slug', delimiter=' ')) + \ SearchVector('chron_date') if SearchVector('chron_date') == "": SearchVector('chron_date') == None if SearchVector('clock') == "": SearchVector('clock') == None return self.get_queryset().annotate(document=vector) Here is my error: invalid input syntax for type date: "" LINE 1: ...| to_tsvector(COALESCE("ktab_entry"."chron_date", ''))) AS "... I first got this error on the prior version of my code, at which time I followed the advice posted here: http://kb.tableau.com/articles/issue/error-invalid-input-syntax-for-type-date-error-while-executing-the-query by adding the two if clauses at the end, but that didn't work. I have seen this answer on SO: Error on using copy Command in Postgres (ERROR: invalid input syntax for type date: "") but there are no spaces in my quotes. This question on SO invalid input syntax for type date: "" in django, postgresql? has no answer. FWIW, there actually is a value in both the chron_date and clock fields: 2017-11-02 & 14:41:00 respectively. I already tried changing datestyle() to no effect. I also added null=True on the models but still get the same error. Django 1.11.5, Postgresql 9.4, Python 3.6 on Ubuntu 16.04 -
Add ForeignKey field to default User without modifying it?
I am using the default User model, and created a custom model called Team. A user can only be on one team, but a team can have many users. Therefore, I must create the ForeignKey field within the User model. The thing is, I'm using the default User by simply importing User with from django.contrib.auth.models import User What is the easiest way of adding a ForeignKey field into the default User model? Or is there a way for me to add a ForeignKey field into Team, and swap the relationship between User and Team? -
Django CreateView messes up bootstrap-modal
Rather a curious problem: My modal works perfectly until I associate the template containing it with a CreateView! So for example if I change template_name in BrandCreateView to new_brand_form1.html, new_brand_form2.html will load perfectly in the modal. But as it stands now, when I click the button that triggers the modal, I get this. views.py: class BrandCreateView(SuccessMessageMixin ,generic.edit.CreateView): template_name = 'new_brand_form2.html' model = Brand fields = ['name'] def get_success_url(self): current_business = Business.objects.filter(owner=self.request.user).first() current_business.brands.add(self.object.pk) return reverse_lazy('index', kwargs={'pk': self.object.pk}) # pre assign-current business to the business field def get_initial(self): initial = super().get_initial() initial['business'] = Business.objects.filter(owner=self.request.user).first() self.business_name = initial['business'] return initial def form_valid(self, form): form.instance.user = self.request form.instance.business = self.business_name try: return super(BrandCreateView, self).form_valid(form) except IntegrityError: form.add_error('name' ,'You already have a brand by that name') return self.form_invalid(form) new_brand_form2.html: <div class="modal fade" tabindex="-1" role="dialog" id="createbrand"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Modal title</h4> </div> <div class="modal-body"> <form class="form-horizontal"> {{ form.as_p }} </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> -
Is this the right way to create a subscription for Braintree in Python using the API
In an effort to bring some clarity, I'm asking this question here and sharing what I've learned so far. First, if you want a simple, easy to develop transaction system, Braintree is it. Really easy, and plays very nicely with Django. However, the subscription side of things has not been so clear. So, I'm sharing some code to get feedback on and help streamline. First.. some assumptions. Work Flow The process for creating a subscription with the API is as follows: (please don't send me documentation on how to do it in the control panel. A very broad description of the Subscription workflow can be found here: https://developers.braintreepayments.com/guides/recurring-billing/create/python) Create a Client token with braintree.ClientToken.generate() Create a customer with braintree.Customer.create() that adds a payment method Get the customer id from the Customer.create() response Create a subscription with braintree.Subscription.create() passing in the new customer and the new customer's token called payment_method_token If you're wondering, this is Django and I'm trying to do this all in one view. Sample Code custy_result = braintree.Customer.create({ "first_name": self.request.POST.get('first_name'), "last_name": self.request.POST.get('last_name'), "company": self.request.POST.get('company_name'), "email": self.request.POST.get('office_email'), "phone": self.request.POST.get('office_phone'), 'payment_method_nonce': 'fake-valid-nonce', # for testing "credit_card": { "billing_address": { "street_address": self.request.POST.get('address'), "locality": self.request.POST.get('city'), "region": self.request.POST.get('state'), "postal_code": self.request.POST.get('postal'), } } }) … -
Validation errors don't appear in Django form
I am trying to create a form where the users will enter their emails. Typically the validation errors for email(empty field or not proper format) are displayed by the browser. Using the basic form example, everything shows correctly: <form action="/notify-email/add/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> In my case, if there are no validation errors I use an ajax request to save the email and show a modal with a thank you message.But if there are validation errors I can see them when only if I hover. Also, the modal is shown even if there are errors in validation. This is my models.py: from django.db import models class NotifyEmail(models.Model): email = models.EmailField(max_length=255) date_added = models.DateField(auto_now_add=True) time_added = models.TimeField(auto_now_add=True) def __str__(self): return self.email This is the form based on the model: from django import forms from landing.models import NotifyEmail class NotifyEmailForm(forms.ModelForm): class Meta: model = NotifyEmail fields = ["email"] def __init__(self, *args, **kwargs): super(NotifyEmailForm, self).__init__(*args, **kwargs) self.fields['email'].widget = forms.EmailInput(attrs={'placeholder': 'Email', 'required': True}) My views.py: from django.shortcuts import render from django.http import JsonResponse from .forms import NotifyEmailForm def add_notify_email(request): if request.method == "POST": form = NotifyEmailForm(request.POST) if form.is_valid(): form.save(commit=True) print("Email Added.") return JsonResponse({'msg': 'Data saved'}) else: … -
setting permission for only one object using Django-guardian and Flatpages
I'm trying to use Django-guardian to apply permissions to specific flatpages. we have a number of flatpages on our site, and in most cases the django-auth works for what we need. However, we want to add object level permissions to some of the flatpages and specific users. for example, i have a user YOUNGTEMP and i want to give this user access to edit a subset of the total flatpages we have on the site. I have installed Django-guardian, and using the shell given change_flatpage permissions to this user for the appropriate sites. this user has no other permissions at all, as i don't want them to see anything but this one site from the admin. I can verify by looking at the DB that the permissions are there, as well as that they appear in the admin when i log in as a SU. Why then when i log in as this user YOUNGTEMP does the admin site tell me i have no permissions to edit anything? I followed the excerpts from the readthedocs.io page here to assign permissions in the shell to make sure it wasn't a problem with my overridden admin, which looks like this: imports*... class … -
Download links of protecting file after completing payment process in Django apps
What is best method of giving download links of protecting file after completing payment process with stripe in Django apps? With Ajax Call or any other method?