Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Allauth urls giving blank pages
i have installed django-allauth on my site, i made a modal with both login and signup in it, the login and signup works ok (doh i have a problem that if the login isnt good it just freeze at a white page) the problem is that under login, i have a forgot your password button, but once clicked it redirect to http://127.0.0.1:8000/accounts/password/reset/, but onlice show a white page, like the allauth templates were not loaded URLS path('users/', include('users.urls')), #for allauth url(r'^accounts/', include('allauth.urls')), #custom user SETTINGS: INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', AUTH_USER_MODEL = 'users.CustomUser' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', "allauth.account.auth_backends.AuthenticationBackend", ) TEMPLATES ... # `allauth` needs this from django 'django.template.context_processors.request', LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_LOGIN_ATTEMPTS_LIMIT =5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT =1800 ACCOUNT_USERNAME_BLACKLIST =[] ACCOUNT_UNIQUE_EMAIL =True this is the button for forgotten passord <div> <a class="forgotpass" href="{% url 'account_reset_password' %}"> {% trans "Forgot Password?" %}</a> </div> What did i do wrong ?? -
Print Django ForeignKey object text in html?
I have these Django models: class Message(models.Model): subject = models.TextField(max_length=1000, blank=True) text = models.TextField(max_length=10000, blank=True) sender = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null = True, related_name="sender" ) class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=140,blank=True, null=True) last_name = models.CharField(max_length=140, blank=True,null=True) I passed the model into my html and javascript files (name is received), and I want to retrieve each field. For the subject and text fields, I did: var subject = received.fields.subject; // outputs correct data var text = received.fields.text; // outputs correct data However, when I do the same thing for the foreignKeyModels in order to get the username of the sender: var firstname = received.fields.sender.first_name // returns integers(?) I get integer outputs like 17, 20, etc.. I think each of these corresponds to a single user. How do I retrieve the textfields from the User model (ForeignKey) through the received model I imported? -
Django join with sum
I have two models, Transaction and TransactionType. class Transaction(models.Model): tran_date = models.DateField() tran_amount = models.FloatField(default=0.00) tran_payment_method = models.ForeignKey(PaymentMethod,on_delete=models.SET_NULL,null=True) tran_location = models.ForeignKey(Location,on_delete=models.SET_NULL,null=True) tran_type = models.ForeignKey(TransactionType,on_delete=models.SET_NULL,null=True) account = models.ForeignKey(User,on_delete=models.CASCADE,default='') create_date = models.DateTimeField(auto_now_add=True, blank=True) class TransactionType(models.Model): name = models.CharField(max_length=200) status = models.IntegerField(default=1) # 0:inactive 1:active income_ind=models.IntegerField(default=0) # 1: expense 2: income account = models.ForeignKey(User, on_delete=models.CASCADE,default='') create_date = models.DateTimeField(auto_now_add=True, blank=True) I want to use ORM to run a query like below select b.name,sum(a.tran_amount) as total from Transaction a inner join TransactionType b on a.tran_type = b.id where a.account=some_user_id and b.income_ind=1 How should I implement this without using raw query? -
uploading csv file with user detail and sending reset-password-email when once the user is created Django
I am facing problem in triggering the system to send password reset email to the users. I will upload a csv file(this has details like FN,LN, email address) which contains customer details and once the upload is successful, the system has to send an password reset email to the customers. Now i see the following error when i try to upload the csv 'UploadFileForm' object has no attribute 'save' 1) On importing/uploading the CSV file the users must be created and the users gets a password reset email to change the password ---- This is done by the system. NOTE - I am using Django 2.0.8, I also tried the these links view.py def validate_csv(value): if not value.name.endswith('.csv'): raise ValidationError('Invalid file type') def handle_uploaded_file(request): csvf = StringIO(request.FILES['file'].read().decode()) reader = csv.reader(csvf, delimiter=',') reader.__next__(); count = 0 for row in reader: vu = ValidUser(email = row[1],first_name = row[2],last_name = row[3]) if vu is not None: vu.save() count = count + 1 return count @login_required def registerusers(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): file_name = request.FILES['file'] validate_csv(file_name) user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Enter Password for your Account' message = render_to_string('account_activation_email.html', { 'user': … -
django template forloop.counter multiple operations
I am trying to perform multiple mathematics operations on a forloop.counter in my Django template. Specifically I am trying to identify every 29th instance, after the 24th; so the 53rd, 82nd, 11th, 140th instances etc.... I have tried the following without success: {% if forloop.counter == 24 or widthratio forloop.counter|add:"-24" 29 1 %} {% if forloop.counter == 24 or forloop.counter|add:"-24"|divisibleby:29 %} Does anyone have any suggestions that might help me acheive my aim? Any help is much appreciated! -
How make django API work only in specific package name app?
I created an Android application and linked it to a control panel and a database using django. But what I noticed was that in this library,my api link are accessible in general, and I do not want my api to be accessed or used by anyone else. how make it worked in spisific package name ? -
Serve models based on permissions - Django Rest Framework
I would like to serve different models to different user permission groups in Django Rest Framework. For example, if a user is a member of Group_A, I would like the user to see model_a when they sign into the API. If they are a member of Group_B, I would like them to be served model_b in the API. If they are in Admin_Group I would like them to see both. Does anyone have any insight? Thanks in advance -
Provide API for a Django project as a different docker service
I recently started to work on a friend's project in Django and we want to provide a REST API so other projects can consume our data. I'm starting to learn django-rest-framework (and django-rest-swagger for documentation). Is it possible to create the API as a separate service? this way we dockerize it and serve the api in one container, and keep the application on its original container preventing that if many requests to the API were made, it will not interfere on the application (by bringing it down for example). If it is not possible what is the best way for implement the API on the project? -
Django: Initial Value for Form
I want to show an initial value in the form. At runtime no errors occurs, the field stays empty. Why isn't it showing the value? views.py: def mieteinheit(request, wohnungsgruppenname): if request.method == 'POST': #... else: form = WohnungseinheitenForm(request.POST or None,initial={'ort':'Hof'}) template = loader.get_template('Immo/user/mieteinheit.html') context = {"wohnungsgruppenname":wohnungsgruppenname,"form": form} return HttpResponse(template.render(context,request)) .html-File: <input class="form-control" id="{{ form.ort.auto_id }}" name="ort" type="text" > Form.py: class WohnungseinheitenForm(forms.ModelForm): ort = forms.CharField(required=True,max_length=100) -
Using Django ManyToMany symmetrical property recursively
Is it possible to use the symmetrical property from models.ManyToManyField so that it recursively associates symmetrical records? For example, in my code I have: class User(models.Model): website = models.ForeignKey('myapp.Website') related_users = models.ManyToManyField('self', related_name='users', symmetrical=True) When I do: user_a.related_users.add(user_b) user_a.related_users.all() # returns the user B user_b.related_users.all() # returns the user A Everything is working as expected here, the relationship is symmetrical. But when I do: user_b.related_users.add(user_c) user_b.related_users.all() # returns user A and user C user_c.related_users.all() # returns user B I want user C to return user A and user B automatically, because user C is user B, which is user A, therefore user C is user A too. Is it possible to achieve that or do I have to manually add the association between user A and user C? -
Custom template not loading correctly in Django
I'm attempting to sub out the submit_line.html of the DetailView of an admin template in Django, but I'm getting this error: InvalidTemplateLibrary at / Module data_operations.templatetags.data_operations_tags does not have a variable named 'register' My settings.py contains my app name: INSTALLED_APPS = [ ... 'data_operations', ... ] And template data: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ # os.path.join(PROJ_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'data_operations.apptemplates.load_setting' ], 'libraries':{ 'data_operations_tags': 'data_operations.templatetags.data_operations_tags', } }, }, ] Here's data_operations/templatetags/data_operations_tags.py: from django.contrib.admin.templatetags.admin_modify import submit_row from django.template.loader import get_template from django import template t = get_template('admin/data_operations/submit_line.html') register = template.Library() register.inclusion_tag(t, takes_context=True)(submit_row) I made sure to include an empty __init__.py in the templatetags directory as well. Finally, I have two templates. data_operations/templates/admin/data_operations/change_form.html: {% extends "admin/change_form.html" %} {% load data_operations_tags %} {% block submit_buttons_bottom %}{% submit_row %}{% endblock %} And data_operations/templates/admin/data_operations/submit_line.html (which is exactly the same as the default, except I've added a custom 'Cancel' button to the code): {% load i18n admin_urls %} <div class="submit-row"> {% if show_save %}<input type="submit" value="{% trans 'Save' %}" class="default" name="_save" />{% endif %} {% if show_delete_link %} {% url opts|admin_urlname:'delete' original.pk|admin_urlquote as delete_url %} <p class="deletelink-box"><a href="{% add_preserved_filters delete_url %}" class="deletelink">{% trans "Delete" %}</a></p> … -
django on app engine does not render templates in sub directories
I've been trying to put a django(2.1) (python3) application on google's flexible app engine and have run into the following problem: The application does not render any templates that are in subdirecties of the templates folder, it gives 500 errors. I've been looking at the tails of the logs via gcloud console and within the admin interface and I don't see anything useful. My app.yaml is: runtime: python # api_version: 1 env: flex entrypoint: gunicorn -b :$PORT MyApp.MyApp.wsgi runtime_config: python_version: 3 manual_scaling: instances: 1 resources: cpu: 1 memory_gb: 0.5 disk_size_gb: 10 env_variables: SECRET_KEY: 'key-here' DEBUG: 'False' DB_HOST: '/cloudsql/instance:region:instance' DB_PORT: '5432' DB_NAME: 'instance' DB_USER: 'postgres' DB_PASSWORD: 'db-password' STATIC_URL: 'https://storage.googleapis.com/bucket-name/static/' beta_settings: cloud_sql_instances: 'instance:region:instance' My template folders settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'templates', 'subdir'), os.path.join(BASE_DIR, 'templates', 'subdir', 'othersubdir'), etc. I'm really stumped. Any advice or feedback on where to get more detailed error logs, or what the problem might be would be greatly appreciated - thanks!!! -
No 'Access-Control-Allow-Origin' header is present on the requested resource with Django digitalocean Spaces
My Django website is hosting in digitalocean ubuntu 16.04 with Nginx. When I use digitalocean Spaces as my static and media file storage.There is No 'Access-Control-Allow-Origin' header is present on the requested resource error: Access to Font at 'https://nyc3.digitaloceanspaces.com/kjmgstorage/kjmgstorage/fonts/fontawesome-webfont.woff2?v=4.7.0' from origin 'https://kjmg.co' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://kjmg.co' is therefore not allowed access. I tried to use django-cors-headers,but I received: 502 Bad Gateway nginx/1.10.3 (Ubuntu) So had to uninstalled it. Any friend have any idea?Thank you so much! -
Celery doesn't run task
Help me, please, to understand what I am doing wrong. Celery doesn't run my task. Settings.py CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE proj/celery.py from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() init.py from __future__ import absolute_import, unicode_literals from celery import app as celery_app __all__ = ['celery_app'] Code @shared_task def generate(instance, sender, **kwargs): for i in CK_PROGRAM_NAME: program_kf = i[0] ck = instance.dk*program_kf program_name = i[1] program_obj = Program.objects.get(name=program_name) foodprogram_generator(instance, ck, program_kf, program_obj, sender, **kwargs) return @receiver(post_save, sender=LeadUser) def leaduser_foodprogram_post_save(instance, sender, **kwargs): generate.delay(instance, sender, **kwargs) return Worker is run by: celery -A proj worker --loglevel=INFO The logic is: after client_object is created, post_save signal starts leaduser_foodprogram_post_save, that adds to a queue generate() I can see result, so I think it is not run. Without celery everything works properly. Thanks for you answers! -
Remove read permission in Django
It seems that in Django, models are permissioned as read-only by default. You must give them 'can_add', 'can_change' and 'can_delete'. I would like to make it so that models are not readable by default, with read access only being given explicitly (I want to say 'can_read'). Does anyone know how to do this? Thank you -
django "<QuerySet{[ ]}" appearing in list
I have been wrestling with something that I think is a bonehead oversight on my part. I have a form that feeds an input to a view that queries some SQL tables I have and returns a list back with columns from each table**. The odd thing that is happening is the my list is appearing with <QuerySet{[ ]}> brackets around each list object. Can anyone tell me how to avoid this? Much appreciated. **I am using this list to combine these tables rather than ForeignKeys because I was having a terrible time getting my SQL databases to populate correctly using SQLAlchemy and Postgres and read that there were known issues with that, so I gave up on that method. views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect, HttpResponse, Http404 from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import * from .forms import QuoteForm, RfqForm def bom_result(request): if request.method == 'POST': form = RfqForm(request.POST) if form.is_valid(): bom_list = [] rfq = {} rfq_search = form.cleaned_data['rfq_entered'] rfq['rfq_num'] = rfq_search rfq['bom'] = Quotereq.objects.values('bom_entered').filter(rfq_num__exact=rfq_search) rfq['part_num'] = Bom.objects.values('partnum').filter(bom__exact='07-00-000019') bom_list.append(rfq) context = {'bom_list': bom_list} return render(request, 'quote/result.html', context) else: return HttpResponse("<h1>Something Went Wrong</h1>") else: form … -
Flutter vs angular vs react native vs ionic vs other
I want to make an iOS and Android app using some type of framework. Here are my criterea for the choice It must be easy to write It must be able to scale It should be able to work with Django My main choice is ionic, but I don’t know if it can scale. Any suggestions are appreciated. Thanks -
Django Rest Framework - One to Many relationship not working
I'm trying to Serialize a Object that have Many Objects related. It's a Order has Many Logs relationship. I tried to do the same that in these tutorials (https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/ and http://www.django-rest-framework.org/api-guide/relations/#nested-relationships) but it doesn't work. I have also looked in various google link but nothing. Anyone can help me, please? What I'm doing wrong? models.py class MaintenanceOrder(models.Model): responsible_technician = models.ForeignKey(Technician, on_delete=models.DO_NOTHING, null=True) order_code = models.CharField(max_length=12, null=True) note_code = models.CharField(max_length=12, null=True) equipment = models.CharField(max_length=18, null=True) locale = models.CharField(max_length=30, null=True) short_description = models.CharField(max_length=40, null=False) description = models.TextField(null=True) priority = models.CharField(max_length=1, null=False) breakdown = models.CharField(max_length=1, null=True) stop_time = models.DateTimeField(null=True) end_time = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.ForeignKey(MaintenanceStatus, on_delete=models.DO_NOTHING) def __str__(self): return self.order_code class Meta: managed = True class MaintenanceLog(models.Model): maintenance_order = models.ForeignKey(MaintenanceOrder, on_delete=models.DO_NOTHING) technician = models.ForeignKey(Technician, on_delete=models.DO_NOTHING, blank=True, null=True) start_time = models.DateTimeField() stop_time = models.DateTimeField(null=True) description = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.description class Meta: managed = True serializers.py class MaintenanceLogSerializer(serializers.ModelSerializer): class Meta: model = MaintenanceLog fields = '__all__' class MaintenanceOrderSerializer(serializers.ModelSerializer): status_code = serializers.IntegerField(source='status.status_code', read_only=True) order_log = MaintenanceLogSerializer(many=True, read_only=True) class Meta: model = MaintenanceOrder fields = '__all__' This API it's returning all orders, but without "order_log"... Even if I specify "order_log" in fields, it … -
Unable to load style.css in Django 1.9
I am trying to load the style.css on my page. I've added the path for STATICFILES_DIRS like below, STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "static_cdn") index.html `<link rel='stylesheet' href='{% static "css/style.css" %}' type='text/css'>` When I ran the collectstatic and it collected the style.css. When I do inspect element and open a link of style.css (http://127.0.0.1:8000/static/css/style.css), it gives me not found message. I tried hard-coding the path to style.css but, no luck. I created the another sample project and followed the same steps and style.css loaded successfully. When I do inspect element and open a link of style.css, it shows me html code. I am really helpless. Any help is really appreciated. -
Django: read an uploaded file and add content to a textarea field in the model
I have a model that has a filefiled to upload docx files(e.g cv). I would like to read the contents of this file and add it to a textarea field (e.g experience), such that the contents are saved to the database. Need help on how to go about this. I am aware of REQUEST.FILES but don't know how to piece it together -
How to open a Document whilst in django template?
I have an object that contans a database record that has a FileField which points to a .pdf, .txt or .doc or .docx. In my django template i want to create a link which when clicked opens the file, in the machines default tool for opening that file, How do i do this ? I currently have <a href="#">{{ object.file.name }}</a> i would like to click this link and have the document opened. -
Django: How to import a javascript inside another javascript file
How to import inside JavaScript files and using Django to load another js. Statements like these don't work: import { PolymerElement, html } from '{% static "@polymer/polymer/polymer-element.js" %}'; import '@polymer/app-layout/app-drawer/app-drawer.js'; And also these too: import { PolymerElement, html } from '@polymer/polymer/polymer-element.js'; import '{% static "@polymer/app-layout/app-drawer/app-drawer.js" %}'; Is there is a way to do that without bundling the code in on big file, nor calling all files may be needed in the html file. Thank you -
Unsupported locale setting while deploying on pythonanywhere
So I just got my website running on pythonanywhere but I get this error: unsupported locale setting locale.setlocale(locale.LC_ALL, 'esp_esp') full traceback: http://dpaste.com/355VD3W -
Need to get instance id from django in template
I am new to django and i have a problem. I have a django form class MyModelForm(ModelForm): class Meta: model = MyModel fields = ['id', 'field1', 'field2', 'field3'] localized_fields = ('id', 'field1', 'field2', 'field3') And when I try to output id it doesn't work, but it works with others. {{form.id.value}} How to get id value in template from django form? -
Django: AppRegistryNotReady when importing @wraps
I receive the following error when using wraps. File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/Marc/Desktop/Dev/lumis/config/settings/local_marc.py", line 1, in <module> from .local import * File "/Users/Marc/Desktop/Dev/lumis/config/settings/local.py", line 1, in <module> from .base import * File "/Users/Marc/Desktop/Dev/lumis/config/settings/base.py", line 6, in <module> from lumis.core.helpers import get_env_variable File "/Users/Marc/Desktop/Dev/lumis/lumis/core/helpers.py", line 17, in <module> from .decorators import check_if_mixpanel_defined_in_settings File "/Users/Marc/Desktop/Dev/lumis/lumis/core/decorators.py", line 1, in <module> from django.contrib.auth.views import redirect_to_login File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/contrib/auth/views.py", line 11, in <module> from django.contrib.auth.forms import ( File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module> from django.contrib.auth.models import User File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config self.check_apps_ready() File "/Users/Marc/.local/share/virtualenvs/lumis-vJ5Odiz7/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded …