Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - How to handle exception on serializer create()?
I'm using the friendship Django module with Django Rest Framework. When creating an API the Serializer's create() may raise some exceptions - AlreadyFriendsError, DoesNotExist or AssertionError. Now when an exception occurs, the return object is not valid (None) and I get a Traceback with the AssertionError: create() did not return an object instance. From my API views.py class FriendManageAPIView(CreateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = FriendManageSerializer def post(self, request, *args, **kwargs): if request.data['action'] == 'add_friend': return self.create(request, *args, **kwargs) From my API serializers.py class FriendManageSerializer(serializers.ModelSerializer): to_user = serializers.CharField(max_length=150) def create(self, validated_data): friendship_ret = None try: request = self.context.get("request") if request and hasattr(request, "user"): user = request.user user_model = get_user_model() to_user = user_model.objects.get(username=request.data['to_user']) friendship_ret = Friend.objects.create( from_user=user, # The sender to_user=to_user, # The recipient ) friendship_ret.save() except (AlreadyFriendsError, user_model.DoesNotExist, AssertionError): print("EXCEPTION FriendManageSerializer.create()") return friendship_ret How should I really handle this case? What should I be returning when the object is not valid? -
django file save path is not media path
I'm having trouble getting the URL look right for a file after it's saved to the database. Here's what I'm doing: file_generator.py out_data = 'test text' out_file = open(settings.MEDIA_ROOT + '/post_ship.txt', 'w') myfile = File(out_file) myfile.write(out_data) out_file.close() file_location = settings.MEDIA_ROOT filename = '/post_ship.txt' return file_location, filename Then here's the views.py views.py if form.is_valid(): cd = form.cleaned_data file_location, filename = create_primary_config(cd) with open(file_location + filename, 'rb') as out_file: myfile = File(out_file) tenant = Tenant.objects.get(pk=cd['tenant'].id) Config(tenant=tenant, failover=True, config_file=myfile).save() And lastly, here's my models.py: models.py def save(instance, filename): return filename class Config(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE) failover = models.BooleanField(default=False) config_file = models.FileField(upload_to=save) Everything above is working as expected EXCEPT that it's saving two copies of the file in my media folder, and when I go to my database entry in the Django admin, the path listed for the file is /home/ubuntu/workspace/projectname/media/post_ship_SySI4iw.txt. So when you click that link, it tries to take you to that URL, which doesn't work. If I manually go to the URL media/post_ship_SySI4iw.txt, it works and the file pulls up. Any idea why: 1) It's saving 2 versions of the file (post_ship.txt, and post_ship_SySI4iw.txt 2) why the file path is not being saved as just /media/ as opposed to /home/ubuntu/workspace/projectname/media/ -
Test Upload Excel File and JSONField Django REST
My models.py has 3 fields. One of them is JSONField() attribute = JSONField(null=True, blank=True) # Free to add any note to here type = models.CharField(max_length=30, choices=FileType.choices, default=FileType.zipcode) file = models.FileField(upload_to='import_files') I normally set JSONField(null=True, blank=True) for the sake of easiness. def test_upload_and_process_data_complete_case(self): from soken_web.apps.imported_files.models import ImportFile with open(str(settings.BASE_DIR) + '/apps/zipcodes/complete.xlsx', 'rb') as uploaded_file: data = { 'attribute': {'author': 'Singh'}, '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) And my test runs fine without shooting with JSONField Experiment: When I shoot with JSONField like the given. It will failed with this error AssertionError: Test data contained a dictionary value for key 'attribute', but multipart uploads do not support nested data. You may want to consider using format='json' in this test case. However, from my understanding I have to post with multipart because of file. Question: Is it possible to do unittest shoot the endpoint that has JSONField and FileField in the same time? Reference: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 14: invalid start byte -
Best way to filter ListView with drop down form in Django
I'm trying to filter a ListView based on Users, using a drop down form. models.py class Post(models.Model): ... author = models.ForeignKey('auth.User', verbose_name="Post Author") views.py class PostList(ListView): model = Post context_object_name = 'posts' def get_queryset(self): result = super(PostList, self).get_queryset() author_filter = self.request.GET.get('author') if author_filter: result = Post.objects.filter(Q(author__icontains=author_filter)) return result post_list.html <form action="" method="get"> <select name="author" onchange="this.form.submit();"> <option selected="selected" disabled>Select an author</option> {% all_author as authors %} {% for author in authors %} <option value="{{ author }}">{{ author }}</option> {% endfor %} </select> </form> I am using a custom template tag to render all_authors and this works fine. When selecting an author, in the urls I can see something is passed (/?author=xxx), but the list is not filtered. -
Global variable only for one user
I'm building a Django App and I need your help in order to manage sessions of my users. For now, my index.html is my login page. It is a form (username,password). When user clicks on login, i get the form, compare it to my users SQL Table, then if it matches, I render some global variables (firstname1,lastname1) to profil_page.html . Let's say i just login with (username1,password1). When i try my app on another computer, with another login (username2,password2) , it takes me to profil_page.html and i can see (firstname2,lastname2) on my page. The problem is, when i go back to my first computer which was logged in (username1,password1), i refresh the page and now i see (firstname2,lastname2) on the page. I guess it is a problem of sessions. I want my global variable to be for one computer, not for my entire app. Thanks very much in advance. -
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 …