Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Django DetailView : How to access the single object passed into DetailView for manipulation of its attributes' values
My aim is to access the values within the object that is passed into the Django DetailView. To access that single objects specific attributes' values for further manipulation in another class / function (to be printed). Ideally I would like to be able to write a subroutine inside the view file (like below): This is desirable as DetailView already have made the unique selection of the Product in question and hold this object in memory already. def to_print(object): name = object.product_name price = object.product_price price_new = price + 100 id = object.pk models.py class Product(models.Model): product_name = models.Charfield(max_length=20) product_price = models.FloatField(max_length=12, default=100) urls.py path('product/<int:pk>/', ProductView.as_view(), name='product-detail) views.py class ProductView(DetailView): model = Product template_name = 'product/product_detail.html' product_detail.html {% block content %} <table> <tr> <td>{{ object.id }}</td> <td>{{ object.product_name }}</td> <td>{{ object.product_price }}</td> </tr> </table> {% endblock content %} My attempts (cannot get it to work) class ProductView(DetailView): model = Product template_name = 'product/product_detail.html' def get_object(self, queryset=None): obj = super(ProductView, self).get_object(queryset=queryset) return self.generate_pdf(obj) def generate_pdf(self, obj): from reportlab.pdfgen import canvas response = HttpResponse(content_type='application/pdf') response['pdf'] = 'attachment; filename="summary.pdf"' p = canvas.Canvas(response) name = obj.product_name p.drawString(100, 100, name ) p.showPage() p.save() print(p) return response -
MySQL denies to work with Django in Ubuntu
I am trying a simple blog project in Django with MySQL as database server and installed the mysqlclient adaptor. Made changes in the settings.py as below: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'test', 'USER': 'root', 'PASSWORD': 'i1nt9bt7', 'HOST': '127.0.0.1', 'PORT': '3306', } } But when I am typing "python manage.py migrate" after starting the mysql service it's giving me error that looks something like this: django.db.utils.OperationalError: (2006, "Authentication plugin 'caching_sha2_password' cannot be loaded: /home/sandip/anaconda3/lib/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory") I m using Ubuntu as my OS. When I revert back to Postgresql and make changes in the settings.py file it works fine. But I can work with MySQL when I am write simple Python desktop applications. Problem arises when I try it with Django. Please help. -
No module named django.conf.urls.defaults
) I'm having some trouble building a django app while following the guide here: https://code.djangoproject.com/wiki/searchengine Hardware/Software: Django Version 2.1.4 Python Version 3.7 Windows 10 Lenovo Yoga 720 When inputting the following code: from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^/?$', 'google.searchengine.views.search'), ) into the urls.py, the command line returns: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03D341E0> Traceback (most recent call last): File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 396, in check for pattern in self.url_patterns: File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Konjo\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in … -
How to use result from django view as parameter to IMG tag in HTML?
I'm trying to use data returned from a django view within a template, as a parameter to a SRC attribute to an img tag with the following code. {% for instance in prods %} <img src="{% static '{{ instance.image_url }}' %}" alt="IMG-PRODUCT"> {% endfor %} instance.image_url corresponds to a textfield within the database that contains a url to an image. This url, copied and pasted into a browser shows the image looks fine. My problem is that I'm not sure how to use curly brackets within curly brackets I thought maybe use of static is not needed, and so I tried just: <img src="{{ instance.image_url }}" alt="IMG-PRODUCT"> This results in html with a blank src attribute, like so: <img src="" alt="IMG-PRODUCT"> Using {{ instance.title }} later on in the code, with title corresponding to a textfield in the database, works as expected and displays the value of that field in the HTML. Why is one field displaying and not the other?