Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to extend custum user Model?
I would to create the new UserModel that be Custom from User Model django, so then added extended attribute and methods like Proxy model and One-To-One Link Model togather. I would to using Authentication and permission UserModel django to my defined UserModel for my two type Users that are my defined Admin and staff User. How to using just username and password for Authentication for My UserModels and my other custom fields How to create its and Fill with the ModelForm? -
Video link for registered users
I have a website in which we are now uploading course contents. I now want only authenticated users to access these contents. The video links should not open for other users. My server is on django on aws ec2 instance. How to achieve this? -
Is there a way to set meta data (Title and Description) for login_required pages?
Google is indexing my login_required pages, but it seems as though they are just pulling the title from the link that lead them to the page and then indexing the login form that the page redirects to? The meta description looks something like this: "Sign In. Don't have an account yet? Then please sign up. Login*. Password*. Remember Me. Forgot Password? Sign In. Search · About · Contact · FAQ · Privacy ..." Is there a way to set the meta data for these pages? Or should I just restrict Google from crawling them at all to keep from getting a penalty? -
How to load an image generated in other functions, output the code in the Django binary code
How to load image to bd, well i generate qr image(QRcode)when she is generated, i need to create a new record in bd, to save this image and code himslef This is my model class QRCode(models.Model): user = models.ForeignKey(UserProfile, blank=True, default=None) qr_code = models.CharField(max_length=120) qr_code_img = models.ImageField(upload_to="qr_code_img/", width_field="width_field", height_field="height_field") upcoming_show = models.ForeignKey(SectionUpcomingShow) width_field = models.IntegerField(default=270) height_field = models.IntegerField(default=270) is_active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "{0} - - {1}".format(self.user.username, self.is_active) class Meta: ordering = ["-timestamp"] verbose_name = 'QRCode' verbose_name_plural = 'QRCodes' @property def image_path(self): return os.path.abspath(self.qr_code_img) this is view to gen qrimg def qr_code_generator(hex_code, username, __show__id, __show__name__, __show__q, price): qr_code_generate_himslef = pyqrcode.create(hex_code) generate_name = ''.join(username + '_' + str(__show__id) + '_' + __show__name__ + '_' + str(__show__q) + '_' + str(price) + '.png').replace(" ", "_") qr_code_generate_himslef.png(generate_name, scale=6) print(qr_code_generate_himslef) return qr_code_generate_himslef when i print this function i got this QRCode(content=b'f40a03cb6026d68f0f83c43b47c9e388ed106848', error='H', version=5, mode='binary') this is my save view new_qr_code, created = QRCode.objects.get_or_create(user=get_user_profile, qr_code=hex_code, is_active=True, defaults={"user":get_user_profile, "qr_code":hex_code, "qr_code_img":qr_img, "upcoming_show":get_upcoming_show}) if not created: pass -
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>