Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I list all of the items in a dictionary by biggest value to lowest value using Python and Django?
So I have this as my html file. <form method="post"> {% csrf_token %} Problem: <input type="text" name="poi" autofocus> <input type="submit" value="Submit"> <hr> </form> <br> <ul> {% for u in sort %} <li>{{ u|safe }}</li> {% endfor %} <ul> and I have my variable called sort which takes all of the items in a dictionary dictionary = {'hi': 5, 'hey': 3, 'hiya': 1} and sort them by highest to lowest value using the following. for w in sorted(dictionary, key=dictionary.get, reverse=True): sort.append(w) Now the list is in order from highest to lowest values. As you can see in the html file, I am trying to print them all in order. What's going wrong is that it's not printing anything. What am I doing wrong? -
How should is a procfile made?
I have made a project named mysite with django i cloned it to a directory named tes the directory is as followed. As you can see the procfile is in correct directory. test ├── blog ├── db.sqlite3 ├── manage.py ├── mysite │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-35.pyc │ │ ├── settings.cpython-35.pyc │ │ ├── urls.cpython-35.pyc │ │ └── wsgi.cpython-35.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── procfile ├── Procfile ├── requirements.txt The Procfile is as follows: web: gunicorn mysite.wsgi --log-file - I have also tried web: gunicorn test.wsgi --log-file - but still i get the error no web process runnig. -
Django serializer classes referencing each other
I need to have two serializer classes referencing each other but I'm getting one of the classes not defined if both classes are referencing each other. I created a duplicate of one of the class w/ a difference name and this seems to work but is there a better way to do this without making 3 classes? class ArtistSerializer(serializers.ModelSerializer): name = serializers.CharField() class Meta: model = Artist fields = ('id', 'name',) class TrackSerializer(serializers.ModelSerializer): artist = ArtistSerializer(read_only=True) class Meta: model = Track fields = ('id', 'artist', 'title',) class ArtistSerializer2(serializers.ModelSerializer): name = serializers.CharField() tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Artist fields = ('id', 'name', 'slug', 'tracks') -
Wagtail with Disqus
Does Wagtail goes well with django-disqus? THIS post made me a think that there might be issues on the way. Anybody have any experiences with using/integrating both? -
Django: Uploading direct BASE64 image to S3 Bucket without persisting file locally
I have an internal API for my application. One of the endpoints allows to POST /user/profile_image. The idea is to be able to take a file via API and then put it on an AWS S3 bucket and obtain the URL for that direct file (I don't mind if it's public access). How to implement that endpoint? Should it take a BASE64 string? An HTTP file upload? what Django libraries out there should I be using to stream this file onto my S3 bucket and make it accessible publicly via a URL? I would appreciate any pointers. I'm using the latest versions of Django and DRF. -
Chatterbot Django Custom Corpus Path?
It seems one can use custom corpus json files by specify a path to the location. However, I'm confused by how that is done. The example provided by chatterbot isn't very clear. http://chatterbot.readthedocs.io/en/stable/training.html they do. "./data/my_corpus/" does the ./ mean root with a folder named data inside? If so what is root? My django app? And in the other line they directly refrence the .json file? They also seem to do .corpus.json? Is that the correct file name scheme? Do I need both lines? Its very confusing not a lot of clarity. Is there a clear example of how to do this? -
Django not found : / with a View on set on it for non www?
I'm running a Django app on Heroku using Dnsimple to point the domain to heroku. When I load http://example.com or https://example.com I get "Not Found The requested URL / was not found on this server." I get the following log in my logs window: 2017-06-04T02:20:51.503765+00:00 app[web.1]: Not Found: / 2017-06-04T02:20:51.503784+00:00 app[web.1]: WARNING:django.request:Not Found: / However I have the url supported and it works on example.com or www.example.com or https://www.example.com, or http://www.example.com : supported URL "url(r'^$', views.home, name='home')" The fact that I'm getting Logs in my server display makes me think it's not a config issue with dnsimple but I'm getting a log like the view isn't there on non www domains? -
Docker NGINX setup to run Django project is giving invalid port specification error
I am trying to setup Docker for my django project. I believe everything is setup to run docker in my machine. Currently, the docker version gives following output: Client version: 1.6.2 Client API version: 1.18 Go version (client): go1.2.1 Git commit (client): 7c8fca2 OS/Arch (client): linux/amd64 Server version: 17.05.0-ce Server API version: 1.29 Go version (server): go1.7.5 Git commit (server): 89658be OS/Arch (server): linux/amd64 I have setup my docker-compose.yml file as follows: version: '3' services: nginx: restart: always image: nginx:latest container_name: NGINX ports: - "8000:8000" volumes: - ./src:/src - ./config/nginx:/etc/nginx/conf.d - /static:/static depends_on: - web web: restart: always build: . container_name: DJANGO command: bash -c "python manage.py makemigrations && python manage.py migrate && gunicorn loop.wsgi -b 0.0.0.0:8000 --reload" depends_on: - db volumes: - ./src:/src - /static:/static expose: - "8000" db: restart: always image: postgres:latest container_name: PSQL docker-compose build successfully builds docker images and shows following message: Successfully built 6b13b02488dc Successfully tagged loopserver_web:latest nginx uses an image, skipping But, when I try to run docker-compose up following error occurs: Creating NGINX ... Creating NGINX ... error ERROR: for NGINX Cannot create container for service nginx: invalid port specification: "None" ERROR: for nginx Cannot create container for service nginx: invalid port specification: … -
Can't run django app with rest api on Heroku
I Just created an account on "Heroku.com" and followed the steps in the guide to create a new python project. I cloned the files locally and added a new app to the project and I created a rest api. I added 'rest_framework' to my "settings.py" and I was able to run the project locally. When I tried to push the changes back to heroku, it fails and i get this message: Counting objects: 6, done. Delta compression using up to 2 threads. Compressing objects: 100% (6/6), done. Writing objects: 100% (6/6), 632 bytes | 0 bytes/s, done. Total 6 (delta 5), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing requirements with pip remote: remote: Package django found! remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/core/management/__init__.py", line 353, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/core/management/__init__.py", line 327, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/__init__.py", line 18, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/apps/registry.py", line 85, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.6/site- packages/django/apps/config.py", line 90, … -
django-tables2 exclude not working SingleTableMixin
Using SingleTableMixin, nothing but the model is being passed to the rendered table. I commented out every line until it broke and **model = Stat is the only thing required for it to work. I saw similar questions but nothing particular to my case since the table is rendering, just without any of the class Meta info except model tables.py class StatTable(tables.Table): class Meta: model = Stat data = Stat.objects.all() exclude = ('id',) attrs = {'class': 'table table-hover table-condensed'} views.py class StatTableMixin(SingleTableMixin): table_class = StatTable context_table_name = 'stat_table' class AircraftList(ListView, StatTableMixin): model = Aircraft template_name = "aircraft/aircraft_list.html" def get_context_data(self, **kwargs): context = super(AircraftList, self).get_context_data(**kwargs) context['title'] = "D-> | Aircraft" context['stat_table'] = Stat.objects.all() return context -
django avoid duplicate model entries?
Below is my code snippet for a simple counting task using django models: if a product_id already exists, increment the counter for that id by 1. If the product_id does not exist yet, initiate a product instance with count=1. In runtime, the product_id's are gathered from request URLs of my web application. if Counter.objects.filter(product=product_id).exists(): temp = Counter.objects.filter(product=product_id)[0] temp.count += 1 temp.save() else: temp = Counter(product=product_id, count=1) temp.save() However, the resulting database has some duplicate entries. id,product_id,count 1446,CY8C,1 1450,6698,2 1445,0F99,39 1462,3666,1 1458,NYJJ,1 1459,NYJJ,1 1460,NYJJ,1 1457,NYJJ,2 1451,G99Q,3 1461,V727,1 1456,5LDM,3 1465,5NNQ,5 Did I miss anything in the code? In the django model template, I have already specified product_id = models.TextField(unique=True) Thanks for the help! -
how do I get only text field data from django modelform for email submission?
how do I get only the text field data from a django modelform for email submission? Ive tried a lot of variations in the view, cleaned_data.get() def clean(self): methods etc. Not sure why this is so hard. # models.py - service model class Service(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) service_type = models.ManyToManyField('ServiceType') description = models.TextField(blank=True) def __str__(self): return "Service Order for: {user}".format(user=self.user) class ServiceType(models.Model): label = models.CharField(max_length=200, unique=True) def __str__(self): return self.label # forms.py class NewServiceForm(forms.ModelForm): accept_tos = forms.BooleanField(required=True) class Meta: model = Service fields = '__all__' exclude = ('user', 'created_at',) # views.py @login_required def newservice(request): if request.method == 'POST': form = NewServiceForm(request.POST) if form.is_valid(): form.instance.user = request.user service = form.save() # SEND EMAIL - send copy of project/service modelform data to user and site owner name = request.user.first_name+request.user.last_name username = request.user.username subject = 'New Service Order' from_email = request.user.email service_data = form.cleaned_data message = ''' From: {} {} {} \n {} \n {} '''.format(name, from_email, username, subject, service_data) recipients = ['mytestemail@gmail.com', request.user.email] try: send_mail(subject, message, from_email, recipients) except BadHeaderError: return HttpResponse('Invalid header found.') # END EMAIL messages.warning(request, 'Success! Your service order has been submitted.') return redirect('projects') else: messages.error(request, 'Invalid submission, check and try again.') else: form = … -
Django: How to filter for keyword in multiple fields on a model?
I have Article model with title and body fields. I'm building a search functionality and need to filter for articles that have keywords either in title or body fields. I have two Articles. One has "candy" in the title and the other has "candy" in the body. So my result filter should have both articles. I'm trying below query but it's bringing me the first article only Article.objects.filter(title__icontains='candy').filter(body__icontains='candy') Thx -
Django Rest Framework: ModelSerializer and choosing fields per HTTP METHOD
Say I have a phone book with 3 fields and a model to represent it: Name Age Phone I'm writing an API to post new entries, get existing entries and modify existing entries. For the sake of this question, my constraints are: for POST I'd like to be able to write all three fields when creating a new record. for GET I'd like to return only the Age and Phone for PUT I'd like to allow only the phone field to be updated. Given the rigidness of the class meta and where I can define extra_kwargs with definitions for each field such as read_only and write_only -- Will I need three separate ModelSerializer classes? or can I somehow have some kind of condition in a single ModelSerializer in order to support my constraints. Thanks -
How can i compare two datetimes in Django
I can`t compare two datetime variable. One of it is DateTimeField in my models.py date_of_end_discount = models.DateTimeField() Second is datetime.now. This is sample of code of compare from datetime import datetime def is_discount(self): return parse(str(self.date_of_end_discount)) > datetime.now() But i have TypeError: can't compare offset-naive and offset-aware datetimes -
Synchronise Apache logout with django logout
I have a site with static elements like images. I wanted to protect them (so that you cannot access them directly using a hotlink). For this purpose I used the part "Authentication with mod_wsgi" from the Django documentation: Authentication with mod_wsgi I don't like that fact that the user has to log in twice (one time Django auth and then Apache auth when there is an image on the page) but it's not the main issue (if you know how to handle this it would also be nice) My main problem is that after I log out I still can access the protected image. I know that this is because the fact that Apache uses only Djangos check_password method but maybe there is a way to synchronise it? -
Is object.save() necessary after Django F() expression?
If I do something like: object.votes = F('votes') + 1 is it necessary to do object.save() afterwards? -
POST request to Django Rest API without models
I'm nuts in python and Django-rest-framework QUESTION: how I send username and password in POST request so that server can make a call to 3rd party website and returns a response which is coming from that website to frontend. I'm able to implemented a get request and able do fetch data from the 3rd party website by hardcoding data params and making a request to that 3rd party website. I'm trying it with Django Rest Framework # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpRequest, HttpResponse import urllib2, urllib, requests, re from django.shortcuts import render # Create your views here. def index(request): print(request.method) print(request) startAddress = '*********************' start_response = urllib2.urlopen(urllib2.Request(startAddress)) timestamp = re.findall(r'id="loginstamp" value="(\d+)"',start_response.read(), re.M|re.I)[0] if timestamp: post_data = { 'allowinsubframe': 'null', 'mobile': 'false', 'login': 'jsp', 'loginstamp':timestamp, 'j_username': '*********', 'j_password': '*********' } authUrl = '*****************' requesting_ism = requests.post(authUrl,post_data).text print(requesting_ism) csrftoken = re.findall(r'id="csrftokenholder" value="(\S+)"',requesting_ism, re.M|re.I)[0] uisessionid = re.findall(r'id="uisessionid" value="(\S+)"',requesting_ism, re.M|re.I)[0] print(csrftoken) else: print('else printed') return HttpResponse("<h1>chal kuch toh chala</h1>") -
Prev/Next Links in Django Rest Franeworks "Single View"
Just starting with DRF. I'm wondering if there is a way to include Prev/Next links within a Single DRF view like: GET /artworks/first-artwork/ { "next": "http://localhost:8000/artworks/second-artwork", "previous": null, "image": "http://localhost:8000/media/artworks/someimg.jpg", "title": "First Artwork", "slug": "first-artwork", } I went through the tutorials but I've still no Idea how I can get the above result. At the moment I'm using a ViewSet for my List and "Single" (Instance) view: views.py: class ArtworkViewSet(viewsets.ModelViewSet): queryset = ArtWork.objects.all().order_by('title') serializer_class = ArtworkSerializer lookup_field = 'slug' urls.py: urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include( 'rest_framework.urls', namespace='rest_framework')), ] serializers.py: class ArtworkSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ArtWork fields = ( 'url', 'image', 'title', 'slug', ) lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } Is it possible to reach my goal with ViewSets or do I have to use something different like normal Views. What would be the simplest way of doing it and where can I find resources? The documentation braught me to the Paginator but it seems that it's only used by List Views. kind regards -
Django: cannot migrate due to object reference in form
I am having trouble running the django migrations on a new database because of the get_or_create() function in a form. form.py class EmployeeForm(...): # Make sure that we have a directory before initializing the form default_upload_directory = Directory.objects.get_or_create(name='Employee', parent=None)[0] This is the important part of a custom form I wrote. It will link the Employee's uploaded files to a default directory. Everything works fine except for the migration. When I run it on a new database it will complain with django.db.utils.OperationalError: no such table: filemanager_directory. It also happens if I use a standard objects.get(..) to access the Directory object. I am not sure how to solve this. Obviously the table does not exist, yet. On an existing database with the tables already in place everything works fine. -
Django Rest Framework: How to do nested serialization
I have an application that has a Company, and this company can have 0 or multiple addresses. Companies are not the only 'models' that could have addresses. To achieve this, I use ContentTypes. models.py class Company(models.Model): ''' models a company in the system. ''' number = models.CharField(_('Number'), unique=True, max_length=20) name = models.CharField(_('Name'), max_length=100) active = models.BooleanField(_('Active'), default=True) class Address(Auditable): ''' models an address ''' actor_type = models.ForeignKey(ContentType) actor_id = models.PositiveIntegerField() actor_object = fields.GenericForeignKey('actor_type', 'actor_id') _type = models.CharField( _('Address Type'), max_length=10, choices=sorted(TYPES.items()) ) active = models.BooleanField(default=True) address1 = models.CharField(_('Address 1'), max_length=50) address2 = models.CharField( _('Address 2'), max_length=50, ... This way, I could also have a Profile model and I could link multiple addresses to a Profile. However, my problem comes when I tried to implement the Serializers. Serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ( '_type', 'address1', 'address2', 'address3', 'country', 'state', 'city' ) class CompanySerializer(serializers.ModelSerializer): addresses = AddressSerializer(required=False, many=True) class Meta: model = Company fields = ( 'number', 'name', 'addresses' ) This implementation gives me this error. It says that it cannot iterate through Address model (which makes sense), but I'm not sure how to make my addresses iterable. I would need to perform CRUD operations not only … -
Customising tags in Django to filter posts in Post model
Quick question - I'm not sure what would be the correct way to handle this. Essentially I wish to define a custom tag which handles some logic then returns all posts of model Post which has the is_featured field set to True. I have tried a number of avenues to get this working, but none have worked. My last coherant "guess" was the following: templatetags/blog_tags.py: @register.inclusion_tag('blog/post/featured_posts.html') def show_featured_posts(count=4): """Return 4 of the most recent posts (of model: 'Post') that has the variable is_featured set to True.""" if Post.is_featured: featured_posts = Post.published.order_by('-publish')[:count] return { 'featured_posts': featured_posts} models.py (useful bits): class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) POST_TYPES = ( ('news', 'News'), ('feature', 'Feature'), ('review', 'Review'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(UserProfile, related_name='blog_posts') body = models.TextField() lead_in = models.CharField(max_length=500, default='') #These next items shall contain our development information for game reviews - this is much like the lead_in: platform = models.CharField(max_length=1000, default='') publisher = models.CharField(max_length=1000, default='') developer = models.CharField(max_length=1000, default='') release = models.DateTimeField(default=timezone.now) is_featured = models.BooleanField(default=False) #Out blog layout dictates each featurette has up to three scrolling images associated to it: image_scroll_1 = models.ImageField(storage=site_media_upload_location, null=True, blank=True) image_scroll_2 … -
Django: Outlook email smtp timeout in production server
i'm trying to send a SMTP email from Django, using my credentials of Outlook. My code works in localhost, but when I upload my code to production server, it doesn't. If I use my Gmail credential, it also works in production, but it doesn't with Outlook. So, I think Outlook is configured in a different way, but I dont know. This is my view code: def send_my_custom_email(): connection = mail.get_connection( host = 'smtp-mail.outlook.com', port = 25, username = 'myemail@outlook.com', password = 'mypassword' , ) connection.open() email2send = mail.EmailMessage('hello', 'hello', 'myemail@outlook.com', to=['receiveremail'], connection=connection) email2send.send() connection.close() I know that my configuration setting are right because it can send emails from localhost. These are my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True I already try to check the Outlook settings, but I couldn't find anything about SMTP use. My exact questions are: Outlook need aditional settings in production? The problem is in my code or in Outlook settings? Why it works in localhost but it does not in production server? -
Django - backend logic vs database logic
I wonder if a good habit is to have some logic in MySQL database (triggers etc.) instead of logic in Django backend. I'm aware of fact that some functionalities may be done both in backend and in database but I would like to do it in accordance with good practices. I'm not sure I should do some things manually or maybe whole database should be generated by Django? What are the best rules to do it as well as possible? -
Django http sometimes responds with long string consisted of unicode characters
I am building an arduino project that requests status from raspberry pi server running django web application. The web app is simple, it stores status of one switch in database (True or False meaning On or Off). I have a view that returns simple string with the status in form "Status:1" or "Status:0". The problem is that sometimes the response from the server is in a form of long string consisted of unicode characters. The characters are unknown to me when I copy-paste them from Arduino IDE Serial Monitor they look like this: '⸮'. The arduino code repeatly loads this page and checks for status to update the HW in my project. The length of this string is completely random and sometimes even infinite. The occurence is also random so I cannot predict when it happens therefore why it happens. The problem it is causing me is that I am parsing the response from the server on my arduino and when this infinite string occurs the program on the board freezes because it is parsing it practicaly forever. That is simply unacceptable. The code that reads the response from server on arduino is: while(client.connected() || client.available()){ char c = client.read(); …