Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : Send a mail to user when entry is created
I have read some questions about that, but none works with my case. I want to send a mail to the User when he saves a new entry. post/models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.db.models.signals import post_save from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.dispatch import receiver class Post(models.Model): client = models.ForeignKey(User) date = models.DateTimeField(blank=True, editable=False) @receiver(post_save, sender=User) def first_mail(sender, instance, **kwargs): if kwargs['created']: user_email = instance.User.email subject, from_email, to = 'New Post', 'from@example.com', user_email text_content = render_to_string('post/mail_post.txt') html_content = render_to_string('post/mail_post.html') # create the email, and attach the HTML version as well. msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() This signal does not send any email. I am using mail_panel to track the email. -
django Sessions table entry when a user logs in
models.py from django.contrib.sessions.models import Session class CustomUser(AbstractUser): addr1= models.CharField(max_length=20) addr2= models.CharField(max_length=20) city= models.CharField(max_length=20) class UserSession(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,null=True) session=models.ForeignKey(Session,blank=True,null=True) views.py from django.contrib.auth.signals import user_logged_in from student.models import UserSession def user_logged_in_handler(sender,request,user, **kwargs): UserSession.objects.get_or_create( user= ?, session= ? ) user_logged_in.connect(user_logged_in_handler, sender=CustomUser) def delete_user_sessions(CustomUser): user_sessions=UserSession.objects.filter(user=CustomUser) for user_session in user_sessions: user_session.session.delete() In views.py what should i write in place of ? ...entry into sessions table is not getting created for every user log in...it is only getting created for admin id. What do i do? -
Django Rest Framework - Envelope for response
I'm wanting to convert an API from flask to Django Rest Framework. Currently, the requirements are that the responses are put inside of a basic json structure. eg. { "status": "success", "data": {actual results here} } What's the best way to do this? -
Create a no-model admin page in Django Mezzanine
how do i create a custom page in django mezzanine without a model? I've tried this, but it says page not found. class MyModelAdmin(admin.ModelAdmin): def get_urls(self): urls = super(MyModelAdmin, self).get_urls() my_urls = patterns('', (r'^admin/my_view/$', self.my_view) ) return my_urls + urls def my_view(self, request): #blahblahblah where view file is located: mezzanine/templates/admin/my_view.html -
Django inline admin, show remove option but disable delete?
So I have a relatively simple usecase that I want to achieve. When we display inline admins in django, we can either have the delete permissions or can disable them. If we disable delete, then both new inline elements added and old elements don't have remove/delete button. What I want is to, not show delete option on saved inline elements, but when a new inline element is added via admin, show the remove button. So far I have tried following : def has_delete_permission(self, request, obj=None): if obj is None: return True return False But obviously this won't work. -
Querying a Neo4j DB using Django
I apologize before hand as the Django way of thinking is still very alien to me. I am trying to generate a very simple page that justs lists all results from a simple cypher query using Neo4j and Django (1.9.7) and I am using the Python Neo4j driver to access the database from Django. However, I am getting stuck and have reached the point where I am just blindly trying things, as such I would like some pointers/advice on how the basics of what I am trying to achieve should look. models.py from django.views.generic.listimport ListView from neo4j.v1 import GraphDatabase, basic_auth # Connect to DB driver=GraphDatabase.driver("foo1",auth=basic_auth("foo2","foo3")) session=driver.session() # ListView is not the thing to use here; However, what should be used? models.Model seems the logical candidate to me but that yields several errors regarding INSTALLED_APPS class Stuff(ListView): query = "MATCH (t:Time) return t" results=session.run(query) # Sanity check -> This just shows that the database and query both work for foo in results: print foo break def __str__(self): return results views.py from django.views.generic.list import ListView from .models import Stuff # I assume that I should be using a ListView here (as I was trying to get a queryset or similar from my … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte
I am doing a File upload test with Django REST. Python3.6.2 Django1.11 djangorestframework==3.6.4 Excel-OSX 15.38(170902) OSX 10.12.6 It used to be done successfully with ordinary photo files. This time is Excel file from website. Here is my testcase copy from references. def test_upload_and_process_data_complete_case(self): from django.core.files import File from django.core.files.uploadedfile import SimpleUploadedFile from soken_web.apps.imported_files.models import ImportFile file = File(open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx')) uploaded_file = SimpleUploadedFile('new_image.xlsx', file.read(), content_type='multipart/form-data') data = { 'attribute': {'author': 'Sigh'}, 'type': ImportFile.FileType.zipcode, 'file': uploaded_file } response = self.client.post(reverse('api:import_file-list'), data, format='multipart') response.render() self.assertEqual(status.HTTP_201_CREATED, response.status_code) Like a copy cat. Except this time I download a mock file from https://www.mockaroo.com/. Here is the error raises when I execute file.read() file <File: /Users/el/Code/norak-cutter/soken/soken-web/soken_web/apps/zipcodes/complete.xlsx> file.read() Traceback (most recent call last): File "/Users/el/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/172.3968.37/PyCharm.app/Contents/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> File "/Users/el/.pyenv/versions/3.6.2/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte Confirmations: 1. I can upload file from my web browser 2. I can open that file without any warning messages. Question: Are there anything I forgot to concern? References: How can I test binary file uploading with django-rest-framework's test client? Django REST UnitTest … -
How to use allauth in Django to send a email to users who sign up
I am using allauth in my Django site to have users sign up. I want everyone who signs up to automatically receive an email that thanks them for signing up, etc. I couldn't find a setting for this in the allauth configuration (http://django-allauth.readthedocs.io/en/latest/configuration.html), but there must be a straight forward way to do this. Are there any ideas? Thank you very much. -
Python App working on local host, but not on Heroku
I have developed a simple inventory app and it is working well on local host, but it is only partially working on Heroku. It does not show any error, but it is shows only a static page and does not show any dynamically created contents. What could be the reason behind this problem? Here are the snapshots to make the difference clear: -
Google Cloud SQL: error in running "python manage.py makemigrations"
I am trying to run python manage.py makemigrations while this command is running on another terminal window ./cloud_sql_proxy -instances="test-project-181410:us-central1:poll-instance"=tcp:5432 After running python manage.py makemigrtions it takes awhile before giving me a response. However, its response is an error. See the screenshots below. This is my code in settings.py Your help is very much appreciated. Thank you -
django passing arguments from template to bash script
I am trying to have an input field in the template that the user enters a query and that query goes to the views.py and from there i m taking the query and pass it as argument to the bash script. This is what i have for now. views.py def home(request): if request.method == 'POST': try: query = request.POST['query'] test = subprocess.check_call(['home/.../bash.sh', query]) return render(request, 'base.html', {'input': test}) except KeyError: return HttpResponse("Nothing was submitted!") base.html <form action="/" method="post"> {% csrf_token %} <input type="hidden" name="query" value="{{ input }}"> <input type="submit" value="Submit"> </form> I am stuck right here..i don't know if i shout request.POST or something else much simpler...cause i don't want to use a form. -
Print stdout of function called inside Celery Task
I am using Django with Celery to call a task which in turn calls a function defined in the main function of an object (dr). I need to print the print statements found inside the main method of dr to the Celery worker's output. I have the following code in my tasks.py: from celery import shared_task from .generate_data import daq_runner as dr from datetime import timedelta import warnings @shared_task def generate_data_celery(): print("Testing Printing") dr I am successfully calling the generate_data_celery() from my front end, and I am seeing "Testing Printing" in the worker's output, but the print statements inside dr are nowhere to be found. Is there any way to capture these and redirect them to the stdout? This is the only output I am getting in the worker: [2017-09-29 12:53:10,396: INFO/MainProcess] Received task: daq_result.tasks.generate_data_celery[a24b91c5-56eb-4e0e-88cf-1d95353dc4f9] -
Django Database didn't migrate
school/models.py class School(models.Model): name = models.CharField(max_length=10,null=False) school_id = models.CharField(max_length=8,null=False) weather = models.ForeignKey(Weather,related_name="school") When I modified the school class by adding eng_name = models.CharField(max_length=50,null=False) After running the command python manage.py makemigrations school python manage.py migrate --fake-initial school python manage.py migrate school The messages both for the migrate are Operations to perform: Apply all migrations: school Running migrations: No migrations to apply. But the database didn't update. What is the possible reason to cause this issue? -
How can I set `celeryd` and `celerybeat` in Docker Compose?
I have a task that update per-minute. This is my Dockerfile for the Django application. FROM python:3-onbuild COPY ./ / EXPOSE 8000 RUN pip3 install -r requirements.txt RUN python3 manage.py collectstatic --noinput ENTRYPOINT ["python3", "manage.py", "celeryd"] ENTRYPOINT ["python3", "manage.py", "celerybeat"] ENTRYPOINT ["/app/start.sh"] This is my docker-compose.yml. version: "3" services: nginx: image: nginx:latest container_name: nginx_airport ports: - "8080:8080" volumes: - ./:/app - ./nginx:/etc/nginx/conf.d - ./static:/app/static depends_on: - web rabbit: hostname: rabbit_airport image: rabbitmq:latest environment: - RABBITMQ_DEFAULT_USER=admin - RABBITMQ_DEFAULT_PASS=asdasdasd ports: - "5673:5672" web: build: ./ container_name: django_airport volumes: - ./:/app - ./static:/app/static expose: - "8080" links: - rabbit depends_on: - rabbit This is the front-most log of my running container. rabbit_1 | =INFO REPORT==== 29-Sep-2017::11:45:30 === rabbit_1 | Starting RabbitMQ 3.6.12 on Erlang 19.2.1 rabbit_1 | Copyright (C) 2007-2017 Pivotal Software, Inc. rabbit_1 | Licensed under the MPL. See http://www.rabbitmq.com/ rabbit_1 | rabbit_1 | RabbitMQ 3.6.12. Copyright (C) 2007-2017 Pivotal Software, Inc. rabbit_1 | ## ## Licensed under the MPL. See http://www.rabbitmq.com/ rabbit_1 | ## ## rabbit_1 | ########## Logs: tty rabbit_1 | ###### ## tty rabbit_1 | ########## rabbit_1 | Starting broker... rabbit_1 | rabbit_1 | =INFO REPORT==== 29-Sep-2017::11:45:30 === rabbit_1 | node : rabbit@rabbit_airport rabbit_1 | home dir : /var/lib/rabbitmq … -
Django template: handling the href attribute as a conditional
Right now in my Django template I'm writing a whole new a tag if the conditional passes or fails. Is there a way to write this conditional in the a tag so that there is only one a tag? {% for app in apps %} {% if app.app_id == "app-smart" %} <a href='{{app.url}}' class='portfolio-link'> {% else %} <a href='{% url app.url %}' class='portfolio-link'> {% endif %} {% endfor %} -
How can I get my params in QueryDict?
I use the ajax pass the data to views.py: var params = {'nood_id':'f55dbe56-7fa8-4d13-8e1e-2dc67499b6ac'} $.ajax({ type:'post', url:'/api/nood_detail/', data:{'params':params}, dataType:'json', success:success_func, }) In the views.py, the request.POST is bellow: <QueryDict: {u'params[nood_id]': [u'f55dbe56-7fa8-4d13-8e1e-2dc67499b6ac']}> I can not use the request.POST.get("params") to get the param, nor can I get the nood_id. How can I get my params in QueryDict? -
Can't connect to Google SQL Proxy and project state suspended: Billing issue
I am trying to connect to my database in Cloud SQL using PostgresSQL. I am still in free trial period. I am stuck now, it says ready for new connections, but it's taking too long. Please help. I am following this instruction: https://cloud.google.com/python/django/flexible-environment?authuser=1 -
Django sub-subcategory for subcategory
How to add sub-subcategory for subcategory? For Category subcategory is added. For subcategory sub-subcategory is not added. Tried to render subid in a separate model, error DocPage has no attribute subid Model class DocPage(models.Model): title = models.CharField(max_length=300, default='', unique = True) parentid = models.ForeignKey('self',related_name='subcategories',blank=True,null=True) subid = models.ForeignKey('self', related_name='childsubcategories', blank=True, null=True) class ChildSubcategorySerializer(serializers.ModelSerializer): class Meta: model = DocPage fields = ('title', 'file', 'subid',) Serializers class SubcategorySerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() childsubcategories = ChildSubcategorySerializer(many=True, read_only=True) class Meta: model = DocPage fields = ('id', 'title', 'file', 'subid', 'childsubcategories',) class DocSerializer(serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField() subcategories = SubcategorySerializer(many=True, read_only=True) class Meta: model = DocPage fields = ('id', 'title', 'file', 'project', 'parentid', 'subcategories',) -
Replace foreign key dropdown with textbox with add/edit icon - Django
Related to foreign key fields in the Django Admin, the default display element is a drop down list box containing all of the foreign key items from the related model. I my app it will contain thousands of items and I am looking to change the admin interface and have it use a text box instead of the populated drop down. Looking for textbox with add/edit icon next to it, so that we dont get populated values, we just directly add or edit. Is there any way around to achieve it. -
Django: DoesNotExist: SocialApp matching query does not exist
I'm trying to activate social logins in my Django web application, which comes from open source software in this GitHub repository (so I didn't write it); and am running into this well-known issue: DoesNotExist: SocialApp matching query does not exist. The base settings file is located here. I do not modify that file at all. Instead, I import (inherit) it at the top of my deploy.py settings file, and make overrides and customization there. Specifically related to this issue, here are the relevant overrides and additions that I made in deploy.py to enable Google and Twitter social authentication, both of which result in the same error: INSTALLED_APPS.remove('allauth.socialaccount.providers.persona') # Remove INSTALLED_APPS.append('allauth.socialaccount.providers.google') # Add INSTALLED_APPS.append('allauth.socialaccount.providers.twitter') # Add _GOOGLE = { 'SCOPE': ['email', 'https://www.googleapis.com/auth/userinfo.profile'], 'AUTH_PARAMS': {'access_type': 'online'}, 'PROVIDER_KEY': get_env("GOOGLE_PROVIDER_KEY"), # Stored in secrets.env 'PROVIDER_SECRET_KEY': get_env("GOOGLE_PROVIDER_SECRET_KEY"), # Stored in secrets.env } SOCIALACCOUNT_PROVIDERS['google'] = _GOOGLE # This isn't enabled in biostar.settings.base _TWITTER = { 'SCOPE': ['email'], 'AUTH_PARAMS': {'access_type': 'online'}, 'PROVIDER_KEY': get_env("TWITTER_PROVIDER_KEY"), # Stored in secrets.env 'PROVIDER_SECRET_KEY': get_env("TWITTER_PROVIDER_SECRET_KEY"), # Stored in secrets.env } SOCIALACCOUNT_PROVIDERS['twitter'] = _TWITTER I show two provider examples here -- Twitter and Google -- to show the pattern of what I am doing, and to show that the issue isn't provider-specific; though let's … -
Django: Form validation strange behaviour
I want to do file validation(size,type) on a field on inlineformset. class ProductDocumentModelForm(ModelForm): class Meta: model = ProductDocument fields = ['document'] def clean_document(self): file = self.cleaned_data['document'] validate_file(file, 'document') Because I want to use the same validation in multiple application I created a separate function. def validate_file(file, for_model, max_size=5000): if for_model == 'document': max_size = FILE_MAX_DOC_SIZE if file.size > max_size: raise ValidationError('Please keep file size under {}. Current file size is {}' .format(filesizeformat(FILE_MAX_DOC_SIZE), filesizeformat(file.size))) The file size validation works as intended but introduce a strange behavior. If this validation is in place and is passed the "This field cannot be blank." default validation is triggered even if the fields are not empty. Without the file size validation in place there are no issue even if the fields are empty. I don't understand what is the cause. -
Gdal-Raster installing for windows
I have problem with Gdal-Raster. Soon i joined to the new project and cloned it from git. So i have installed all requirments txt and at last i have error that i can not understand and fix. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'GDALRaster' I can not understand what is GdalRaster and how install this? If somebody can help me please reply. Thanks in advance for the answer. -
Value Error:Cannot assign queryset to attribute it must be instance
I have models.py class employees(models.Model): emp_id=models.PositiveIntegerField() emp_name = models.CharField(max_length = 100) emp_lname = models.CharField(max_length = 100) emp_loc=models.CharField(max_length=5,choices=LOCATION) manager_id=models.ForeignKey('self',null=True,blank=True) class leave(models.Model): employee = models.ForeignKey(employees, on_delete=models.CASCADE, default='1') start_date = models.DateField() end_date = models.DateField() status=models.CharField(max_length=1,choices=LEAVE_STATUS,default='P') ltype=models.CharField(max_length=2,choices=LEAVE_TYPE) message=models.CharField(max_length=500,blank=True) class notify(models.Model): sender_id=models.ForeignKey(leave, related_name='%(class)s_sendername') receiver_id=models.ForeignKey(leave,related_name='%(class)s_receivername') date_time=models.DateTimeField() I have views.py def accept(request): approved_emp_id=leave.objects.filter(id=accept_id); approving_emp_id=leave.objects.filter(employee__emp_id=request.user.username); accept_notify=notify(sender_id=approving_emp_id, receiver_id=approved_emp_id,date_time=datetime.datetime.now(),viewed='N'); accept_notify.save() When I want to save values to database I am getting error as ValueError: Cannot assign "<QuerySet [<leave: 121-geeta-2017-10-04-2017-10-06-C-V-2017-09-27 07:48:36.288873+00:00>]>": "notify.sender_id" must be a "leave" instance. Where am I going wrong approving_emp_id and approved_emp_id are both leave instance only. -
Using drf-nested-routers with nested HyperlinkedIdentityFields
I am trying to generate nested HATEOAS links in a serializer using the drf-nested-routes package. My current setup would be as follows: /resource_a/<pk> /resource_a/<pk>/resource_b/<pk> /resource_a/<pk>/resource_b/<pk> /resource_a/<pk>/resource_b/<pk>/resource_c I am unable to create a HyperlinkedIdentityField that points to the last route. According to the documentation, one can create hyperlinked fields like this: nameservers = HyperlinkedIdentityField( view_name='domain-nameservers-list', lookup_url_kwarg='domain_pk') Or nameservers = NestedHyperlinkedRelatedField( many=True, read_only=True, # Or add a queryset view_name='domain-nameservers-detail' parent_lookup_url_kwargs={'domain_pk': 'domain__pk'} ) But these approaches fail when trying to reach a resource that is 2 layers deep in the URL hierarchy. The first method is not compatible, as it does not allow to add a second lookup_url_kwarg, and as for the second one, it throws an exception (ImproperlyConfigured) when configuring with the (in my opinion) proper attributes (resource_a__pk, resource_b__pk). Is this at all possible with this package? Otherwise I will resort to a simpler solution using a SerializerMethodField: resource_c = serializers.SerializerMethodField() def get_resource_c(self, obj): url = reverse('resource_b-resource_c-list', kwargs=dict(resource_a_pk=obj.resource_a.pk, resource_b_pk=obj.pk)) return self.context['request'].build_absolute_uri(url) Thanks in advance! -
how to create dynamic Row/Col table in reactjs
i am trying to render a table using react, there are three entities, Criteria(Row), Rating(Col), and explanation (at their intersection). Row/col can be added i am able to render criteria, rating and explanation, but i want to add a /Popover button if the explanation does not exist. For ex use case R1 R2 R3 R+ C1 E1 E2 C2 E3 C+ At all the empty places i want to add a popover to add Explanation. I am using reactjs, graphql, ant-d, Following is the code for looping return ( <div> { <FlexRow> {" "} <FlexCol key={"rating.id"} span={24 / (ratings.length + 2)}> <CriteriaRatingBox> <CriteriaRatingTitle>{"index"}</CriteriaRatingTitle> </CriteriaRatingBox> {ratings.map((rating, i) => ( <CriteriaRatingBox> <CriteriaRatingTitle>{rating.title}</CriteriaRatingTitle> </CriteriaRatingBox> ))} <CriteriaRatingBox> <Popover content={ <RubricRatingsForm requirementId={this.props.requirementContextId} handleMcAddRubricRating={ this.props.handleMcAddRubricRating } /> } > <CriteriaRatingTitle>{"+Add Rating"}</CriteriaRatingTitle> </Popover> </CriteriaRatingBox> </FlexCol> </FlexRow> } {criteria.map((criteria, i) => ( <FlexRow> <FlexCol key={criteria.id}> <CriteriaBox>{criteria.description}</CriteriaBox> </FlexCol> {ratings.map((rating, i) => ( <div> <FlexCol key={rating.id} span={24 / ratings.length + 1}> <CriteriaRatingBox> {criteria.explanations.map((explanation, i) => ( <Popover content={ <EditRubricExplanationForm handleEditRubricExplanation={ this.props .handleMcRequirementEditRubricExplanation } rubricExplanation={explanation.description} rubricExplanationId={explanation.id} toggleEditRubricExplanationOpen={ this.toggleEditRubricExplanationOpen } /> } > <CriteriaExplanation> {explanation.rating.id === rating.id && explanation.criteria.id === criteria.id && ( <RichTextEditor rawData={explanation.description} /> )} </CriteriaExplanation> </Popover> ))} </CriteriaRatingBox> </FlexCol> </div> ))} </FlexRow> ))} <FlexRow> <FlexCol> <Popover content={ <RubricCriteriaForm requirementId={this.props.requirementContextId} …