Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2 Test: Created object cannot be gotten for tests
I've read about building programs starting with tests, so I thought I'd give it a shot. I've made my initial project and app and a model, but when I try to run a test, I get a "Does not exist" error. I've run the migrations, is there more I have to do before I can run a test? Here's my code: models.py from django.db import models class Name(models.Model): first_name = models.CharField( "First Name", max_length=100, ) middle_name = models.CharField( "Middle Name or Initial", max_length=100, default='', ) last_name = models.CharField( "Last Name", max_length=200, ) def __str__(self): return f'{self.last_name}, {self.first_name}' tests.py from django.test import TestCase from contacts.models import Name class TestNameModel(TestCase): @classmethod def setupTestData(cls): Name.objects.create(first_name='Banny', last_name='Banvil') def test_name_exists(self): name = Name.objects.get(id=1) print (name) And the error that I get: Creating test database for alias 'default'... System check identified no issues (0 silenced). E ====================================================================== ERROR: test_name_exists (contacts.tests.TestNameModel) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/CrazyCarl/Software/contact/contacts/tests.py", line 12, in test_name_exists name = Name.objects.get(id=1) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name contacts.models.DoesNotExist: Name matching query does not exist. ---------------------------------------------------------------------- Ran 1 test in 0.002s FAILED (errors=1) Destroying test database for alias 'default'... I tried making … -
Django migrations run_before and reset give same error
I have a project with a custom user model. Because of an unrelated screw up, I had to reset migrations. Since I already had set the custom user once, I didn't think about migrating it separately first again, so of course I got django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'. Reading this error literally, it seems like I ought to be able to adjust the sequence and be ok, rather than the more challenging steps laid out for when you try to change to a custom user mid project https://docs.djangoproject.com/en/2.0/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project. See https://docs.djangoproject.com/en/1.11/howto/writing-migrations/#controlling-the-order-of-migrations However, when I did run_before, I STILL got the same error. Here is that code: class Migration(migrations.Migration): initial = True run_before = [ ('admin', '0001_initial'), ] So I tried a reset: python manage.py migrate admin zero And I STILL get the same error! So then I tried: dependencies = [ ('auth', '0007_alter_validators_add_error_messages'), ('admin', '0001_initial'), ] And, you guessed it, same error! What am I doing wrong, and/or what are my options here? Thanks. -
how to forbidden user download pdf or other files at django
When I use the below code in my django views, it will show download icon at Chrome. Is there any method to forbidden user download my pdf for privacy restrictions. python def home(request): data = open("/path/mypdf.pdf", 'rb').read() return HttpResponse(image_data, content_type="application/pdf") Chrome sceamshoot -
Django REST Framework and Vue.js throwing IntegrityError on post
I have an API created by the Django REST framework that is feeding data to my Vue.js frontend. That's going all well and good until I try to post to the API. The error I get is: django.db.utils.IntegrityError: null value in column "ifflist_id" violates not-null constraint DETAIL: Failing row contains (100, do more stuff, f, null). Here is the model I'm trying to post to: class TodoItem(models.Model): text = models.CharField(max_length=200) # this is the text of the actual to-do ifflist = models.ForeignKey(IffList, on_delete=models.CASCADE, related_name='item') is_completed = models.BooleanField(default=False) Here's serializers.py: class TodoItemSerializer(serializers.ModelSerializer): class Meta: model = TodoItem fields = '__all__' depth = 1 Here's the API views.py: class TodoListCreateAPIView(ListCreateAPIView): queryset = TodoItem.objects.all() # this returns all the things, which is bad permission_classes = (IsAuthenticated, ) serializer_class = TodoItemSerializer lookup_field = 'id' class TodoRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = TodoItem.objects.all() # this returns all the things, which is bad permission_classes = (IsAuthenticated, ) serializer_class = TodoItemSerializer lookup_field = 'id' The relevant urls.py: path('api/', api_views.IffListCreateAPIView.as_view(), name='ifflist_rest_api'), path('api/todoitems/', api_views.TodoListCreateAPIView.as_view(), name='todoitem_rest_api'), path('api/user/', api_views.UserListCreateAPIView.as_view(), name='user_rest_api'), # api/:slug path('api/<int:id>/', api_views.IffListRetrieveUpdateDestroyAPIView.as_view(), name='ifflist_rest_api'), path('api/todoitems/<int:id>/', api_views.TodoRetrieveUpdateDestroyAPIView.as_view(), name='todoitem_rest_api'), And finally, the Vue.js method where the magic is happening: addTodo: function () { let new_todo_item = document.querySelector('#new_todo_item').value; this.newTodo = {'text': new_todo_item, 'ifflist_id': this.displayedIfflist.id}; console.log(this.newTodo.text); console.log(this.newTodo.ifflist_id); … -
Searching for users and displaying their profile details in search results Django
I am creating a blog site where users can search other users using their first_name, last_name which belong to the user model. and the search result will show first_name, last_name, username( from user model) profile_image, city, country from (user_profile model) Below is my models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=100) country = models.CharField(max_length=100) profile_image = models.ImageField(default='', blank=True, null=True) def __str__(self): return "Profile of {}".format(self.user.username) Below is my views.py class ProfileList(ListView): model = User template_name = 'accounts/profile_list.html' def get_queryset(self): queryset = super(ProfileList, self).get_queryset() query = self.request.GET.get('q') if query: queryset = queryset.filter( Q(user__username__iexact=query)| Q(user__first_name__iexact=query)| Q(user__last_name__iexact=query) ) return queryset Below are my Templates <div class="col-md-8"> # I know this is not correct {% for user in User.objects.all %} {{user.first_name}} {{user.last_name}} {{ user.profile_image.url }} {{user.username}} {{ user.profile.city }} {{ user.profile.country }} {% endfor %} </div> I am again just learning Django any help is greatly appreciated. I have been hitting error after error trying to resolve this -
"uncaught Syntax error: unexpected token {" when exporting JSON content to bootstrap table script
I am trying to convert data under pandas dataframe to json and then to table using pandas_bootstrap_table. The error in browser console is "uncaught Syntax error: unexpected token {" Here is my view function def productview(request): qs = npmargin.objects.filter(user=selected_user) df = convert_to_dataframe(qs, fields=['gross_profit_margin_2015',]) json = df.to_json(orient='records') context = { "data": "json" } return render (request, 'operating/chart2.html', context) Below is charts2.html {% load static %} <script src="{%static "js/bootstrap.min.js"%}"></script> <script src="{%static "js/jquery-slim.min.js"%}"></script> <script src="{%static "js/bootstrap-table.js"%}"></script> <script src="{%static "js/pandas_bootstrap_table.js"%}"></script> <table id='datatable'></table> The Json data from the above view function is sent to pandas_boostrap_table.js. The browser shows the unexpected token "{" error at the data:{{data|safe}} $(document).ready(function(){ $('#datatable').bootstrapTable({ striped: true, pagination: true, showColumns: true, showToggle: true, showExport: true, sortable: true, paginationVAlign: 'both', pageSize: 25, pageList: [10, 25, 50, 100, 'ALL'], data:{{data|safe}}, //"The browser console shows error here" }); }); -
Css static reference do not work on Django Template
I have a html template that is rendered through index view. It has a couple static css that are referenced: <html lang="pt-pt"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>AppGestao by Araujo</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' /> <meta name="viewport" content="width=device-width" /> <!--STYLE FILES START--> {% load staticfiles %} <!-- Bootstrap core CSS --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet" type="text/css"/> <!-- Animation library for notifications --> <link href="{% static 'css/animate.min.css' %}" rel="stylesheet" type="text/css"/> <!-- Light Bootstrap Table core CSS --> <link href="{% static 'css/light-bootstrap-dashboard.css?v=1.4.0' %}" rel="stylesheet" type="text/css"/> <!--STYLE FILES END--> </head> I have the files inside APP_NAME/static/css If I run this html alone without django rendering and manuel reference to static css works perfect. If I do it through {%static it don't. Despite this, when I see source code in chrome, they look exactly the same with same css links! -
Turbodbc returns ODBC error state 60 when run from apache2/mod_wsgi
I have a Django website that uses TURBODBC to execute some direct SQL calls on a legacy database. This works perfectly when using the built in django test server, but when I run it with Apache2 I get the error message: “ODBC error state: 60”. I feel like it has something to do with running it with mod_wsgi but I am not sure. I have had NO luck with Google. Not even sure what “state: 60” means. Internal Server Error: /inventory/in/ [Mon Apr 09 22:01:09.718077 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] Traceback (most recent call last): [Mon Apr 09 22:01:09.718147 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] File "/usr/local/lib/python3.5/dist-packages/turbodbc/exceptions.py", line 50, in wrapper [Mon Apr 09 22:01:09.718213 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] return f(*args, **kwds) [Mon Apr 09 22:01:09.718282 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] File "/usr/local/lib/python3.5/dist-packages/turbodbc/connect.py", line 44, in connect [Mon Apr 09 22:01:09.718347 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] turbodbc_options)) [Mon Apr 09 22:01:09.718410 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] turbodbc_intern.Error: ODBC error [Mon Apr 09 22:01:09.718493 2018] [wsgi:error] [pid 10074:tid 140709839501056] [client 10.20.51.169:55415] state: 60 Questions: What does "state 60" mean? What is causing this error? How do I correct the … -
Delete file from specific model field when uploading a new version when Model has several file.fields without deleting everything Django
my problem is regarding orphaned files and the fact that my model uses several file fields. I have a model for a user, which has a profile image field and a cv field. The user is able to update these fields which works fine but the files remain. Now I've looked at various solutions online, created my own etc but its not working quite properly. The problem with my solutions (see below) is that it deletes all media files associated with that instance at that time even though I've only changed one value. Additionally, each of the fields have their directory path. Its fine when I change both fields since both change and the previous files are deleted but often people only change one value so how do I fix this? I don't want to use django-cleanup for a variety of reasons. models.py def teacher_avatar_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'teachers/avatar/{0}/{1}'.format(instance.user.email.replace(" ", "_").lower(), filename) def teacher_cv_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'teachers/cv/{0}/{1}'.format(instance.user.email.replace(" ", "_").lower(), filename) #Teacher class ProfileTeacher(models.Model): created = models.DateTimeField(auto_now=False, auto_now_add=True, blank = False, null = False, verbose_name = 'Creation Date') user = models.OneToOneField(app_settings.USER_MODEL,blank=True, null=False) first_name = models.CharField(max_length = 400, null=True, … -
manage.py collectstatic does not upload to files S3
Problem: Whenever I run python manage.py collectstatic all my static files are placed into a local 'staticfiles' folder. I have set STATICFILES_STORAGE = myapp.aws.utils.StaticRootS3Boto3Storage however the files always go to 'myapp/staticfiles'. Settings.py: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_FILE_EXPIRE = 200 AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = True DEFAULT_FILE_STORAGE = 'myapp.aws.utils.MediaRootS3Boto3Storage' STATICFILES_STORAGE = 'myapp.aws.utils.StaticRootS3Boto3Storage' AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') S3DIRECT_REGION='us-east-1' AWS_S3_URL = '//s3.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = 'http://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = AWS_S3_URL + '/static/' STATICFILES_LOCATION = STATIC_URL MEDIAFILES_LOCATION = 'media' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_HEADERS = { 'Expires': 'Thu, 31 Dec 2099 20:00:00 GMT', 'CacheControl': 'max-age=94608000', } myapp / aws / utils.py: from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3Boto3Storage = lambda: S3Boto3Storage(location='static') MediaRootS3Boto3Storage = lambda: S3Boto3Storage(location='media') Project Structure: myproject/ |-- myapp/ | |-- aws/ | | |-- __init__.py | | |-- utils.py | |-- __init__.py | |-- settings.py | |-- urls.py | +-- wsgi.py +-- manage.py |-- static/ | |-- scss | |-- css | |-- js | |-- images |-- staticfiles/ | |-- **ALL STATIC FILES END UP HERE** Notes: Changing STATICFILES_STORAGE seems to have no effect on the output python manage.py collectstatic results in: You have requested to collect static files at the destination location as specified in … -
Django serializing associated objects
I've the following Location and User model. class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, max_length=255) mobile = PhoneNumberField(null=True) username = models.CharField(null=True, unique=True, max_length=255) full_name = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_mobile_verified = models.BooleanField(default=False) location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True) These are the respective Serializers. class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) id = serializers.IntegerField(read_only=True) class Meta: model = models.User fields = ( 'id', 'email', 'mobile', 'username', 'full_name', 'password', 'is_active', 'is_mobile_verified', ) class LocationSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = models.Location fields = ('id', 'country', 'city', 'longitude', 'latitude') Now I'm serializing and outputting data like this. return Response(UserSerializer(user).data, status=status.HTTP_200_OK) My question is how can I return user data with his location using the two serializers together? -
How to specify redirect URL for OAuth Facebook Login
me and my team are developing a Django Web App and facing a problem with the Facebook Login we use. It always gives us this error: We have found a solution here on stackoverflow and tried it to add the redirect url into the settings in our Facebook Developer App, like this: We unfortunately still got the same error, please help! -
serializing django models (for use in js files)?
-- DJANGO/PYTHON-- class Sounds(models.Model): sound = models.TextField(max_length=500, blank=True) syl = models.TextField(max_length=500, blank=True) tone = models.IntegerField(blank=True, default=0) def as_json(self): return dict( input_id=self.id, sound=self.sound, syl=self.syl, tone=self.tone) --JS-- function init() { -- create a list of all instances with tone = 1 -- } This is what my model looks like. In my js file, I want to be able to pull all created instances with a certain tone (or syllable, etc..) into a list so I can use them. I created the as_json function (above), but I'm not sure where to call this function. If I call in in the python file, then..how can I use it in the js file, and vice versa? -
Is there a way to iterate through a single django query object?
When developing a website i run over a question. I have a query object and i want to iterate through all its` properties like for i in object: print(i) Haven`t found anything on Web. Any ideas? -
Django selection option set value
How can i set the selection box value to the value the user has choosen. Since when the page updates when they change value, it goes back to 1. I would like to be able to set the value which i arleady sending from the views.py. But have no idea how i can achive it through the template. <form name="week" method="get" action="{% url 'site:calender_index' %}"> <select class="week_picker" name="select_week" id="select_week" data-style="btn-primary" onchange="this.form.submit()"> {% for value in 1|times:52 %} <option>{{ value }}</option> {% endfor %} </select> </form> -
Implementing autocomplete for python django project
Can you recommend simple packages for Autocomplete for Django/python Project. My requirements: Account name and Subsidiary are stored in a DB. I would like a input form on html side, where if a user types "abc.." I would like to see all options for account names starting with "abc.." in the pres-elected Subsidiary. Are there any packages that i should use or should i look at a implementation from scratch? Thanks -
Django migration to multiple databases
I am using two databases in my django project. To handle that I have a router files: class SecondDB: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): if model._meta.app_label == 'app_in_second_db': return 'second_db' else: return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'app_in_second_db': return 'app_in_second_db' else: return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'app_in_second_db' or \ obj2._meta.app_label == 'auditlog': return True else: return False def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'app_in_second_db': return db == 'second_db' else: return db == 'default' The problem is if I run $./manage.py migrate --database second_db All applications in the project are migrated to second database. I can migrate specific app ./manage.py migrate app_in_second_db 0001_initial --database second_db but wonder if there is some error in my router file and how to prevent accidental moving all the models to the second_db database. Thank you -
How do I get the posts in a topic in Django?
Okay I'm trying to get the posts in a topic in Django, but not sure how. I have tried many methods. forums/models.py: from django.db import models # Create your models here. class Attachment(models.Model): file = models.FileField() def __str__(self): return self.file class Category(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Topic(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=150) body = models.TextField() topic = models.ForeignKey('Topic', on_delete=models.CASCADE) def __str__(self): return self.title class Reply(models.Model): title = models.CharField(max_length=150) body = models.TextField() post = models.ForeignKey('Post', on_delete=models.CASCADE) def __str__(self): return self.title Thanks in advance, if you need any other details let me know. -
Django custom ChoiceField form with selected=selected
I have the following form: POSSIBLE_POSITIONS = ( ('1', 'Brazo'), ('2', 'Muñeca'), ('3', 'Pierna'), ('4', 'Pie'), ) class PositionForm(forms.Form): position = forms.ChoiceField(choices = POSSIBLE_POSITIONS, label="", initial=1, widget=forms.Select( attrs={ 'class': 'form-control' } )) Here is the model that uses that positions: class User(models.Model): id = models.CharField(max_length=10, primary_key=True) position = models.CharField(max_length=1, choices=POSSIBLE_POSITIONS, default=1) And this is the view: def modify(request): return render(request, 'interface/modify.html', {'user': User.objects.get(pk=id), 'device_list': Device.objects.all(), 'form': PositionForm()}) I would like to know, how to select the default Position based on the current user.position. Like what I do here: <select name="device_id" class="form-control"> {% for device in device_list %} {% if device.id == user.device.id %} <option selected="selected">{{ device.id }}</option> {% else %} <option>{{ device.id }}</option> {% endif %} {% endfor %} {% if user.device.id == None %} <option selected="selected"> Sin dispositivo </option> {% else %} <option> Sin dispositivo </option> {% endif %} </select> But I don't know how to do it here: <div class="form-group"> <label>Posición actual dispositivo</label> {{ form }} </div> -
Change the widget for django admin's foreign key inline to a pop-up like the many-to-many's
I have a few models in my django project: CoursePacks, Courses and Chapters. Courses have a many-to-many relationship to the CoursePacks, which in the admin, after some inline editing, displays this widget: (This is a COURSE-COURSEPACK relationship) Which allows me to select, edit and create another course which will be automatically added to the course pack. The chapter ("capítulo") and the course models, however, are connected through a foreign key relationship, and the widget displayed on the admin is the following: (This is A CHAPTER-COURSE relationship) Which I have edited so that less fields are shown, because if I didn't all the fields and the entire textarea content would be displayed. When I click on the add or edit button to the side of the course instance on the course pack admin window, a window pops up which allows me to edit or create another course. I would like to be able to have a similar mechanism but for creating chapters through the course admin window. Will I have to edit the admin's markup or is there a widget editing functionality that does what I need? If not, where could I begin to do so? -
Django update model without UpdateView
I have a scenario where in my users profile they have an associated organisation. I need to be able to allow the users to select and set this organisation (user_organization), however I would like to do it without allowing them to just see a list of all the organisations within the application. My work around for this was to issue each organisation with a unique code (org_code) and allow users to enter that code into a form and have the related organisation applied to their profile. I can easily understand the suedocode logic behind this, however I am unsure how to implement it within my views and forms. If anyone can advise me the best way to do this or point me in the correct direction to learn how? It would be appreciated. See my models below for clarification on how things fit together. Profile: class Profile(models.Model): Super_Admin = "Super_Admin" Admin = "Admin" Manager = "Manager" Developer = "Developer" ROLE_CHOICES = ( (Super_Admin, 'Super_Admin'), (Admin, 'Admin'), (Manager, 'Manager'), (Developer, 'Developer'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) user_group = models.OneToOneField(Group, on_delete=models.CASCADE, blank=True, null=True) user_organization = models.OneToOneField(Organization, on_delete=models.CASCADE, blank=True, null=True) role = models.CharField(choices=ROLE_CHOICES, default="Developer", max_length=12) activation_key = models.CharField(max_length=120, blank=True, null=True) activated = models.BooleanField(default=False) … -
Flask: Message is not getting emitted by the socket
Here is my python code, the socket is supposed to emit two messages.One is 'started' and the other is the text generated by the Keras model. The keras model works completely fine in isolation. The message to be emitted doesn't get displayed in the terminal or the web interface. The python and the HTML code is given below. from flask import Flask, render_template, flash, request import numpy as np from flask_socketio import SocketIO, emit # App config. # DEBUG = True app = Flask(__name__) # app.config.from_object(__name__) app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a' socketio = SocketIO(app) @socketio.on('generate',namespace='/') def generate(ret): print(ret) emit('myevent','started') from keras.models import load_model model = load_model('model.h5') chars = ['w', 'n', 'q', 'g', 'm', 'v', 'o', 'r', 'k', 's', 'p', 'x', 'h', 't', 'z', 'ï', 'í', 'a', 'é', 'º', 'l', ' ', 'y', 'd', 't', 'i', 'j', 'r', 'c', 'ı', 'u', 'b', 'è', 'e', 'f', 'ĺ'] seq_length = 140 ix_to_char = {ix:char for ix, char in enumerate(chars)} char_to_ix = {char:ix for ix, char in enumerate(chars)} VOCAB_SIZE = len(chars) ret = list(ret.lower()) ret = [i for i in ret if i.isalpha() == True] ret = ret[:140] while len(ret)<140: ret = [" "] + ret X_sequence = ret y_char = [] X_sequence_ix = [char_to_ix[value] for … -
ASCII codec error Can't upload files django apache and redhat
When I tried to upload a file, my page shows this: 'ascii' codec can't encode character u'\xc1' in position 51: ordinal not in range(128) os.stat(path) u'/opt/djangoproject/ConvocatoriaESCA/media_cdn/Luis \xc1ngel Garc\xeda Ramos/Comprobante_Ingl\xe9s_Luis_\xc1ngel_Garc\xeda_Ramos.pdf' My path to upload Files in models.py have: def upload_location_comprobante_ingles(instance, filename): filename = u"Comprobante_Inglés %s %s.pdf" % (instance.nombre, instance.apellidos) return u"%s %s/%s" % (instance.nombre, instance.apellidos, filename) and nombre and apellidos are UTF-8 strings -
Cant find django module . import error
I have installed Django and it is already in the package. But when i run python manage.py runserver.I am getting this error Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
django/js submiting form and getting response without refreshing page
I was making this simple bmr calculator app the problem is when i submit i dont want to go to any other page i want to show the results in the same page instead of having to go to another page. views.py def bmrvalue(age ,height ,weight , gender ): if gender == 'm': BMR = (10 * weight ) + (6.25 * height ) - (5 * age ) + 5 else: BMR = (10 * weight ) + (6.25 * height ) - (5 * age ) - 161 return BMR def MyBmr(request): if request.method == "POST": form = BmrForm(request.POST) if form.is_valid(): age = form.cleaned_data['age'] height = form.cleaned_data['height'] weight = form.cleaned_data['weight'] gender = form.cleaned_data['gender'] mybmr = bmrvalue(age,height,weight,gender) return render (request , 'resultes.html', {'bmr':mybmr }) else: form = BmrForm() return render (request , 'home.html' , {'form': form}) any idea how can achieve that ?