Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django jquery file upload: linking to another model
Setting up django-jquery-fileupload https://github.com/sigurdga/django-jquery-file-upload and it works, here's the model # encoding: utf-8 from django.db import models class Picture(models.Model): """This is a small demo using just two fields. The slug field is really not necessary, but makes the code simpler. ImageField depends on PIL or pillow (where Pillow is easily installable in a virtualenv. If you have problems installing pillow, use a more generic FileField instead. """ file = models.FileField(upload_to="uploads") slug = models.SlugField(max_length=50, blank=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('upload-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(Picture, self).save(*args, **kwargs) def delete(self, *args, **kwargs): """delete -- Remove to leave file.""" self.file.delete(False) super(Picture, self).delete(*args, **kwargs) and the view # encoding: utf-8 import json from django.http import HttpResponse from django.views.generic import CreateView, DeleteView, ListView from .models import Picture from .response import JSONResponse, response_mimetype from .serialize import serialize class PictureCreateView(CreateView): model = Picture fields = "__all__" def form_valid(self, form): self.object = form.save() files = [serialize(self.object)] data = {'files': files} response = JSONResponse(data, mimetype=response_mimetype(self.request)) response['Content-Disposition'] = 'inline; filename=files.json' return response def form_invalid(self, form): data = json.dumps(form.errors) return HttpResponse(content=data, status=400, content_type='application/json') for now ignoring how behind the scenes it uploads the images, what I do however need to figure out is … -
Django - How to reorder model objects
Let's say I want to reorder fruits. Somewhere in the code I call fruit.reorder(3) where fruit is the fruit I want to move and 3 is the ID after which I want to insert the fruit. Before calling reorder, fruits where in the following order : 4,3,6,1. And now, given that the calling fruit is 1, the order would be : 4,3,1,6. How should I implement def reorder: in Fruit.py model to achieve this ? -
Django raises NoReverseMatch: 'en-us' is not a registered namespace
Django raises django.urls.exceptions.NoReverseMatch: 'en-us' is not a registered namespace How i can fix it? -
Schedule task in Django using schedule package
I am trying to learn how to scheduled a task in Django using schedule package. Here is the code I have added to my view. I should mention that I only have one view so I need to run scheduler in my index view.. I know there is a problem in code logic and it only render scheduler and would trap in the loop.. Can you tell me how can I use it? def job(): print "this is scheduled job", str(datetime.now()) def index(request): schedule.every(10).second.do(job()) while True: schedule.run_pending() time.sleep(1) objs= objsdb.objects.all() template = loader.get_template('objtest/index.html') context= { 'objs': objs} return HttpResponse(template.render(context, request)) -
How can I get the IP address of RabbitMQ running from another container (Docker Compose)?
I am following this tutorial. In there, I need to set RabbitMQ IP address to my Celery settings. I have three containers in my docker-compose.yml: NGINX, Django + Celery, and RabbitMQ. These are all run with docker-compose up. However, I need to have the RabbitMQ IP address for celery.py in different container. Looking through Google, docker-machine ip <container> should be the solution. However, docker-machine only works for running container, AFAIK. So, how can I pass container IP address to another container in same docker-compose.yml file? In this case I want to have my RabbitMQ IP address. -
customize django admin object detail page url(object change url)
I am trying to override the default django admin change url. I my table i have composite primary key. class ABC(models.Model): code = models.ForeignKey('PQR', models.DO_NOTHING, db_column='code', primary_key=True) language = models.ForeignKey(Languages, models.DO_NOTHING, db_column='language') me_name = models.TextField() common_name = models.TextField(blank=True, null=True) abbreviation = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'abc' unique_together = (('code', 'language'), ('language', 'me_name'),) Now my admin url in django admin for each object is /admin/home/abc/{{code}}/change/. But i have repeated codes in objects because primary key is composite of ('code', 'language'). So for objects which have repeated code are throwing Error MultipleObjectsReturned at /admin/home/abc/X00124/change/ get() returned more than one ProcedureTranslations -- it returned 2! here X00124 this code associated with more than one object. What i want here that override the modeladmins get_urls() method and construct the url /admin/home/abc/{{code}}/{{language}}/change/. I tried but no success. Help will be appreciated. -
Django+Jinja2+i18n: jinja2.exceptions.UndefinedError: 'gettext' is undefined
I'm trying since many hours to get things work, but still without success. I use Jinja2 with Django (https://docs.djangoproject.com/en/1.11/topics/templates/#django.template.backends.jinja2.Jinja2) and now I try to enable translations. Jinja2 docs suggest (http://jinja.pocoo.org/docs/2.9/extensions/#i18n-extension) existing extension (jinja2.ext.i18n). So my configuration looks like this: settings.py TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": [os.path.join(BASE_DIR, 'templates')], "APP_DIRS": False, 'OPTIONS' : { 'environment': 'config.jinja2.environment' } }] jinja2.py: def environment(**options): env = Environment(**options, extensions=['jinja2.ext.i18n']) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, 'dj': defaultfilters }) return env within template: {{ gettext('...') }} result: jinja2.exceptions.UndefinedError: 'gettext' is undefined Does anyone know what the problem is and what I miss? thanks for help in advance! -
Can't edit richtext field in Wagtail
We have a magazine and use Django project and Wagtail. We came upon a very bizarre bug: One of our remote editors is unable to edit one specific field, that is the main content body of the page. He is able to see the text, but when tries to click nothing happens. It does not enter edit mode, like it is disabled, but ONLY for him: He is not trying locally, he is trying live, so there is not a difference between Wagtail versions He cannot edit using his credentials, or any other credentials He tried different browsers and different computers I tried with his credentials and I am able to edit Any idea of what could be causing this? Could the location have something to do? -
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]