Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trouble with template rendering in Django on Heroku
I worked through a very good tutorial (Django Girls). Works perfectly on Django's local server. It was also working perfectly on Heroku, so long as the web pages were static. But once I used a template to fill in three simple items, it does not render them as it does on the local Django server. I have been through installing/using whitenoise, following the advice at Heroku's site, etc., etc. All that did was cause the admin console to look pretty again (it had been rendering like a web page with very low bandwidth - no actual graphic oomph, just text with underlines). So, the use of whitenoise seems to have worked there. But on my home-brew page, when I look at the HTML that gets sent to the browser from Heroku, it has all the various tags, etc., but none of the content. As I said this is od since it works fine on the local server. I have tried changing the {% include static %} tp {% include staticfiles %}, I have run 'collectstatics' successfully, I have inserted all the code that whitenoise and heroku recommend. Any ideas? -
Django Template For Loop - reverese last two iterations
I am using Django 1.10 and Python 3.5. I have been given some code that consists of a for loop that returns 3 iterations of value in alphabetical order. For example the for loop returns: Chronological, Combination, Functional. However I need the for loop to return: Chronological, Functional, Combination (the last two iterations/values are reversed). I am forced to keep the for loop. Is this at all possible with a for loop? I have tried combining {% if forloop.last %} with {% if forloop.first%} and also setting the value with {% if forloop.counter == 2 %}...set value to Functional...{% endif %} and {% if forloop.counter == 3 %}...set value to Combination...{% endif %} but I cannot get this to achieve what I want. Here is my code: {% for resume_format_image in resume_format_images %} <div class="col-md-4"> {% with "resumes/resume_format_description_"|add:resume_format_image.style.lower|add:".html" as template_name %} {% include template_name %} {% endwith %} </div> {% endfor %} -
shared hosting django fastCGI
Hello I have seemed to set up my a2 shared hosting server up correctly with fastCGI, however, when I try to run my website a 500 error appears. Why could this be happening? Also when I try to migrate my database the following error appears match = datetime_re.match(value) type error datetime expected string or buffer How would you fix this? Thank you! -
Append / Insert button from a HTML page from a domain to another one
I have a website and we are creating a plugin button that will be show on our partners website. Something like this green button, on the right of this page: The button is already created and it's in a single HTML page on my own domain. The problem is, how to insert it on the partner's website with less code possible? Like an include or an IFRAME? Since I can't make javascript requests between different domains, how could I achieve this? Thanks!! -
Django- How to store file path in postgres database to be called in iframe
I have an small web application contained in a folder inside my static file tree and I'd like to be able to link the the html file inside to display the app in an iframe. In my models.py I've tried both models.FileField() and models.FilePathField(), but I can't get the iframe to display the file. The models.FilepathField() just displays a drop down box in the admin with no options, and the models.FileField() just re-uploads a new copy of the file which conflicts. Currently in my models.py I have class OreDeposit(models.Model): model_link = models.CharField(max_length = 255) and in my template I have the this: <iframe src="{% static "{{ore_deposit.model_link}}" %}" width="100%" height="600" ></iframe> But this returns this inside the iframe: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/%7B%7Bore_deposit.model_link%7D%7D What I would like to do is be able to click on a file from inside the admin of the website and save the relative path in the database without uploading a new copy of the file itself and then use {{ object.model_link.url}} to display the file. -
Difference between direct download and content-disposition download?
I am a new Django user and please explain the pro's and con's of these 2 types of download options, method 1: <a href="/path/to/download/pleaseanswermyquestion.pdf">Download here</a method 2: as a Django view def download(request): data = open('/path/to/download/pleaseanswermyquestion.pdf', 'rb') bdata = data.read() response['content-type'] = "pdf" response['content-disposition'] = "attachment; filename=%s" %(bdata) return response PS: the above python code is wrong but I just want to know the difference between the above 2 concepts of downloading a file from server -
Loop through images and tile them using django template syntax
I am trying to tile images with the logic, if there are an even amount of images - tile them and then go on to the next row, if there is only one image - center it, if there are an odd number of images - tile the images but for the last one, center it. <table style="border-spacing: 0px; margin: 0 auto; width: 100%"> <tbody> <tr>{% for item in event.Items %}{% if forloop.counter|divisibleby:2 %} <td style="margin-top: 5px;"> <p style="text-align: center; letter-spacing:0px; font-family:Noto Sans, Helvetica; font-weight:700; font-size:16px; padding: 15px 0;">{{ item.Name }}</p> <a href="{{ item.ProductURL }}"><img src="{{ item.ImageURL }}" style="width: 250px;" /></a></td> </tr> <tr>{% endif %}{% endfor %} </tr> </tbody> I have also been trying to use {% if event.Items|length == 1 %}, {% elif forloop.last and forloop.counter|divisibleby:2 == False %} but have not been able to figure out exactly how to lay everything out. This example below is not tiled - figured using the html table would allow me to do this easier For Example: {% for item in event.Items %}{% if event.Items|length == 1 %} <div style="margin:0 auto; text-align: center; clear: both;"><br /> <p style="display: block;"><a href="{{ item.ProductURL }}"><img src="{{ item.ImageURL }}" style="width: 200px; margin: 0 auto; display: block;" … -
How to use django-rest-auth to protect endpoints?
I got the rest-auth urls to work. But when I try to protect my api endpoints, it doesn't check for authentication. Any thoughts about why this would be happening? This is essentially what the documentation says, and all the examples I've found fall just short of actually demonstrating requiring authentication on endpoints. views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Stock from .serializer import StockerSerializer from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated # Lists all stocks or creates a new one # stocks/ class StockList(APIView): authentication_classes = (SessionAuthentication, BasicAuthentication) permission_classes = (IsAuthenticated,) def get(self, request): stocks = Stock.objects.all() serializer = StockerSerializer(stocks, many=True) return Response(serializer.data) def post(self, request): if request.user.is_authenticated == True: return Response('<h1>Hahahhahaha</h1>') else: return Response('<h1>nope</h1>') settings.py """ Django settings for gettingstarted project, on Heroku. For more info, see: https://github.com/heroku/heroku-django-template For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ import os import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: change this before deploying to production! … -
Django-AllAuth verification email never sent
The site thinks its sending the email and I can see the user in the admin (without having verified the account via email) but I never received the email. Also, I can send email in the shell. I have tested that and it works. Does anyone have any idea what is going on? I am using Django 1.11 and Python 3. #AllAuth Settings ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 7 ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_EMAIL_VERIFICATION = "mandatory" #ACCOUNT_USER_MODEL_USERNAME_FIELD = "email" ACCOUNT_USERNAME_REQUIRED = False -
Django: How to create a multilingual website
I wanto create a multilingual website in Django and I tried using django-parler but when I want to add an object by the admin, the admin doesn't show the translatedfield Here is a part of my models: class Movie(TranslatableModel): translations = TranslatedFields( synopsis=RedactorField( verbose_name=u'Sinopsis', allow_file_upload=False, allow_image_upload=True, ), data_sheet=RedactorField( verbose_name=u'Sinopsis', allow_file_upload=True, allow_image_upload=True, ), ) name = models.CharField(verbose_name='nombre', max_length=250) And my parler settings: PARLER_DEFAULT_LANGUAGE = 'es' PARLER_LANGUAGES = { 1: ( {'code': 'es', }, {'code': 'en', }, ), 'default': { 'fallback': 'es', 'hide_untranslated': False, } } -
DJANGO_SETTINGS_MODULE not defined
I'm trying to start a project in Django, but I've come up against a wall right at the start. Whenever I run django-admin with no commands, I get this notice after the help message: Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). And whenever I try to run it or manage.py with a command such as runserver, I get: python manage.py runserver Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 62, in execute super(Command, self).execute(*args, **options) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 73, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/home/castro/Code/django_tests/tutorial/lib/python3.6/site-packages/django/conf/__init__.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I don't know how to … -
Reading first line from in-memory CSV file using io.TextIOWrapper
I can successfully upload and access a CSV file using a Django form and loop through the rows in the file. However, the first row contains the column headers and these are somehow skipped when the code begins to read the file. from io import TextIOWrapper if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): csvfile = TextIOWrapper(request.FILES['file'], encoding="utf-8") logger.info('Position: {}'.format(csvfile.tell())) # <-- This returns 0 for line in csvfile: logger.info('line: {}'.format(line)) # <-- The first iteration actually logs the second line in the CSV file. What would cause the first call to the file in the for loop to return the second line in the file? -
How to save the data that has same model but with different data in Django
I'm working on a mini project which uses Django 1.8. The aim is to build a small billing app. So, I've created two models, Bill and Product, as follows. #bill/models.py class Bill(models.Model): date_of_issue = models.DateField() name = models.CharField(max_length=50, default="N/A", null=True) address = models.CharField(max_length=150, default="N/A", null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return "{} {}".format(self.input_name, self.date_of_issue) class Product(models.Model): bill = models.ForeignKey(Bill, on_delete=models.CASCADE) description = models.CharField(max_length=100, default="N/A") quantity = models.IntegerField(default=0) total = models.IntegerField(default=0) By seeing the model, you can tell that my approach is to create Bill and Product tables and connect the Product to Bill via ForeignKey. Now, the thing is that a single bill will contain at least one product. If there are more than one product, how should I write my views in views.py. I'm a beginner in the Django development. If a Bill contains a single Product then I can write its view. But how can I store multiple Product which have different data and storing it in database. -
How do I create a webpage for my PayPal business account [on hold]
Ok I need to create a buy now button for my PayPal business account except I don't have a webpage to do so. How do I create a webpage for my PayPal business account and then add or create my buttons? -
Django send_mail SMTPSenderRefused 530 with gmail
I've been trying for some time to be able to receive emails with Django from a website I'm developing. Now, I haven't deployed it yet, and I am using the Django Development Server, and I don't know if this affects it. Here is my settings.py configuration: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWROD = 'my_password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER DEFAULT_TO_EMAIL = EMAIL_HOST_USER Then, through the root folder of the project I run python manage.py shell, and type the following: >>> import django >>> from django.conf import settings >>> from django.core.mail import send_mail >>> send_mail('test', 'test', settings.EMAIL_HOST_USER, [settings.EMAIL_HOST_USER], fail_silently=False) And what I receive back is the following error: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/__init__.py", line 62, in send_mail return mail.send() File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 111, in send_messages sent = self._send(message) File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/mail/backends/smtp.py", line 127, in _send self.connection.sendmail(from_email, recipients, message.as_bytes(linesep='\r\n')) File "/home/paulo/anaconda3/envs/MyDjangoEnv/lib/python3.6/smtplib.py", line 866, in sendmail raise SMTPSenderRefused(code, resp, from_addr) smtplib.SMTPSenderRefused: (530, b'5.5.1 Authentication Required. Learn more at\n5.5.1 https://support.google.com/mail/?p=WantAuthErrorv11sm8729581qkl.88 - gsmtp', 'my_email@gmail.com') I have enabled the option to allow less secure applications. I tried, when using 2-step verification, to input, … -
How does bash completion for django's manage.py work?
I'd like to use the django's bash completion script in my shell. However, I have a customized version of manage.py which seems to produce some garbage as well as useful suggestions. So I wonder how that script actually work, i.e. how should I call manage.py to see the suggestions for some argument? -
Django Rest Framework: How to get value of the ForeignKey
In Django Rest Framework, how can I get the value of the ForeignKey instead of 'id'? I want to get financial_year as full year i.e. 2012 or 2013 and not the the id of e.g. 1 and 2 in the output. How can I achieve that? The output I'm getting is following: [{"financial_year":1,"mainline_revenue":18743.0,"regional_revenue":2914.0},{"financial_year":2,"mainline_revenue":23876.0,"regional_revenue":3204.0}] But I want: [{"financial_year":2012,"mainline_revenue":18743.0,"regional_revenue":2914.0},{"financial_year":2013,"mainline_revenue":23876.0,"regional_revenue":3204.0}] Models.py: class FinancialData(models.Model): financial_year = models.ForeignKey(Year) mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2) regional_revenue = models.DecimalField(max_digits=7, decimal_places=2) class Year(models.Model): YEARS_CHOICE = ( (2012, 2012), (2013, 2013), (2014, 2014), (2015, 2015), (2016, 2016), ) year = models.IntegerField(choices=YEARS_CHOICE, blank=True, null=True) Serializers.py: class FinancialDataSerializer(serializers.ModelSerializer): class Meta: model = FinancialData fields = ( 'financial_year', 'mainline_revenue', 'regional_revenue',) -
Django - filtering over many to many fields
How can I filter over multiple many to many fields. for example I've: class Category(models.Model): products = models.ManyToManyField(Product) ... class Product(models.Model): shippers = models.ManyToManyField(Shipper) manufacturer = models.ForeignKey(Manufacturer) ... With products = Product.objects.filter(category=category) I will get query with list of products in category. How to get list of all possible shippers for all products in the category? The second question is how to get all instances of manufacturers from this query. Now extracting of manufacturers looks like manufacturer_ids = products.values_list('manufacturer').distinct() manufacturers = Manufacturer.objects.filter(id__in=manufacturer_ids) But i believe that should be better way Also I don't have any idea how to get list of all possible shippers from this query. -
Assigning model instance to foreign key in django not working
I have a model with Foreign keys as below: class UserAccessModel(models.Model): sys_id = models.AutoField(primary_key=True, blank=True) user = models.ForeignKey('UserModel', on_delete = models.CASCADE, null=True, blank=True) access_type = models.ForeignKey('AccessModel', on_delete = models.CASCADE, null=True, blank=True) Now I am trying to save an entry in this model as below: form = access_forms.UserAccessForm({"user":user,"access_type":access_type}) if form.is_valid(): form.save() where user is model class instance retrieved as below: user = UserModel.objects.get(sys_id=sys_id) but when I am trying to save the form, it throws an error : user : Select a valid choice. That choice is not one of the available choices. I am bit confused here. Sometimes assigning whole model instance to FK works and sometimes assigning column value (ex. user.sys_id) works. Someone please explain this as I think here assigning model instance should work. -
Multiple vs one big context_processor
I have multiple context processor and in each I have to request the user. Each of these look like this: def UploadForm(request): user = request.user Uplo = UploadForm(request.POST or None, initial={user}) return {'Uplo': Uplo} I saw that this is not efficient since im requesting the user multiple times, so I thought about writing one big context processor where I define all the Forms at once. def AllForms(request): user = request.user Uplo = UploadForm(request.POST or None, initial={user...}) SetForm = SetForm(request.POST or None, initial={user...}) ... return {'Uplo': Uplo,'SetForm': SetForm} Can anybody tell me if I gain here anything? What is the common standard for context processors? I could not find anything on SO. -
How to CreateView (generic) item in generic Album - problrm with url directions
I have problems with generic Views. I trying Create form to add foto to albums but when I testing my app by trying add some foto it redirect me to create Album (It suppose it schould create Foto). Why it hapening and and what is the solution? (maybe generic is not the best way to do such displays?) some clues? Thanks! Ps. i notice that it get right url but then goes to "views.DetailView.as_view(), name='detail' " not to right one "views.FotoCreate.as_view, name='foto-add' " -This from detail html: <a href="{% url 'albumbum:foto-add' album.pk %}" class="btn btn-default active" role="button"> <span class="fa fa-plus fa-1x" aria-hidden="true"></span>&nbsp;Dodaj element do albumu</a> urls: urlpatterns = [ # /albumbum/ url(r'^$', views.IndexView.as_view(), name='index'), # /albumbum/<albumbum.id>/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # /albumbum/add/ url(r'add/$', views.AlbumCreate.as_view(), name='add'), # /albumbum/albumbum/2/ url(r'albumbum/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='albumbum-update'), # /albumbum/albumbum/2/delete url(r'albumbum/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='albumbum-delete'), # /albumbum/2/add url(r'^(?P<pk>[0-9]+)/add/$', views.FotoCreate.as_view, name='foto-add'), -Models class Album(models.Model): autor = models.CharField(max_length=250) nazwa_albumu = models.CharField(max_length=500) temat = models.CharField(max_length=100) opis_albumu = models.CharField(max_length=700, default="abc") album_logo = models.CharField(max_length=1000) def get_absolute_url(self): return reverse('albumbum:detail', kwargs={'pk': self.pk}) def __str__(self): return self.nazwa_albumu + ' - ' + self.autor class Foto(models.Model): albumnr = models.ForeignKey(Album, on_delete=models.CASCADE) nazwa_foto = models.CharField(max_length=250, default='abc') obraz = models.CharField(max_length=1000, default='abc') def get_absolute_url(self): return reverse('albumbum:detail', kwargs={'pk': self.pk}) def __str__(self): return self.nazwa_foto And Views.py … -
error upstream prematurely closed nginx django gunicorn
In my project Django - gunicorn - nginx sudo nano /etc/nginx/sites-available/myproject server { listen 80; server_name ***IP***; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /path/to/env/app/static/; } location / { include proxy_params; proxy_pass http://unix:/path/to/env/app/project.sock; } } sudo nano /etc/systemd/system/gunicorn.service Description=gunicorn daemon After=network.target [Service] User=eavinti Group=www-data WorkingDirectory=/path/to/env/app/ ExecStart=/path/to/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/path/to/env/app/project.sock app.wsgi:application [Install] WantedBy=multi-user.target I'm getting this error sudo tail -F /var/log/nginx/error.log 2017/08/21 17:50:56 [error] 12463#12463: *15 upstream prematurely closed connection while reading response header from upstream, client: 186.4.200.54, server: ***IP***, request: "GET / HTTP/1.1", upstream: "http://unix:/path/to/env/app/project.sock:/", host: "***IP***" -
Custom endpoint with basic serializer?
In my model's viewset, I have created a custom endpoint and I'm trying to serialize some quick meta information to send out. Endpoint Declaration: @list_route(methods=['get'], url_path='meta') def get_meta_details(self, request): serializer = ThingMetaSerializer return Response(serializer.data) ThingMetaSerializer: class ThingMetaSerializer(serializers.Serializer): some_data = serializers.SerializerMethodField(method_name='ret_zero') def ret_zero(self): return 0 Every time I run the endpoint I get the following error: TypeError(repr(o) + " is not JSON serializable") Any idea how I can make this work? Edit: I made this work using the following code in the viewset: meta_data = { 'some_data': 0, } @list_route(methods=['get'], url_path='meta') def get_meta_details(self, request): # do some calculations return JsonResponse(self.meta_data) However this method does not auto generate into the Django RF Schema. If there is a better way of doing this I would love to know. -
TypeError: Cannot create a consistent MRO for bases Mixin, object
I am trying to add an explain() method to django QuerySet, but get the MRO error: File ".../mixin.py", line 10, in <module> QuerySet.__bases__ += (QuerySetExplainMixin,) TypeError: Cannot create a consistent method resolution order (MRO) for bases QuerySetExplainMixin, object the mixin and code I add it with: from django.db import connections from django.db.models.query import QuerySet class QuerySetExplainMixin: def explain(self): cursor = connections[self.db].cursor() query, params = self.query.sql_with_params() cursor.execute('explain %s' % query, params) return '\n'.join(r[0] for r in cursor.fetchall()) QuerySet.__bases__ += (QuerySetExplainMixin,) (credits of the mixin: https://stackoverflow.com/a/39168237/3385534 ) -
django-jwt reverse token search
I'm using django jwt http://getblimp.github.io/django-rest-framework-jwt/ and I want to use the token generated. Since they belong to a user, how I can search for the user by token and return user data.