Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pythonanywhere website is idle after deployment [on hold]
I deployed a django app to http://rishus23.pythonanywhere.com/ following the tutorial on pythonanywhere but my website seems to be static as when I click on join chat button nothing happens. -
OSX Django Project makemigrations error: Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
Python 2.7.10 System: Mac OS Sierre I've installed mysql-python, and the connection to local mysql was all good. But in the PyCharm manage.py command line, when I tried to run makemigrations command, the following error message came up: bash -cl "/Users/alan/.virtualenvs/testvir/bin/python /Applications/PyCharm.app/Contents/helpers/pycharm/django_manage.py makemigrations /Users/alan/PycharmProjects/djangoStart" Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) I'm wondering if anyone has a fix on this? -
Django Template Does not exist with string literal
Inside Django I have a template that when specified explicitly with return "letter.html" -- everything works as expected class letterView(PDFTemplateView): def get_context_data(self, **kwargs): letterID = self.kwargs['letterID'] object = get_object_or_404(djangoLetters, id=letterID) return super(letterView, self).get_context_data(object=object,**kwargs ) def get_template_names(self): letterID = self.kwargs['letterID'] letterType = djangoLetters.objects.get(pk=letterID).letterType #template_name = str(letterType.letterBackgroundBase) template_name = "letter.html" return template_name However, when I use str(letterType.letterBackgroundBase) which returns letter.html -- I get an error saying that the Template can not be found for "letter.html". I expect the problem has something to do with unicode literals, but I've tried importing the future unicode line at the top of the service/view as well as using django's smart_str built in utilities. The file is definitely there and works when called explicitly, but when it's coming from an object, even though "letterType.letterBackgroundBase" returns back "letter.html" something is still failing. Any thoughts? -
Form not being validated because of file attachment
My form won't validate in my view function. The file not getting properly sent to the view function is my guess. my form <form enctype="multipart/form-data" action="{% url 'kar:createItem' %}" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> my view def createItem(request): form = itemCreateForm(request.POST) if form.is_valid(): model_instance = form.save(commit=False) model_instance.save() with open(BASE_DIR + '/kar/products.js', 'r+') as json_file: products = json.loads(json_file.read()) products['products'][model_instance.pk] = model_instance.returnAsJSON() json_file.seek(0) json_file.write(json.dumps(products)) else: print(form.errors) return HttpResponseRedirect('/Karklude/CMS/') my settings and urls.py #settings MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' #urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my view function I have the if_valid(), it'll go to the else statement and print out the following: <ul class="errorlist"><li>image<ul class="errorlist"><li>This field is required.</li></ul></li></ul> From the This field is required. It looks like the file is not being processed properly to the server or something? -
Python3+Django1.10+mysqlclient1.3.9: cannot save emoji characters
I got the error below in django when saving a field with emoji character in the admin panel. OperationalError at /admin/core/message/add/ (1366, "Incorrect string value: '\xF0\x9F\x98\x9E \xF0...' for column 'name' at row 1") I'm sure the database is ready for utf8mb4, because I can write/read these emoji character in phpmyadmin. More, the saved emoji character displayed correctly in phpmyadmin but displays ??? in django output. And in my another django project, the emoji plays well, till I just cannot find the difference between the two environment. So what can be the problem when I save the same thing using python? -
Django-cms page view restrictions
I have just started using django-cms to create a website, and I'm generally impressed with what you can do with it out of the box. However, I want to restrict the viewing of some pages, so that only registered users with a certain attribute or credential, can view restricted pages. The way I intend to proceed is as follows: Introduce a credential system (with expiring date) for users - is there a package that already exists for this, or do I need to write my own? Provide a 'page category' attribute for ALL pages in the blog Provide a mapping mechanism from 'page category' to credential required to view the page Insert logic to check whether current user has the required credential to view the requested page, before displaying the page (if user has the required credential), or directing user to another page if user does not have credentials required. My question is twofold: A. Is the problem decomposition I have described above a good way to implement the solution - or is the a better way that involves using existing packages without reinventing the wheel (if so, which packages to use)? B. If I have to write my own … -
Integrating pinax-notifications failed in django app
i working with django-1.10 and would like to implement some notification behaviour for my application using pinax-notifications-4.0. I am following the quickstart for including this to the INSTALLED_APP INSTALLED_APPS = [ # ... "pinax.notifications", # ... ] then and the usage guide. First is to create the notice type in heat/handler.py from django.conf import settings from django.utils.translation import ugettext_noop as _ def create_notice_types(sender, **kwargs): NoticeType.create( "heat_detection", _("Heat Detected"), _("you have detected a heat record") ) Secondly call the handler to create notices after the application is migrated. heat.apps.py from .handlers import create_notice_types from django.apps import AppConfig from django.db.models.signals import post_migrate class HeatConfig(AppConfig): name = 'heat' def ready(self): post_migrate.connect(create_notice_types, sender=self) finally include the appconfig to the heat.__init__.py default_app_config = 'heat.apps.HeatConfig' but when trying to run these: python manage.py makemigrations pinax.notifications I got this error: RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Then i try to change the pinax.notifications to pinax-notifications in the INSTALLED_APPS. The server yield me this error: ImportError: No module named pinax-notifications How to make this work? -
How to uninstall pip packages on Elastic Beanstalk
How to uninstall pip packages on Elastic Beanstalk? We removed a package in our requirements.txt file, but we think the package is still there because its causing a namespace collision with another app we created with the exact same name. details: We used to have this package django-whatever. In our .py files, it was imported like from whatever import something the package wasn't giving us enough control, so we rolled out our own package called whatever which we use like from whatever import goodstuff AWS EB now returns an error "cannot import goodstuff from whatever" which heavily implies that django-whatever is still installed even tho its not in requirements.txt -
django use a model before its definition in another model
I am trying to build a messaging app. models: class Thread(models.Model): subject = models.CharField(max_length=255, blank=True, null=True) user = models.ManyToManyField(User, related_name='thread_set') def thread_creator(self): return self.message_set.first().sender class Message(models.Model): thread = models.ForeignKey(Thread, related_name='message_set', blank=True, null=True) pub_date = models.DateTimeField(default=timezone.now) sender = models.ForeignKey(User) body = models.TextField() So, when a message is sent, a new thread is created. And that first message will have a foreignkey relation with that thread. So, any other messages sent to this thread will have its foreignkey relation with the thread. This is working fine. However, suppose I want to add a reply to a particular message. So now, it should create a new thread for that message, and a message can only have one thread (which will hold other reply messages). This makes one to one relation of the new thread with that message. So, I changed the Thread model to this: class Thread(models.Model): subject = models.CharField(max_length=255, blank=True, null=True) user = models.ManyToManyField(User, related_name='thread_set') message = models.OneToOneField(Message, blank=True, null=True) But, since Message model is not defined yet, it gives me error: NameError: name 'Message' is not defined How can I use a class model before its defined? Or is there any other way around to solve the problem? -
How to Avoid multi post request by one click?
I have a simple form which adds personal information of a family. sometime it saves two instance of a person just by one submit. Maybe my mouse has problem and and double clicks instead of one click (it has some problems). I think this is not possible and django accepts just one post request from an instance of a form and not more (maybe it accepts). what if may code has problem? if it is problem of my code, why it happens once a while? house = get_object_or_404(House, id=code) if request.method == 'POST': form = ParentForm(request.POST) if form.is_valid(): # save it if it's valid parent = form.save(commit=False) if parent.living == 0: parent.in_family = 0 if not parent.guardian: parent.save() if parent.guardian and parent.in_family: parent.save() -
How to deal with this StaleElementReferenceException in Selenium?
I'm currently going through an intro to Django/TDD book and I've hit __ and got stuck. I've been googling around and searching StackOverflow for a solution to my error, but I haven't been able to work around it. My relevant code is as follows: functional_tests.py inputbox.send_keys(Keys.ENTER) self.browser.implicitly_wait(3) table = self.browser.find_element_by_id('id_list_table') #rows = table.find_elements_by_tag_name('tr') rows_ref = lambda: table.find_elements_by_tag_name('tr') #self.browser.implicitly_wait(3) foundBuy = False for row in rows_ref(): self.browser.implicitly_wait(3) rows_text = row.text if (rows_text == '1: Buy peacock feathers'): foundBuy = True break if not (foundBuy): self.fail('Could not find "1: Buy peacock feathers" in rows\' text') #self.assertIn('1: Buy peacock feathers', [row.text for row in rows_ref()]) The error occurs in the above code at the "rows_text = row.text" line of code. In my original code, it occurred in the commented out self.assertIn statement at the bottom. home.html <html> <head> <title>To-Do lists</title> </head> <body> <h1>Your To-Do list</h1> <form method="POST"> <input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/> {% csrf_token %} </form> <table id="id_list_table"> {% for item in items %} <tr><td>{{ forloop.counter }}: {{ item.text }}</td></tr> {% endfor %} </table> </body> </html> The original code the book has me enter is commented out (minus the one implicity_wait). In my previous time going through this book, the code … -
Retrieving User with Django API
I am trying to create a standard API call for user login. For example, I would POST a 'username' and 'password' to an API View, it would query the database in search of those parameters, and return the full User JSON back if found. I am fairly new to Django and Python, but I have been working with Django Rest Framework. I have managed to make it so I can create/update users, but haven't figured how to query data correctly yet. Should I be looking to create a new view? or build on the UserViewSet that I already created? I am not sure how to build the URLS properly for this type of task either. VIEWS # Create your views here. @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'ideas': reverse('idea-list', request=request, format=format), 'ideacomments': reverse('ideacomment-list', request=request, format=format) }) # class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView): # queryset = User.objects.all() # serializer_class = UserSerializer # lookup_fields = ('username', 'password') class UserViewSet(MultipleFieldLookupMixin, viewsets.ModelViewSet): """ This viewset automatically provides `list` and `detail` actions. """ queryset = User.objects.all() serializer_class = UserSerializer def retrieve(self, request, pk=None): queryset = User.objects.all() serializer_class = UserSerializer lookup_fields = ('username', 'password') SERIALIZERS class UserSerializer(serializers.HyperlinkedModelSerializer): ideas = serializers.HyperlinkedRelatedField(many=True, view_name='idea-detail', read_only=True, allow_null=True) ideacomments … -
Display static images with url from dict in template
I'm having some trouble displaying my images if the url value comes from a dict. if I do below it works. {% for key, values in images.images.items %} <div class="imageBox"> <img src="{% static 'images/ka/1.jpg' %}" alt="My image" width=100% height=100%/> </div> {% endfor %} But I'd like to use the url values from the dict iteration instead. Like below {% for key, values in images.images.items %} <div class="imageBox"> <img src="{% static '{{values}}' %}" alt="My image" width=100% height=100%/> </div> {% endfor %} value {{values}} = 'images/ka/1.jpg' But this dosen't work even tho {{values}} is 'images/ka/1.jpg' like the previous example. If I inspect the html in my browser it shows the src is /static/%7B%7B%20values%20%7D%7D. Why is it different? -
Automatically detect test coupling
We have a large test codebase with more than 1500 tests for a Python/Django application. Most of the tests use factory-boy for generating data for the project models. Currently, we are using nose test runner, but open to switching to py.test. The problem is, from time to time, when running parts of tests, combination of tests we encounter unexpected test failures that are not reproduced when running all the tests or these tests individually. It looks like the tests are actually coupled. The Question: Is it possible to automatically detect all the coupled tests in the project? My current thinking is to run all the tests in different random combinations and report the failures, can nose or py.test help with that? -
Show user's group in django tables2
This is my first time posting on stackoverflow, i hope i'm respecting the rules. As for my question , i'm new to django and using the default django models ( User and Group ) and i'm trying to display the user's group in a table rendered with django tables2. The table is written as follows: class UserTable(tables.Table): selection = tables.CheckBoxColumn(accessor="pk", attrs={"th__input": {"onclick": "toggleall(this)"}}, orderable=False) user = User.objects.get(id=2) usergroup = Group.objects.get(user=user) username = tables.LinkColumn('edituser', args=[A('pk')]) first_name = tables.Column() last_name = tables.Column() # group= tables.Column(accessor='Group.name') group = tables.Column(accessor='user.groups.group_id') class Meta: template = 'django_tables2/bootstrap.html' attrs = {'class': 'table table-bordered table-striped table-hover'} sequence = ('selection','username', 'first_name', 'last_name', 'group') Thank for helping -
Why can't I run django app outside visual studio?
I have setup a Python/Django application in Visual Studio, and it works fine. I can also use django commands if I open prompt from Visual Studio itself like: And command line runs ok from there: But if I manually open cmd and go to same folder to run same command I get: Why I can't run it from a command line that isn't opened from Visual Studio? Sometimes I just want to manage.py runserver, but I need to open Visual Studio, run the command and then shut it down and leave prompt open. There's some way to avoid using Visual Studio to run those django commands? I'm also interested in developing such django app in Visual Studio Code sometimes, how could I configure it to run there? Obs: My env is a Python 3.x + Windows 10 + Visual Studio 2015 -
AttirbuteError: read when trying to post an image using Python Facebook SDK (in a Django proj)
In a Django web app of mine, users post photos on the website. Once photos accumulate high enough upvotes, I post them to a Facebook fan page using this function from the Python Facebook SDK. Initial tests of the SDK work correctly. One simply passes a file object representing the image, and a caption to graph.put_image() method, and it works. But I can only get it to work when the image is being uploaded from the client. I'm struggling if an image object is already saved on the server; then the SDK throws an AttributeError: read error. I might be making a rookie mistake, so please advise. I get the error when I do: from PIL import Image api.put_photo(image=Image.open(photo.image_file),message='my caption') Where the photo object is defined as follows in my models.py: class Photo(models.Model): image_file = models.ImageField(upload_to=upload_photo, storage=OverwriteStorage()) upload_time = models.DateTimeField(auto_now_add=True) OverwriteStorate() is an overwritten Django Storage class (imported from django.core.files.storage). It contains functionality to upload to Azure blob storage, and has been working correctly. upload_photo_to_location is simply: def upload_photo(instance, filename): try: blocks = filename.split('.') ext = blocks[-1] filename = "%s.%s" % (uuid.uuid4(), ext) instance.title = blocks[0] return os.path.join('photos/', filename) except Exception as e: print '%s (%s)' % (e.message, type(e)) return … -
Django urlpatterns, instances?
From the official docs: urlpatterns should be a list of url() instances. For example: from django.conf.urls import include, url urlpatterns = [ url(r'^index/$', index_view, name='main-view'), url(r'^weblog/', include('blog.urls')), ... ] Here is where I get confused, url() is not just a function ? Why they use OO terminology or thats valid or I missing something? -
Keep getting "Could not resolve URL for hyperlinked relationship using view name "songs"
I have the following model class: # Song Model class Song(models.Model): title = models.CharField(max_length=200) artist = models.CharField(max_length=200) content = models.TextField() user = models.ForeignKey('auth.User', related_name='songs') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): # __unicode__ on Python 2 return self.title + ' ' + self.artist class Meta: ordering = ('title',) My serializers class SongSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ('id', 'title', 'artist', 'content') model = Song class UserSerializer(serializers.ModelSerializer): songs = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='songs' ) class Meta: model = User fields = '__all__' and my views class SongViewSet(viewsets.ModelViewSet): queryset = Song.objects.all() serializer_class = SongSerializer class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer I am trying to get the list of songs but I keep getting this error ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "songs" This has been working with PrimaryKeyRelatedField but not as it is now. -
Link to a specific div in another app(page) in Django using anchor tag
I have a div with a certain id <div id="services"> Then I try to link to it using Django templates <a href="{% url 'homepage' %}#services"> But it only works if I'm in the same page (App) Is there a way to work around this ? -
Referencing if/then statements with a model?
I have a site for my students where I have pulled in a bunch of information from different websites they use for instruction. I want to be able to award 'badges' if they meet certain criteria, like reading 50 books, or spending 100 minutes practicing math, etc. That data is stored as objects in different models on my site. I can't figure out how to cleanly make different badge objects with unique requirements for unlocking each badge without being incredibly repetitive. My basic model: class Sticker(models.Model): name = models.CharField(max_length=255,) slug = models.CharField(max_length=255,) image = models.ImageField(upload_to='stickers') #requirements = ? I'd like to be able to easily add badges with just a line of code like this as the requirement: if books_read >= 50: return True Part of the complexity is that there are a lot of different types of requirements with different models for all the different "Stickers" they can earn. I tried Django Badgify but ran into a couple issues. My students aren't actual Django Users, and I don't know how to separate that part out, as the script is far more complex than I'm currently able to modify with my skillset. What's the best way to work in a … -
Secure browser-based S3 uploads: signed policy doc or presigned URL?
I want to allow users to upload files directly from their browser to an S3 bucket. I've seen some recommendations for signing policy documents on the server, and others that suggest creating a pre-signed URL on the server and passing it back to the client. For example, this Django REST Framework library provides options for both: https://github.com/bodylabs/drf-to-s3 What are the advantages/disadvantages from a security perspective? -
Django REST Framework Login
I am not really understanding why I am unable to login as a user that I created using Django REST Framework. I am using the User Model from django.contrib.auth.models import User. I am spinning up the server locally, and can log in with a superuser that I created and access the data I want to, but I have created the API such that I can create Users through the browsable API, and I wish to log in with one of those users. However I am not able to. Any suggestions? For the picture below, I would not be able to login using 'test' username, and 'test123' password. -
django+nginx+uwsgi, Django response time too long
I've django application hosted in AWS EC2 instance using uWsgi+nginx.I'm using a t2.medium instance. The django app was working fine in the heroku app. But after the migration the response time app seems to be too long and it started giving 504 timeout errors. The following are my nginx and uwsgi configs: uwsgi.ini [uwsgi] master = true socket = /tmp/nginx.sock chmod-socket = 666 chdir = /home/nijo/nginx-test/sample wsgi-file = /home/nijo/nginx-test/sample/sample/wsgi.py virtualenv = /home/nijo/nginx-test/sample_env processes = 12 threads = 4 vacuum = true enable-threads = true daemonize= /home/nijo/nginx-test/sample/testuwsgi.log nginx.conf server { listen 443 ssl; server_name example.com; error_log /home/nijo/nginx-test/nginx.log; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.fiz.com/privkey.pem; client_max_body_size 1024M; uwsgi_read_timeout 1800; uwsgi_send_timeout 1800; uwsgi_connect_timeout 1800; keepalive_timeout 1800; location / { uwsgi_pass unix:///tmp/nginx.sock; include uwsgi_params; } } The timeout issue was fixed by timeout parameters in nginx. But i really need to decrease the response time of my django application. Is there any extra parameters in uwsgi that i can use to increase the response time. The app was working fine in heroku. So i just tried the aws with gunicorn. Now the app is having much performance than while i was uwsgi. Why is my app not working properly with uWsgi. -
Django Rest Framework, add object to request.data and then call serializer is_valid()
I'm wondering which is the best way to solve this, I have a nested serializer like this: serializers.py: class PaymentMethodSerializer(serializers.ModelSerializer): data = serializers.JSONField() payment_type = PaymentTypeSerializer(required=False) Then, the view looks something like this: class PaymentMethodView(APIView): def put(self, request, id): try: payment_method = PaymentMethod.objects.get(id=id) except ObjectDoesNotExist: return Response("No PaymentMethod with that id", status=status.HTTP_404_NOT_FOUND) payment_method_serialized = PaymentMethodSerializer(instance=payment_method, data=request.data) payment_type = request.data.get("payment_type", None) if payment_type: try: payment_method_type = PaymentType.objects.get(id=payment_type) except ObjectDoesNotExist: payment_method_type = None else: payment_method_type = None # Now, call is_valid() if payment_method_serialized.is_valid(): payment_method_serialized.save(payment_type=payment_method_type) return Response(payment_method_serialized.data, status=status.HTTP_200_OK) is_valid() returns False and this error: {"payment_type":{"non_field_errors":["Invalid data. Expected a dictionary, but got int."]}} I understand it, I'm giving the serializer a pk. However I don't want to create a new serializer with a PrimaryKeyRelatedField instead of the nested relationship just for this. How can I get the PaymentType that corresponds to that pk and then add that object to the request.data dictionary so that is_valid doesn't fail? is it the best way to solve this?