Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change type column in django-tables2
Fill table mydata.append({ 'bool_access': True, 'path': path }) table = mytable(data=mydata) ----> render table Table class mytable(tables.Table): path = tables.Column(verbose_name='My path') # path = tables.LinkColumn('page_web', args=[A('path')],verbose_name='My path') bool_access = "" class Meta: attrs = {'class': 'table table-bordered table-striped table-condensed'} sequence = ('path') Wanted I want that if a add a row in my data with bool_access at "True" that the column type for path is tables.LinkColumn and else if bool_access at "False" the column type is tables.Column. Thanks in advance for any help. -
django makemigration alterfield without any change
On every makemigrations altered estate field while don't change that field. what's reason of it?! class Announcement(OJModel): owner = models.ForeignKey('user.User', verbose_name=_('Announcement Owner'), on_delete=models.CASCADE, related_name='owner_announcements', null=True, blank=True) title = models.CharField(max_length=300, default='', verbose_name=_('Title')) description = models.TextField(max_length=3000, default='', verbose_name=_('Description')) estate = models.OneToOneField('announcement.Estate', on_delete=models.CASCADE, verbose_name=_('Estate'), null=True) -
django:postgres Querying Boolean Field with Null Values
I have a table with around 150 million rows. I have added a new Boolean field which was not there in the old rows. So, I added null in those rows and created the field. ride_active = models.NullBooleanField(null=True, blank=True) I migrated it to DB and added an admin filter on this field. list_filter = ( 'ride_active', ) Now, all the previous rows have Null value, so Unknown filter value is working as fine. But while filtering for Yes and No, the query takes too much time and it results in Bad Gateway. When I explain the query(on test environment), Index Scan Backward using iot_data_nov_pkey on iot_data_nov (cost=0.44..1604685.17 rows=12708380 width=311) Filter: ride_active I don't think adding an index on this field will be a good idea. How can I speed up my query on this field where the value is True/False, creating a partial index? -
save model form and update
I have created a form and I would like to save the form without having to enter the Id in the form. I am able to update the form only if I enter Id in this instance, also I would like to show the Id of the class in the template but I don't want to have to write on it. models.py class w_orders(models.Model): Id = models.AutoField(primary_key=True) datedefwo = models.DateField(default=datetime.now) datesched = models.DateField(blank=True, null=True) datefinished = models.DateField(blank=True, null=True) sign = models.BigIntegerField(blank=True, null=True) statusid = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES) typeid = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) comments = models.CharField(max_length=254, blank=True, null=True) navid = models.BigIntegerField(blank=True, null=True) navkonsid = models.CharField(max_length=12, blank=True, null=True) navname = models.CharField(max_length=254, blank=True, null=True) navcustadr = models.CharField(max_length=254, blank=True, null=True) navdebt = models.FloatField(blank=True, null=True) navpropcode = models.CharField(max_length=254, blank=True, null=True) navdepcode = models.CharField(max_length=254, blank=True, null=True) navphoneno = models.CharField(max_length=254, blank=True, null=True) navreasoncomp = models.CharField(max_length=254, blank=True, null=True) nightshift = models.BooleanField(default=False) priority = models.BigIntegerField(blank=True, null=True) st_id = models.BigIntegerField(blank=True, null=True) mapurl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.Id views.py from django.shortcuts import render, get_object_or_404, redirect from django import forms from django.views.generic import TemplateView from django.core.serializers import serialize from django.http import HttpResponse from MMS.models import w_orders from MMS import forms from MMS.forms import CreateWorkorder from django.contrib.auth.forms import … -
how can i use math operation in to_representation in django rest
def to_representation(self, instance): job_count = Jobs.objects.filter(user_id=instance.user.id).count() job_open = Jobs.objects.filter(user_id=instance.user.id, status='Open').count() job_closed = Jobs.objects.filter(user_id=instance.user.id, status='Closed').count() proposal_count = JobProposal.objects.filter(user_id=instance.user.id).count() # connects_left = ((UserProfile.connects) - (proposal_count*2)) return { 'id': instance.id, 'created': instance.created, 'modified': instance.modified, 'user': instance.user.id, 'category': str(instance.category), 'category_id': instance.category.id if instance.category else '', 'expert_level': instance.expert_level, 'category_skill': instance.category_skill, 'offer_skill': instance.offer_skill, 'title': instance.title, 'description': instance.description, 'dob': instance.dob, 'overview': instance.overview, 'english_level': instance.english_level, 'hourly_rate': instance.hourly_rate, 'daily_availability': instance.daily_availability, 'expected_availability': instance.expected_availability, 'avatar': instance.avatar, 'address': instance.address, 'city': instance.city, 'zipcode': instance.zipcode, 'state': instance.state, 'country': instance.country, 'user_type': instance.user_type, 'status': instance.status, 'timezone': instance.timezone, 'phone': instance.phone, 'visibility': instance.visibility, 'search_engine_privacy': instance.search_engine_privacy, 'earnings_privacy': instance.earnings_privacy, 'linkedin': instance.linkedin, 'facebook_id': instance.facebook_id, 'twitter_id': instance.twitter_id, 'google_plus_id': instance.google_plus_id, 'vat': instance.vat, 'membership': instance.membership_id, 'connects': instance.connects, 'connects_left': (instance.connects - (proposal_count*2)), 'existing_membership': instance.existing_membership, 'Proposal_count': proposal_count, # 'company_name': instance.company_name, 'job_count': job_count, 'job_open': job_open, 'job_closed': job_closed } 'connects_left': (instance.connects - (proposal_count*2)), TypeError: unsupported operand type(s) for -: 'str' and 'int' i got this error -
post_save, pre_save not triggered, but post_init does
I am a bit baffled by the behavior of django signals. Namely, the same code can trigger post_init, but not pre_save or post_save @receiver(post_save, sender=Asset) def assetCreated(sender, **kwargs): asset = kwargs['instance'] asset, created = kwargs['instance'], kwargs["created"] if created: read = Privilege.objects.get(name=Privilege.READ) grant = Privilege.objects.get(name=Privilege.GRANT) accGrp = GroupAccess(asset=asset, researchGroup=asset.belongsToGroup, privilege=read) accGrp.save() accSbtr = ResearcherAccess(asset=asset, researcher=asset.submitter, privilege=grant) accSbtr.save() accCrtr = ResearcherAccess(asset=asset, researcher=asset.originalCreator, privilege=grant) accCrtr.save() With changing the first line to: @receiver(post_init, sender=Asset), the function will be called. I need to assign default privileges upon the creation of an asset. Obviously, pre_init is not the right way, since many instances would be created per request, thus leading to several triggers. Has anyone encountered such behavior or better idea of triggering a callback after the creation of new entries, please help! Thank you. Note 1: The same happens when the signals are implemented in the other variation, i.e. in models.py. Note 2: This is different than the built-in permissions, as this binds a user/group to a given instance with privileges. Python v3.7.0, Django v2.1.4 -
How to configure DATABASE_ROUTERS? It errors ModelNotFound Error
when I set up multiply databases,there is a problem,anyone can help me ? error img -
Django form wizard save data into PostgreSQL
I'm creating two form using form wizard. When the user finish fill in the first form(personal details), then select next button, it will go to second form(family member's details). When the user select submit button, the data will save into specific table(Details and Family). My database engine is PostgreSQL. Here is my code in view: FORMS = [("customer", CustomerForm), ("family", FamilyForm)] TEMPLATES = {"customer": "customer_register.html", "family": "family_register.html",} def cust_contact_register(wizard): cleaned_data = wizard.get_cleaned_data_for_step('customer') or {'method': 'none'} return cleaned_data['method'] == 'family' class CustWizard(SessionWizardView): template_name = 'customer_register.html' # def get_template_names(self): # return [TEMPLATES[self.steps.current]] def done(self, form_list,form_dict,**kwargs): form_data= [form.cleaned_data for form in form_list] for form in form_data: name = form['name'] ## I want to get the data here to save nto database but it return error. mobile = form['mobile'] email = form['email'] familyname = form['familyname'] address = form['address'] add_member = Customer( name=name, mobile=mobile, email=email, ) add_family = Family( name=name, address=address, ) add_member.save() add_family.save() return render(self.request, 'customer_register.html', { 'form_data': form_data, }) Customer table have id,name,mobile,email,and familyid(Foreign Key) attribute where Family table have id,name and address attribute. The error returned: Traceback: File "C:\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, … -
Django server failed to deploy
When I tried to send a mail using django, the following error showed up. path('mail',views.mail) I was using the same code for some time but , this is the only time i saw the error. -
Django Rest Framework Token Authentication with Postman
I am trying to use Postman to test my DRF end-point, but I always get an Authentication credentials were not provided. error. The end-point works properly, but I haven't found how to send the request from Postman. I am able to get the token for the user: But I always get the error when I try to use the token to send a request: I set the Authorization Type to Inherit auth from parent. -
How to run git cloned Django project which has been written in Pycharm in another Pycharm?
How to run git cloned Django project which has been written in Pycharm in another Pycharm? I have tried simple open project but this option does not recognize the project as a Django project. Moreover, I tried to get the only source code ( without .idea and venv folders) and get this error below: Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Is there any already proven way of doing this? -
Django-filter - I want to filter in different attributes with just one filter input
Having the following model: class Project(models.Model): ... name = models.CharField(max_lenght=70) short_description = models.CharField(max_length=135) description = models.CharField(max_lenght=25000) ... I want to use only one input to look by name, short_description and description. So for example, if I have the following data: object1: name = Amazing airplanes short_description = This project wants to be ... description = ... ... ... object2: name = Testing potatoes as batteries short_description = ... ... ... description = ... this project ... object3: name = project creator short_description = ... ... ... description = ... ... ... And I filter in only one input of the filter by project, I must get the three objects as a result. (Also if one object have the same word in few attributes, it have to return me only one time that object) What I have now is this: class ProjectListFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') short_description = django_filters.CharFilter(lookup_expr='icontains') description = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Project fields = ['name', 'short_description', 'description'] queryset = Project.objects.all() But this generates 3 inputs, and is what I'm trying to evade. -
django: how to develop test cases for MEDIA_ROOT and STATIC_ROOT url patterns
I have a Django web application, wherein I am running test cases using coverage test tool. I would like to know how to develop test cases for STATIC_ROOT and MEDIA_ROOT, since my coverage test states that for my urls.py file, the coverage is only 78%, the following two url patterns have not been tested. I have researched a lot online, but couldn't find anything resourceful. Please help! Thanks. -
Is it possible to do a redirect + POST from Chrome Extension
If a user clicks on a link on my Chrome Extension, I would like them to be redirected to a page on my server, along with POST data (not GET data). I followed the instructions here, http://theshybulb.com/2016/01/16/data-from-chromeextension-to-website.html, but Django is still recognizing it as a GET request, not a post request. -
How to authorize django-rest-knox login path without 401 error?
I'm trying to put an authentication api on my django app so I can start using a Vue+Node frontend. I've read over the knox documentation, but I don't seem to see anything suggesting what the issue is. Any insight would be greatly appreciated. My suspicious are below. What I'm doing: I was following this tutorial which suggest using knox, which seems to have nice features. When I try to curl to create a user, everything works as expected, but when I try to login (via curl), I get the following response (401) in my console: API Call (venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/register/ --header 'content-type: application/json' --data '{"username": "user3", "password": "hunter2"}' {"user":{"id":4,"username":"user3"},"token":"2b261fcdcbfff47cd8819accc2a3a08befa169c59982659a64012c680a69c3e8"} (venv) brads-mbp:ReportVisualization brads$ curl --request POST --url http://127.0.0.1:8000/backend/auth/login/ --header 'content-type: application/json' --data '{"username": "user3","password": "hunter2"}' {"detail":"Authentication credentials were not provided."} Server Log System check identified no issues (0 silenced). December 18, 2018 - 07:47:05 Django version 2.1.3, using settings 'project.settings' Starting ASGI/Channels version 2.1.5 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. HTTP POST /backend/auth/register/ 200 [0.13, 127.0.0.1:61332] Unauthorized: /backend/auth/login/ HTTP POST /backend/auth/login/ 401 [0.00, 127.0.0.1:61336] The curl login response makes me think there is something wrong with my setup of knox or django's auth. … -
Testing with Travis-CI (Django)
I'm very new to testing so I'm not sure how to do it. I created the .travis.yml file (see the code below) and also added travis to settings.py (also below). Do you know what I should do? Creating test database for alias 'default'... System check identified no issues (0 silenced). ====================================================================== ERROR: travis (unittest.loader._FailedTest) ImportError: Failed to import test module: travis Traceback (most recent call last): File "\Documents\python\lib\unittest\loader.py", line 154, in loadTestsFromName module = import(module_name) ModuleNotFoundError: No module named 'travis' Ran 1 test in 0.000s FAILED (errors=1) Destroying test database for alias 'default'... .travis.yml file: language: python cache: pip python: - 3.7.1 env: - DJANGO_VERSION==2.1.3 install: - pip install -r requirements.txt services: - db.sqlite3 before_script: - sqlite3 -e 'create database travis_ci_db;' - python manage.py syncdb script: - python manage.py travis settings.py: if 'TRAVIS' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'travisci', 'USER': '', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '', } } -
Running n time django_content_type query
Django content type table query hits n time in admin user add page other page working fine. Can any one please assists and help for resolve this issue and let me know why its hitting n time? here is query SELECT "django_content_type"."id", "django_content_type"."app_label", "django_content_type"."model" FROM "django_content_type" WHERE "django_content_type"."id" = 94 also share screenshot -
How do I copy a file to 'document root' of my Django web server
I really hit an impasse. I wanted to download a file when I click a button. The file is present in a network path and the Django server is also in the same network. I could open/reach the file using file explorer in windows. However, when I try to download the file like this: success: function(msg){ console.log(msg); if(msg.zip == 'ok'){ window.open('file:'+msg.te_logs); } }, I get a console error: **Not allowed to load local resource**: file://PCName-labstore/Log_Database/Campaigns/log.zip I am told Local file access is impossible (even though the server is in the network). At this point, all I could think of is copying the .zip file somehow to document root, and then give that path to download and then delete the file from document root after download is complete. I haven't done this before. Can you kindly advise me how? Or if it is possible to open the network path using FileReader API, can you please point me to an example how? My Django server and all users who use my site/app have are on the same network as the network drive where the files are at. -
Django reset password sender and receiver inverted
In Django my project i add the "Frorget password" link. In my urls.py: path('accounts/', include('django.contrib.auth.urls')), in my settings.py: # Email setting EMAIL_USE_TLS = True EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_PORT = 587 EMAIL_FROM = 'account@test.io' EMAIL_HOST_USER = 'YUIJKHKBKBD7879' EMAIL_HOST_PASSWORD = 'By6786ghgkgk//89jkjlnCkVt' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' but when i go to my page /accounts/password_reset/ and insert the email for what i whant to change the password es. mario.rossi@gmail.com, when i click The Submit button, system return: SMTPDataError at /accounts/password_reset/ (554, b'Message rejected: Email address is not verified. The following identities failed the check in region US-EAST-1: mario.rossi@gmail.com, webmaster@localhost') But mario.rossi@gmail.com is not the sender, it's the receiver! why django reset password does seem to use EMAIL_FROM from settings.py for send email From? So many thanks in advance -
How can we assign different expiry time to different users in jwt tokens in django
i am using jwt tokens in django. i have expiry time 5mins for all the users.but i want to change the expiry time of the user based on the role. How can i achieve that in django SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': True, } -
Amazon SES and EC2 instance in different regions
I want to use Amazon SES for a website based on Django that I am working on. Amazon SES comes for 3 regions US East (N. Virginia) US West (Oregon) EU (Ireland) I also have an ec2 instance which is in US West (N. California) region. The pricing of SES(https://aws.amazon.com/ses/pricing/) varies if you have an ec2 instance or not. Can I use SES for my ec2 instance(as it will be cheaper) which is in a different region? If yes, how do I do it? If no, what do I do? I am currently using Sendgrid for email service but I want to change that to SES. Currently, I don't have to do anything but add the SENDGRID API KEY and EMAIL Backend to setting and use normal email function provided by Django. Do I have to change a lot if I want to use SES? -
Get searched(filtered) objects
I'm trying to get the sum of some fields, this amount should be dynamic, depending on the search or filter. How do I make price_total dynamic? class OrderAdmin(ImportExportModelAdmin, admin.ModelAdmin): resource_class = OrderResource form = OrderForm date_hierarchy = "created" list_display = ('price_total', 'order_no', 'phone', 'get_directions') search_fields = ("document__first_name", "document__last_name", 'order_no', 'user__username') readonly_fields = ("dealer", ) list_filter = ('status', 'payment_type', 'channel', ('buy_time', DateRangeFilter), ('created', DateRangeFilter)) def price_total(self, obj): return obj.__class__.objects.aggregate(Sum('total_price')).get('total_price__sum') def order_no(self, obj): return obj.order_no def phone(self, obj): return obj.user.username if obj.user else obj.contact def get_directions(self, obj): return obj.get_directions() -
Django there is any app about survey/DB saved/viewing some kind of forms?
i need some help about making Django site. now i'm learning about Django to make my company groupware site. BTW i have a one question about Django application. i'm always doing same boring working like my company's employ use Google Survey submit to their own work result -> it can be number, date then it's going to saved Google Drive(SpreadSheet) -> like a Database! and finally i use GS data copy to MS Excel organized form form to my superior want see. like this -> date | workfactor 1 | part | name '####-##-## | 5 | 1T | 00000 00 so i wanna develop this work to Django site. to sum up, users doing survey on that site. and that data save in database, viewing form by their authorization. if there is any kind of app to i wanted?? or what i've must learning about ?? plz will u guys tell me help to find out. have a nice day. thx! -
How to get all celery tasks?
everyone. I want to get all celery tasks in my program. Like django-admin did. enter image description here But i have searched a lot which didn't help. Plz. Help me out! -
Django ORM query duplicates annotated values
I have two almost equal test query: test1 = ( Invoice.objects .filter(id=2787) .annotate(plan_total=Sum( 'item_reason__planned_bank_operations__amount') )) test2 = ( Invoice.objects .filter(id=2787) .annotate( plan_total=Sum( 'item_reason__planned_bank_operations__amount'), pieces_total=Sum( 'invoice_pieces__amount') )) The result of test1.values('plan_total') returns <QuerySet [{'plan_total': Decimal('658.00')}]>, but when I try to get the same values of test2.values('plan_total') it returns <QuerySet [{'plan_total': Decimal('1316.00')}]>. How could this happen? A little bit more information about the fields above: item_reason is ForeignKey when planned_bank_operations is related query which was associated by related_name in PlanOperation model. Same history with invoice_pieces. InvoicePiece is individual model that have ForeignKey to Invoice with related name InvoicePieces. So, I can't understand this behavior. This is a bug or a feature?