Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django qrcode generation PIL image saving
I am trying to generate QR code based on model. I am hosting the app at Heroku and using AWS S3 as sotrage. Storage with S3 works totally fine with other model elements, just the model for QR code generation is giving trouble. I am using this link as reference: https://gilang.chandrasa.com/blog/generate-qr-code-in-django-model/ My model is: class BusinessQRCode(models.Model): business = models.ForeignKey(Business, null=True) location_name = models.CharField(max_length=255) qrcode = models.ImageField(upload_to='documents/{}'.format(time.strftime("%Y/%m/%d")), blank=True, null=True) def save(self): super(BusinessQRCode, self).save() self.generate_qrcode() def generate_qrcode(self): from activation.models import RandomFileName qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data('Some data') qr.make(fit=True) filename = 'qrcode-%s.png' % self.id img = qr.make_image() from django.conf import settings img.save(settings.MEDIA_ROOT + filename) # reopen = open(settings.MEDIA_ROOT + filename, "rb") # django_file = File(reopen) self.qrcode.save(filename,img, save=True) The above code gives me this error: TypeError TypeError: seek() takes exactly 2 arguments (3 given) I have tried using the commented code as well, that is opening the file and than trying to save it, but it doesnt work, it just keep looping. What I mean is this part of the code in the end: reopen = open(settings.MEDIA_ROOT + filename, "rb") django_file = File(reopen) self.qrcode.save(filename,django_file, save=True) What am I doing wrong? -
How to manage templates and static files for multiple apps in a Django project?
right now, I have 2 apps running in the same project. For the front-end, I am using Angular, so ideally, I would want to bring all these together in one place. However, the way Django's templates and static files are handled is that these are placed within the app's folders. What would be the right way to bring these together in one location? I don't need to have templates, and static folder inside each of my app's folders, since I am using a framework for my front end. For example: I have this in my urls.py url(r'^$', TemplateView.as_view(template_name='base.html')), This works if I put a base.html file in either of the following: myapp1/templates/ myapp2/templates/ So, what is the conventionally right way of doing things like this? -
Combining django ORM with custom classes with non-sqlite variables
I have a class which has some np.array instance variables, these don't have a directly compatible sqlite type. from django.db import models import numpy as np def Myclass(models.Model): id = model.CharField() def __init__(self): self.id = '' self.data = np.array() def some_function_for_data(data): pass # do some stuff on data While I can use the Myclass.save() functionality for id, how would I use it for data? Can I define that logic in Myclass, or some other serializer? -
Serving MEDIA FILES FROM NGINX
BREAKDOWN OF THE CURRENT PROBLEM: I had created a site with django, that was serving media files uploaded in the admin correctly(as I believed it was), because they appeared at the respective page once uploaded. However, after some new site fixes, these files stopped showing up, and the images and audio would not appear. To host my site I am using Digital Ocean. If I set the MEDIA_URL to '/media/' it keeps getting prepended to the STATIC URL, and the URL would look like "www.site.com/media/static/Images/etc', and then nothing works properly. In my models, for the ImageField() I have upload_to set as photo = models.ImageField(upload_to="photos/") MY urls.py: urlpatterns = [ url(r'^' + ADMIN + '/', admin.site.urls), url(r'^', include('a.urls')), url(r'^', include('b.urls')), url(r'^', include('c.urls')), #for static files ] #+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This creates a folder inside my media folder which is at the root directory where my django app is located. I read in the documentation, but I am still unclear on how to do things when it comes to serving my media files when it is uploaded. I know the right way to do it, is to serve them using a server like nginx. I would like to know why my media … -
Django / MySql and 4 Byte UTF-8 characters
I want to store 4-byte utf-8 characters in my django models with a mysql backend. I read that MySql does not support 4 byte utf-8 characters but changing the encoding to utf8mb4 would solve this issue. I changed the encoding and verified the settings: SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%'; character_set_client - utf8mb4 character_set_connection - utf8mb4 character_set_database - utf8mb4 character_set_filesystem - binary character_set_results - utf8mb4 character_set_server - latin1 character_set_system - utf8 When I try to send the "pile of poo" (as an example) I still get OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x92\\xA9' for column 'text' at row 1") I also tried to insert the pile of poo manually to an entry in my database. That worked and the database accepted the emoji. On my django view there is only "??" showing up. -
Upload Events from Database to FullCalendar
I want to render events that are saved in the database to the Calendar Template. All the events are passed as objects and can be retrieved like so: {% for object in objects %} var start = "{{ object.start }}"; var end = "{{ object.end }}"; var name = "{{ object.name }}"; {% endfor %} I can confirm this is working because I see it in Sources tab when I inspect the page. So I have a few events stored in the database and I want to render these events. So looking at the documentation, I thought about doing something like this: $('#calendar').fullCalendar({ eventSources: [ // your event source { events: [ // put the array in the `events` property {% for object in objects %} var start = "{{ object.start }}"; // Can't seem to identify this statement var end = "{{ object.end }}"; var name = "{{ object.name }}"; var event={id:1 , title: name, start: start, end:end}; //$('#calendar').fullCalendar( 'renderEvent', event, true); { title : name, start : start, end : end, } {% endfor %} ] } // any other event sources... ] }); But the events array returns empty shown in the Sources inspect tab. I have … -
How to run a python (django) app on my internet server?
Yesterday I finished the tutorial for Django framework. On this tutorial I've created simple application and now I'd like to move my app to remote internet server. I have such server , I'm connected to SSH by putty and when I write python, I see: Python 2.7.12 (default, Nov 19) But if I try to put this commend: python setup.py install I get: Traceback (most recent call last): File "setup.py", line 5, in <module> from setuptools import find_packages, setup ImportError: No module named setuptools and it's strange because after this: >>> import django >>> django.VERSION I see the version: (1, 10, 5, u'final', 0) And I copied a folder with my app by FTP So, can you tell me, step by step, how can I run my application? -
Error while executing python manage.py runserver
I am new to python. I created this file using following command: C:\Python35\Scripts\django-admin startproject mysite After that successfully created a file in directory.But when i run C:\Python35\Scripts\mysite\python manage.py migrate or C:\Python35\Scripts\mysite\python manage.py runserver, i am getting the following error python is not recognized as an internal or external command operable program or batch file how to solve this problem? -
Wrong order of running docker containers in convox/docker-compose
Here is the compose file that I am using. It consist one postgres db container and one redis container. On top of them I have a gunicorn-django-python web server(docker image:python-3.5). There is one nginx proxy server which is linked to web container. version: '2' services: nginx: build: ./nginx/ ports: - 80:80 volumes: - /usr/src/app/static links: - web web: build: ./web ports: - 8000:8000 volumes: - /usr/src/app/static env_file: .env environment: DEBUG: 'true' SECRET_KEY: 5(15ds+i2+%ik6z&!yer+ga9m=e%jcqiz_5wszg)r-z!2--b2d DB_NAME: postgres DB_USER: postgres DB_PASS: postgres DB_SERVICE: postgres DB_PORT: 5432 command: /usr/local/bin/gunicorn messanger.wsgi:application -w 2 -b :8000 links: - redis - postgres postgres: image: postgres ports: - 5432 volumes: - pgdata:/var/lib/postgresql/data/ redis: image: redis ports: - 6379 volumes: - redisdata:/data I am facing issue while starting docker containers via convox start -f docker-compose.yml Problem is , ideally first postgres/redis servers to be started, then the web server and then nginx server in the end according to their linking order. But actually web server is getting started first due to which it fails without db/cache. See error logs below: web │ running: docker run -i --rm --name python-app-web -e DB_NAME=postgres -e DB_USER=postgres -e DB_PASS=postgres -e DB_SERVICE=postgres -e DB_PORT=5432 -e DEBUG=true -e SECRET_KEY=5(15ds+i2+%ik6z&!yer+ga9m=e%jcqiz_5wszg)r-z!2--b2d --add-host redis: -e REDIS_SCHEME=tcp -e REDIS_HOST= … -
Django InMemoryUploadedFile with universal line brakes and utf8
In my django application users can upload their csv files to import data into django. It works fine for CLRF unicode files. But there are two issues: When the file is not encoded with utf8 I keep getting 'utf8' codec can't decode byte 0xdc in position 393: invalid continuation byte. I tried to resolve that by using the following code file = codecs.EncodedFile(request.FILES['import'],"utf-8") dialect = csv.Sniffer().sniff(file.read(2048)) file.open() # seek to 0 reader = csv.reader(file,dialect=dialect) When the file uses CR Linebreaks they are not recognized or I get: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?. But the InMemoryUploadedFile is already an opened file object. My issue is very similar to this one but the solution mentioned for point 1 didn't work for me (as you can see my code is very similar) and point 2 isn't answered at all: Proccessing a Django UploadedFile as UTF-8 with universal newlines -
How to Redirect to user profile in django? i am using Django registration Redux
I am working on an app where the user will be able to login to his profile. I am using Django-registration-redux. I am using the below code to inculde in my project. LOGIN_REDIRECT_URL = '/profile/view/(?P<pk>[0-9]+)/' I want to redirect the user to his profile after logging in. I know that is not the way you can actually call an url in settings file. any solution for the problem? -
Django Form not being displayed
I have been working on a personal project for a bit now and have been unable to resolve an issue I have been having with a particular form. I have written successful Django forms in the past and have modeled it after those but I am still unable to get it to display. My model looks like: name = models.CharField(max_length=100) director = models.CharField(max_length=50) genre = models.TextField() rating = models.IntegerField() mpaa_rating = models.CharField(max_length=5) # movie_file = models.FileField() movie_cover = models.CharField(max_length=100) cast_list = models.TextField() year = models.TextField() url = models.CharField(max_length=100, default='http://www.imdb.com/title/') My form like: class Meta: model = Movie fields = ['url', 'name', 'director', 'genre', 'rating', 'mpaa_rating', 'movie_cover', 'cast_list', 'year'] View: context = RequestContext(request) movie_form = MovieForm() if request.method == 'POST': movie_form = MovieForm(data=request.POST) if movie_form.is_valid(): url = urlrequest.urlopen(movie_form.url) movie = BeautifulSoup(url, 'html.parser') movie_form.set_name(movie.find(itemprop='name')) data = get_movie_data(url) movie_form.data['name'] = data[0] movie_form.data['director'] = data[4] movie_form.data['genre'] = data[7] movie_form.data['rating'] = data[3] movie_form.data['mpaa_rating'] = data[2] movie_form.data['year'] = data[1] movie_form.data['cast_list'] = data[5] movie_form.data['movie_cover'] = data[6] movie_form.save() print('movie added') return render_to_response('add_movie.html', {movie_form: 'movie_form'}, context) And finally Template: <form id="movie_form" method="post" action="{% url 'add_movie' %}"> {% csrf_token %} {{ movie_form.as_p }} <input type="submit" value="Save" /> </form> I have read several posts on stack overflow about how to fix … -
Django import_export: import a group of columns as a model and configuring column names
I have a .csv file with 30 "columns" and i want to import it using different models, something like: id,name,age,car,year 1,hendrix,27,Celta,2009 Now, i want to split the file content into 2 different models, something like:` class Person(models.Model): name = models.CharField(max_length=120) age = models.PositiveIntegerField() class Car(models.Model): car = models.CharField(max_length=120) year = models.PositiveIntegerField()` And then, importing them TOGHETHER, changing the name of the result columns (something like 'name' = 'Person's name'. How can i do that? Thanks in advance! -
Django related_name not found
I have this model: class Person(models.Model): something ... employers = models.ManyToManyField('self', blank=True, related_name='employees') When I do person.employees.all() I get this error: 'Person' object has no attribute 'employees'. Is the related name only created when there is an actual link in place. If yes, how can I check this? -
Add second sign up screen to social sign up allauth
I'm using the django allauth auth system and I use the social sign ups with the "next" parameter like this: <a data-provider="facebook" href="{% provider_login_url "facebook" method="oauth2" next=next %}"> where next is a dynamic variable. However i would like to inject a second screen to the process, asking for i.e. a phoner number or other info. I imagine I would need to override a method to redirect to the second screen and pass the next parameter to this view. Any idea which method to override? Regards Julian -
Django validate model forms
I try to validate my model forms. User chooses category, subcategory, category1, subcategory1 from form fields. I'd like to raise an error when subcategory and subcategory1 are equals. I tried with clean method: class Meta: model = Site fields = ('url', 'name', 'description', 'keywords', 'group', 'category', 'subcategory', 'category1', 'subcategory1') def clean(self): cleaned_data = super().clean() subcategory = cleaned_data['subcategory'] subcategory1 = cleaned_data['subcategory1'] if subcategory == subcategory1: raise forms.ValidationError('ERROR') This is my Site model: class Site(models.Model): category = models.ForeignKey('Category') subcategory = ChainedForeignKey( 'SubCategory', chained_field='category', chained_model_field='category', show_all=False, auto_choose=True) name = models.CharField(max_length=70) description = models.TextField() # importuje zmienione TextFields widgets.py keywords = MyTextField() date = models.DateTimeField(default=datetime.now, editable=False) url = models.URLField() is_active = models.BooleanField(default=False) category1 = models.ForeignKey('Category', related_name='category', blank=True, null=True, default=None) subcategory1 = ChainedForeignKey( 'SubCategory', chained_field='category1', chained_model_field='category', related_name='subcategory', show_all=False, auto_choose=True, blank=True, null=True, default=None) group = models.CharField(max_length=10, choices=(('podstawowy', 'podstawowy'), ('premium', 'premium')), default='podstawowy') def get_absolute_url(self): return reverse('site', args=[str(self.category.slug), str(self.subcategory.slug), str(self.id)]) def get_thumb(self): host = urlparse(self.url).hostname if host.startswith('www.'): host = host[4:] thumb = 'http://free4.pagepeeker.com/v2/thumbs.php?size=s&url=' + host return thumb class Meta: verbose_name_plural = "Strony" My method doesn't work. There is no error. Form validates correctly no matter what i set in subcategory == subcategory1 (i tried sucategory !- subcategory1 too). -
DJango contains does not work on JSONField
I have created model like this: class Customer(models.Model): name = models.CharField(max_length=200) data = JSONField() and data filed has this structure: Customer.objects.create(name='David', data={ 'key1': 'text1', 'key2': 'text2', }, }) The problem is when I want to query by contains it doesn't return any result. Customer.objects.filter(data__key1__contains='t') Generated sql query result does not serve correct sql for 'json like' structure. -
AttributeError: type object 'Httplib2Interceptor' has no attribute 'Browser'
I am introducing myself to testing python web applications with wsgi_intercept. I have an environment.py file that contains a merchanize http driver. I am trying to convert it to a httplib2 driver. ### Set up the Mechanize browser. I have removed this line: # from wsgi_intercept import mechanize_intercept And replaced it with this: import httplib2 from wsgi_intercept.interceptor import Httplib2Interceptor And removed this line: # browser = context.browser = mechanize_intercept.Browser() browser.set_handle_robots(False) And replaced it with this: browser = context.browser = Httplib2Interceptor.Browser() browser.set_handle_robots(False) I get the following error: AttributeError: type object 'Httplib2Interceptor' has no attribute 'Browser' I understand the error, however do not know how to go about fixing it? -
Python Django - Access Response Headers In View
I am working on a web application which works with entities that all have their unique IDs. I have a submit form for users to create these entities and this form is in several steps (i.e. view 1 redirects to view 2, etc... until the end of the submission process). The first view will create the ID of the entity after form submission and I then need to use the ID of the instance created in the other views. I do not want to pass this ID as a URL parameter to the other views as these will be POST and that means that users could easily manipulate these and create records in models for several IDs. I have managed to pass this ID to several views using the session parameters (request.session) but this is not ideal as this is permanent for the session. Current code below: def view1(request): if request.method == 'POST': form = xxx_creation_form(request.POST) if form.is_valid(): cleaned_form_data = form.cleaned_data xxx_entry = Model.objects.create( ... object creation ... ) request.session['xxx_id'] = xxx_entry.id return HttpResponseRedirect(reverse('form_2')) else: form = xxx_creation_form() return render(request, 'xxx_form.html', {'form': form}) def view2(request): xxx_id = request.session['property_id'] if xxx_id == 'SET_BACK_BLANK': return render(request, 'no_xxx_id.html') if request.method == 'POST': form … -
What is the best way to manage custom serializer in DRF
I have a custom serializer which container some other model serializer, data field, and some list field for manage many to many relation. Here is an example. class CustomSerializer(serializers.Serializer): a_model_serializer = AModelSerializer() b_model_serializer = serializers.ListField(child=CModelSerializer()) another_field = serializers.CharField() Based on this serializer I have to create some model object and some many to many relation through a third table. Now, what could be the best way to manage this situation. -
ImportError: No module named Project.settings
After reseting a database and adding some files into the project, I started recieving this error in gunicorn.log on DigitalOcean ubuntu droplet. Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 473, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 100, in init_process self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 115, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 33, in load return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 362, in import_app __import__(module) File "/home/django/project/project/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named Project.settings My project is called project, not Project. I've checked wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") application = get_wsgi_application() Which seems to be correct. Do you know why it tries to find settings in camel-cased name of project? Is there some config file where this path is? -
Django and frontend. How not to use Django urls and templates
Ordinary concept is to use urls.py and views.py. So you define in urls.py for main page smth like: urlpatterns = [ url(r'^', project.views.index), ] and this in views.py: def index(request): return render(request, 'index.html') But I saw code where there wasn't any url in urls.py for the main page and any others pages. I can realise, that further routing can be done with this modern frameworks and their routing modules. But I can't realise where is the entrypoint, which says: "Take this main Html page for this route". It's a very interesting approach, so I want to implement it too, but I don't even know how to find the suitable words to find any material in order to realise this. -
Can anyone suggest me some good tutorials for hosting python3/django sites on digitalocean?
I want to host a django 1.9/python3 site with MySQL database on digitalocean. The problem I am facing while hosting is that digitalocean is having default python2.7. When I tried to change the alias I am getting Baad Server Gateway error. -
Sort Columns in Django Templates
I know I should put up some code with what I've tried but I don't know where to start. In Django admin I can display data so that it can be sorted by the user using: class MyModelAdmin(admin.ModelAdmin): list_display = ['field1', 'field2'] ordering = ['field2','field1'] Within the admin site, users will be able to click the top of the column and reorder on that column. I want to replicate this functionality in an non-admin screen. How do I do that? -
Override template tag in wagtail cms?
I am using ModelAdmin to register a custom model with the Wagtail admin. I would like to customise the IndexView. The only thing I want to do is add a button to each row. I can see that the rows are added by the template tag - results_list, which leads me to the results_list.html in modeladmin/includes. As this is registered with the @register.inclusion_tag decorator, is it possible to override the template in my own app? The normal django methods of overriding templates dont seem to be working for me...