Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Import error when deploying django app to Heroku
I am trying to deploy the app that they have mentioned in the getting started section. However I am getting error ModuleNotFoundError: No module named 'six'. The whole build log is mentioned below: -----> Python app detected -----> Installing python-3.6.1 -----> Installing pip -----> Installing requirements with pip Collecting dj-database-url==0.4.1 (from -r /tmp/build_1900e0c2c9d2dd1135d0cd7b517175ae/requirements.txt (line 1)) Downloading dj-database-url-0.4.1.tar.gz Collecting Django==1.9.7 (from -r /tmp/build_1900e0c2c9d2dd1135d0cd7b517175ae/requirements.txt (line 2)) Downloading Django-1.9.7-py2.py3-none-any.whl (6.6MB) Collecting gunicorn==19.6.0 (from -r /tmp/build_1900e0c2c9d2dd1135d0cd7b517175ae/requirements.txt (line 3)) Downloading gunicorn-19.6.0-py2.py3-none-any.whl (114kB) Collecting psycopg2==2.6.2 (from -r /tmp/build_1900e0c2c9d2dd1135d0cd7b517175ae/requirements.txt (line 4)) Downloading psycopg2-2.6.2.tar.gz (376kB) Collecting whitenoise==2.0.6 (from -r /tmp/build_1900e0c2c9d2dd1135d0cd7b517175ae/requirements.txt (line 5)) Downloading whitenoise-2.0.6-py2.py3-none-any.whl Installing collected packages: dj-database-url, Django, gunicorn, psycopg2, whitenoise Running setup.py install for dj-database-url: started Running setup.py install for dj-database-url: finished with status 'error' Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-vkji1x5w/dj-database-url/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-e09119wj-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib copying dj_database_url.py -> build/lib running egg_info writing dj_database_url.egg-info/PKG-INFO writing dependency_links to dj_database_url.egg-info/dependency_links.txt writing top-level names to dj_database_url.egg-info/top_level.txt reading manifest file 'dj_database_url.egg-info/SOURCES.txt' writing manifest file 'dj_database_url.egg-info/SOURCES.txt' running install_lib copying build/lib/dj_database_url.py -> /app/.heroku/python/lib/python3.6/site-packages byte-compiling /app/.heroku/python/lib/python3.6/site-packages/dj_database_url.py to dj_database_url.cpython-36.pyc running install_egg_info Copying dj_database_url.egg-info to /app/.heroku/python/lib/python3.6/site-packages/dj_database_url-0.4.1-py3.6.egg-info running install_scripts Traceback (most recent call last): File "<string>", line … -
Django Polymorphic inline form
My Django-admin has a form that allows editing of articles. The articles may have Media objects. I use the django polymorphic class to allow Video, and Photo media. I can create or delete media objects fine using the inline class. But I also want to be able to select already created Media that is currently unassigned to any article. Ideally I want an inline form that lists all unassigned media objects and has a checkbox beside them so that I can add some to the currently being edited story. First, I don't know how to show unassigned media in my inline objects. Second how do I add a checkbox to their form to allow selecting or removing them. Thanks. -
custom exception handler for DRF response and Django response
I'd like to define a custom exception class and raise it. Django rest framework has a hook where I can define custom exception handler (http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling) Django also provides a way to do it via middleware. Question, is if I want to handle exceptions in drf views and regular django views, would it be sufficient to handle them in django middleware? Or do I need separate handler for DRF views? In other words, does DRF request/response goes thgrough django middleware as well or not? -
django rest-auth datefield format
I installed django rest-auth framework with a custom user model setup. When I register with a user from: http://localhost:8000/rest-auth/registration/ api end point html form, I get an error of: uye_emailuser.date_of_birth may not be NULL Here is my Model: class AbstractEmailUser(AbstractBaseUser, PermissionsMixin): """ Custom user class without the Django default 'username' field, using the email as unique login handle. """ email = models.EmailField(_('email address'), max_length=254, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_of_birth = models.DateField() is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin ' 'site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as ' 'active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [first_name, last_name, date_of_birth] objects = EmailUserManager() admin.py: class EmailUserAdmin(DefaultUserAdmin): fieldsets = ( (None, {'fields': ('email', 'password',)}), (_('Personal info'), {'fields': ('first_name', 'last_name')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'first_name', 'last_name', 'date_of_birth', 'password1', 'password2'), }), ) form = EmailUserChangeForm add_form = EmailUserCreationForm change_password_form = AdminPasswordChangeForm list_display = ('email', 'first_name', 'last_name', 'date_of_birth', 'is_staff') search_fields = ('first_name', 'last_name', 'email') ordering = ('email',) … -
i have a check with multiple inputs (multiple x and y)
I am unable to save MEDIA_CHOICES in the database I don't know why ! The market parameter is saved. But I have problem with sector parameter that has MEDIA_CHOICES as input, The user choose the inputs but after save it is empty in the database. I cant find where is the problem. Image here the user need to check sector than save the value,when i access to the saved page i find the sector field empty not saved class Parameters(models.Model): MARKET= ((1,'Nasdaq'),(2, 'Nyse'),(3,'Amex'),) MEDIA_CHOICES = (('Utilities', (('vinyl', 'Vinyl'),('cd', 'CD'),) ),('Basic Materials', (('vhs', 'VHS Tape'),('dvd', 'DVD'),)),) user = models.ForeignKey(User) title = models.CharField('title', max_length=100, default='', blank=True, help_text='Use an indicative name, related to the chosen parameters') type = models.CharField('forecast type', choices=FORECAST_TYPES, max_length=20, default="backtest") #input characteristics price_1_min = models.FloatField('1. Price, min', default=0.1, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) price_1_max = models.FloatField('1. Price, max', default=20000, validators=[MinValueValidator(0.1), MaxValueValidator(20000)]) stocks_num_2_min = models.IntegerField('2. Number of selected stock, min', default=3, validators=[MinValueValidator(0), MaxValueValidator(100)]) stocks_num_2_max = models.IntegerField('2. Number of selected stock, max', default=7, validators=[MinValueValidator(1),]) limit_3 = models.FloatField('3. Last price to upper straight, %', default=20, validators=[MinValueValidator(-200),]) learning_days_4_min = models.IntegerField('4. Number of Learning days, min', default=1, validators=[MinValueValidator(1),MaxValueValidator(30)]) learning_days_4_max = models.IntegerField('4. Number of Learning days, max', default=10, validators=[MinValueValidator(1),MaxValueValidator(30)]) evaluation_days_5 = models.IntegerField('5. Number of Evaluation days', default=10, validators=[MinValueValidator(1),MaxValueValidator(10)]) delay_days_6 … -
After changed latin1_swedish_ci to utf8_general_ci can't migrate db
Yesterday I deleted my db tables, cause I needed change latin1_swedish_ci to utf8_general_ci for have a polish words in my apps. After that i can't do full migrate my database, because I have problem like that: (venv) C:\netbast\fastandbeauty\project>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, comments, contenttypes, registration, sessions, social_django, user_content, user_profile Running migrations: Applying social_django.0005_auto_20160727_2333...Traceback (most recent call last): File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\db\backends\utils.py", line 65, in execute return self.cursor.execute(sql, params) File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\db\backends\mysql\base.py", line 101, in execute return self.cursor.execute(query, args) File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\cursors.py", line 374, in _do_query db.query(q) File "C:\netbast\fastandbeauty\venv\lib\site-packages\MySQLdb\connections.py", line 292, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1146, "Table 'fastandbeauty.social_auth_association' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\core\management\__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\core\management\base.py", line 330, in execute output = self.handle(*args, **options) File "C:\netbast\fastandbeauty\venv\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File … -
Django loop is returning multiple posts
I am trying to get django to display posts from a single catgory on that category's page, instead, it displays all the categories and the posts under each category in the template. Here are my models (I trimmed them down): class Category(models.Model): ... title = models.CharField(max_length=255, verbose_name="Title", null=True, blank=True) slug = models.SlugField(max_length=200, unique=True) class Petition(models.Model): ... category = models.ManyToManyField(Category, verbose_name="Category", related_name='petitions') ... This is what I have in my views: class CategoryMixin(object): def get_context_data(self, **kwargs): context = super(CategoryMixin, self).get_context_data(**kwargs) context['categories'] = Category.objects.all() return context class CategoryView(CategoryMixin, generic.ListView): model = Category categories = Category.objects.all() # this will get all categories, you can do some filtering if you need (e.g. excluding categories without posts in it) queryset = Category.objects.all() template_name = 'petition/category_list.html' class CategoryIndexView(generic.ListView): model = Category template_name = 'petition/category.html' context_object_name = 'category_list' def get_queryset(self): return Category.objects.prefetch_related('petitions').order_by('-created_on')[:10] class PetitionIndexView(generic.ListView): template_name = 'petition/home.html' context_object_name = 'petition_list' queryset = Petition.objects.order_by('-created_on') def get_queryset(self): queryset_list = Petition.objects.order_by('-created_on') #SEARCH QUERY LOGIC query = self.request.GET.get("q") if query: queryset_list = queryset_list.filter( Q(title__icontains = query) | Q(petition__icontains = query) | Q(created_by__first_name__icontains = query) | #icontains = only text fields. Use text field within foreign key field Q(created_by__last_name__icontains = query) ).distinct() paginator = Paginator(queryset_list, 10) # Show 10 posts per page … -
Display time stamp in django templates?
I am using edit profile case in my Django templates and I am not sure how to convert a timestamp into proper time? the value I am getting from API is "dob": 730166400000,. Now I was using this in templates:- value="{{ result_data_for_editing.dob |print_timestamp }}" but it shows invalid filter tag error.is there is any method I can convert a timestamp in Django templates only?I know it is possible in views but I want to convert it in Django templates. -
Update django objects after filtering from a list of integer values
Following is my model of app named 'curiously'. class ChangeActivityLogForEmb(models.Model): activities = models.ForeignKey(activities) read_status = models.IntegerField(default = 0) login = models.ForeignKey(logins) status = models.IntegerField(default = 0) selected_id = models.IntegerField(blank=True, null=True) I am doing something like this. return_json_dict = {} scene_ids = ChangeActivityLogForEmb.objects.filter(login__id=1,activities__id__in= [12,2],read_status=0).values_list('selected_id',flat=True) counter = 1 for scene in scene_ids: return_json_dict.update({"scn"+str(counter):scene}) ChangeActivityLogForEmb.objects.filter(selected_id__in=scene_ids).update(read_status=1) When I try to update values of objects. I am getting an error like (1093, "You can't specify target table 'curiously_Changeactivitylogforemb' for update in FROM clause") -
How to retrieve foreign key field in Django rest framework?
Given the model and serializer classes below, when I retrieve Track details, it'll only show the Track title but not the related Artist. How would I also show the Artist name when retrieving Track details? models.py class Artist (models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") title = models.CharField(max_length=100, verbose_name="Title") def __str__(self): return self.title serializers.py class ArtistSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=True) name = serializers.CharField() class Meta: model = Artist fields = ('id', 'name') class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' -
Queryset expression using List Comprehension [duplicate]
This question already has an answer here: django Building a queryset with Q objects 1 answer Again I have same problem with query set Following is the list for exclude some pattern in my query. list = ['AW', 'cons', 'AR', 'AA', 'S1'] I am using the list contents one by one from the list and then using in below query set objects_list = XeroLabourIndirect.objects.exclude( Q(job_num__istartswith='AW') | Q(job_num__istartswith='cons') | Q(job_num__istartswith='AR') | Q(job_num__istartswith='S1') | Q(job_num__istartswith='AA')) if obj else None Instead of using the list content one by one in query set, I want to use my list inside query set with list comprehension method and iterate inside the query and then I have to get the resultant queryset. For that what I have to do? I tried something but all ends in syntax error, or some other errors. Please give some solution for my problem -
Does Django sanitize request.FILES['file']?
Does Django sanitize the request.FILES['file'] parameter? Or do I have to check it myself for Path/Directory Traversal attacks? Thx -
Celery beat crontab send task twice 10 minute's interval
I set celery crontab like below Proj_root/proj/celery.py app.conf.update( CELERYBEAT_SCHEDULE={ 'do_every_1st_day_of_month': { 'task': 'foobar', 'schedule': crontab(0, 0, day_of_month='1'), 'args': () }, }) But finally it was executed twice, 2017/05/31 23:50:00 and 2017/06/01 00:00:00. I cannot find reason. according to crontab params, it shouldn't be done at 2017/05/31. why it's like this? and here's related log at that time. If other part of project is needed, I'll apply later [2017-05-31 23:50:00,002: INFO/Beat] Scheduler: Sending due task (foobar) [2017-05-31 23:50:00,004: DEBUG/Beat] foobar sent. id->8240fb96-994c-4f96-bf4d-4824f0e0c407 [2017-05-31 23:50:00,005: DEBUG/Beat] beat: Waking up in 5.00 minutes. [2017-05-31 23:50:00,005: INFO/MainProcess] Received task: foobar[8240fb96-994c-4f96-bf4d-4824f0e0c407] [2017-05-31 23:50:00,006: DEBUG/MainProcess] TaskPool: Apply <function _fast_trace_task at 0x80740b1e0> (args:('foobar', '8240fb96-994c-4f96-bf4d-4824f0e0c407', {'lang': 'py', 'task': 'foobar', 'id': '8240fb96-994c-4f96-bf4d-4824f0e0c407', 'eta': None, 'expires': None, 'group': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '8240fb96-994c-4f96-bf4d-4824f0e0c407', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen63835@neadrc-test01', 'reply_to': '257ab156-57fa-3806-bdf1-28d5501b0472', 'correlation_id': '8240fb96-994c-4f96-bf4d-4824f0e0c407', 'delivery_info': {'exchange': '', 'routing_key': 'celery', 'priority': 0, 'redelivered': None}}, b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]', 'application/json', 'utf-8') kwargs:{}) [2017-05-31 23:50:00,006: DEBUG/MainProcess] Task accepted: foobar[8240fb96-994c-4f96-bf4d-4824f0e0c407] pid:63838 [2017-05-31 23:50:00,789: INFO/PoolWorker-4] Task foobar[8240fb96-994c-4f96-bf4d-4824f0e0c407] succeeded in 0.7823948785662651s: None [2017-05-31 23:55:00,006: DEBUG/Beat] beat: Synchronizing schedule... [2017-05-31 23:55:00,007: DEBUG/Beat] beat: Waking up in 5.00 minutes. [2017-05-31 23:59:59,991: DEBUG/Beat] beat: Synchronizing schedule... [2017-06-01 00:00:00,001: INFO/Beat] … -
Django ChoiceField saves None value after editing?
I have a Model as follows, gender = ( ('Male', 'Male'), ('Female', 'Female'), ) class UserProfile(models.Model): profile_id = models.CharField(max_length=60, blank=True,default='',) gender = models.CharField(max_length=60, blank=True, default='', choices=gender,verbose_name="gender") I have a modelform as follows for that model, class UserProfileForm(forms.ModelForm): def __init__(self, *args, **kargs): super(UserProfileForm, self).__init__(*args, **kargs) class Meta: model = UserProfile fields = '__all__' And views for editing form, def userprofile_edit(request, pk): userprofile = UserProfile.objects.get(pk=pk) form = UserProfileForm(request.POST or None,instance=userprofile) if request.method == "POST": form = UserProfileForm(request.POST or None,instance=userprofile) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('userprofile') else: form = UserProfileForm(instance=userprofile) else: form = UserProfileForm(request.POST or None,instance=userprofile) return render(request,'userprofiles/user_edit.html', {'form':form,'userprofile': userprofile}) And Template for Edit userprofile form, <div class="col-md-3"> <div class="form-group"> <label>Gender <star>*</star></label> <select name="gender" required class="selectpicker" value="{{ userprofile.gender }}" data-title="{{ userprofile.gender }}" data-style="btn-default btn-block" data-menu-style="dropdown-blue"> {% for Male,Female in form.fields.gender.choices %} <option value="{{ Male }}"{% if form.fields.gender.value == Male %} selected{% endif %}>{{ Female }}</option> {% endfor %} </select> The Problem is only while editing the userprofile form,when I click the submit button for this form, it raises "This field is required". When I click the choicefield and select an option, it works. But if I didn't select an option it saves a None.I wanted to know how to pass values … -
Django testing - update view won't change db object field
my view's code looks like that: if self.request.POST.get('is_useful'): help_obj = get_object_or_404(Help, pk=self.kwargs['pk'], answer_to__author__username=self.request.POST.get('sender')) help_obj.useful = True print(help_obj) help_obj.save() print(help_obj) response = json.dumps({'message': 'marked as useful help!'}) I'm testing it using this: def test_logged_user_can_mark_help_as_useful(self): self.client.login(username='bunny', password='pass') response = self.client.post(reverse('questions:edit-help', kwargs={'pk': 1}), {'is_useful': True, 'sender': 'bunny'}) content = json.loads(response.content) print(self.help1) self.assertTrue('useful' in content['message']) self.assertTrue(self.help1.useful) The problem is that self.assertTrue(self.help1.useful) does not pass, regardless of help_obj.useful = True in the view. Each one of that prints show that help object has ID 1 and it's an only object made for testing. That first assertion passes. Any help would be appreciated. Thanks! -
Django: point url behind root of app?
I am going through Django's tutorials (Django tutorial part 3) and I am at the part where we are adding views and urls. In this demo app they add subviews for polls, e.g. /polls/34/ to get to the 34th poll. Quoting from the tutorial: When somebody requests a page from your website – say, “/polls/34/”, Django will load the mysite.urls Python module because it’s pointed to by the ROOT_URLCONF setting. It finds the variable named urlpatterns and traverses the regular expressions in order. After finding the match at '^polls/', it strips off the matching text ("polls/") and sends the remaining text – "34/" – to the ‘polls.urls’ URLconf for further processing. There it matches r'^(?P<question_id>[0-9]+)/$', resulting in a call to the detail() view like so: My question is as follows: suppose you have a view that is related to your app, but where the url - prepended by the app name - makes less sense than just the new view by itself. How could you make a view (which is part of the app) start at a new path name. This might be confusing so here is an example. Suppose you have an app (decks) for decks users make out … -
How do I get AWS credentials in the AWS ECS docker container?
First, I use the server environment sever: django + nginx + uwsgi cloud: docker + AWS ECS logging: AWS CloudWatch log service + watchtower third party app I use the watchtower third party app for the AWS CloudWatch log service. So I need to give AWS credential information to the docker container. When testing locally, docker run -v $ HOME / .aws: /root/.aws --rm -it -p 8080: 80 image_name will connect the local credentials to the volume. But I don't know how to apply it in AWS ECS. http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-config.html Write the .aws/ecs.confg file by following above article AWS_DEFAULT_REGION=ap-northeast-1 AWS_ACCESS_KEY_ID=AKIAIPVZLZJVDOY2NTIQ AWS_SECRET_ACCESS_KEY=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 I added command to the Dockerfile likes bello. COPY .aws/ecs.config /etc/ecs/ecs.config However, internal server error occurs when accessing ECS. Another way, I tried to assign an "IAM role" to the container when "Task define" Even if you create "CloudWatchLogsFullAccess IAM role", nothing appears on the "Task define" creation screen role drop down. If you have any other way, please help me. Thank you. Here is my logging setting. In local tests, logging works normally. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, … -
xampp wsgi.py cannot import ssl module
Installed xampp on ubuntu-16.04. XAMPP root installation location: /opt/lampp Python 2.7.12 Django 1.11 XAMPP 5.6.30 The wsgi.py settings: ```python import os import sys import site site.addsitedir('/opt/lapmpp/htdocs/dpcm/dpcm/lib/python2.7/site-packages') sys.path.insert(0, '/opt/lampp/htdocs/dpcm') sys.path.insert(1, '/opt/lampp/htdocs/dpcm/dpcm1') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dpcm1.settings") os.environ.setdefault("PYTHON_EGG_CACHE", "/opt/lampp/htdocs/dpcm/.python-eggs") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # if import ssl module, it will occur an error. import ssl ``` /opt/lampp/apache2/conf/httpd.conf content: Alias /bitnami/ "/opt/lampp/apache2/htdocs/" Alias /bitnami "/opt/lampp/apache2/htdocs" <Directory "/opt/lampp/apache2/htdocs"> Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all </Directory> WSGIScriptAlias /dpcm/ /opt/lampp/htdocs/dpcm/dpcm1/wsgi.py #WSGIDaemonProcess /dpcm/ python-path=/opt/lampp/htdocs/dpcm:/opt/lampp/htdocs/dpcm/dpcm/lib/python2.7/site-packages #WSGIProcessGroup /dpcm/ WSGIPythonPath /opt/lampp/htdocs/dpcm WSGIPythonHome /opt/lampp/htdocs/dpcm/dpcm/ <Directory /opt/lampp/htdocs/dpcm/dpcm1> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> Alias /static/ /opt/lampp/htdocs/dpcm/static/ <Directory /opt/lampp/htdocs/dpcm/static> Order allow,deny Allow from all </Directory> if import ssl module in inactive-mode, it can be imported successfully. But if add 'import ssl' in wsgi.py or other django project file, there will report an error message: [Thu Jun 01 10:54:13.272126 2017] [wsgi:error] [pid 5430] [client 10.0.2.15:41534] mod_wsgi (pid=5430): Target WSGI script '/opt/lampp/htdocs/dpcm/dpcm1/wsgi.py' cannot be loaded as Python module. [Thu Jun 01 10:54:13.272176 2017] [wsgi:error] [pid 5430] [client 10.0.2.15:41534] mod_wsgi (pid=5430): Exception occurred processing WSGI script '/opt/lampp/htdocs/dpcm/dpcm1/wsgi.py'. [Thu Jun 01 10:54:13.272207 2017] [wsgi:error] [pid 5430] [client 10.0.2.15:41534] Traceback (most recent call last): [Thu Jun 01 10:54:13.272230 2017] [wsgi:error] [pid … -
cron tab not working with virtual env django
I am using python django community ami from bitnami and i am not able to execute python script in cron via virtual env Directly executing script in terminal works e.g. /path/to/env/bin/python /path/to/script.py (works) crontab (non sudo) */opt/bitnami/python/bin/python /path/to/script.py (works) /path/to/env/bin/python /path/to/script.py >> /tmp/log.out 2>&1 (not working)* "Cannot locate wrapped file" -
error 'makeHalloRichTextEditable is not defined' with Django form in Wagtail 1.10.1
I'm running Wagtail 1.10.1 on Django 1.11.1 and Python 3.5.2. I have a Django form for people to submit pages to the website without being users. It was working until a month or so ago and broke some time after I upgraded from Wagtail 1.8. The error message on my dev machine (localhost) is Uncaught ReferenceError: makeHalloRichTextEditable is not defined at localhost/:136 The relevant part of the form HTML looks like <label for="id_body">Content of the item.</label> <textarea name="body" cols="40" id="id_body" rows="10"> </textarea><script>makeHalloRichTextEditable("id_body");</script> In the template that section looks like {{ form.body.label_tag }} {{ form.body }} {{ form.body.errors }} The relevant bit of the models.py file is class NewsPage(Page): body = RichTextField(blank=True) submitted_by = models.CharField(max_length=255) submitter_email = models.EmailField() I found https://github.com/wagtail/wagtail/pull/2673 which seems relevant, but I haven't figured out how to make sure the correct JavaScript files are imported, or what else might need fixing. What's the best way to figure out how to fix this? -
from django.utils.importlib import import_module ImportError: No module named importlib
I am new to Django. I got a Django rest project. When i run it, an error shows as from django.utils.importlib import import_module ImportError: No module named importlib I tried installing importlib with the command pip install importlib Then it shows Requirement already satisfied: importlib in ./lib/python2.7/site-packages So how coild i install importlib package? -
How to export database to CSV file from datatable view?
I am able to export the datatable to csv/pdf/excel format. But I am getting only few database fields which were rendered in html page. Instead I want give access to export all the database fields when I click on export to csv. Is it possible using DataTable export ? Does anybody tried it? Please do not down-vote this question if you don't know the answer. FYI: I did research in internet and posted this question. -
How to use multiple tables for authenticating users in django rest?
Hi I am starting a new project and i need to create separate tables for user(CustomUser model) and vendor(Vendor model) and authenticate user from CustomeUser model and vendor from Vendor model I know that by using AUTH_USER_MODEL i can change default User model but i need to use tow different tables for two different type of users and authenticate them If there any way to do this or have any suggestion please let me know -
django redirects different links to same page
from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return render(request, 'platoweb/index.html') def about(request): return render(request, 'platoweb/about.html') This is the views.py file. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index.html'), url(r'^$', views.about, name='about.html'), ] This is the app urls.py from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ url(r'^platoweb/index.html', include('platoweb.urls')), url(r'^platoweb/about.html', include('platoweb.urls')), url(r'^admin/', admin.site.urls), # . url(r'^posts/', include("posts.urls", namespace='posts')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) This is the global urls.py Essentially, I'm trying to hit two different urls, index.html and about.html (and more later). However, when I run it, both index.html and about.html redirect to index.html. I've tested both html files and they work just fine. Any ideas or thoughts? -
Django: adding multiple values to a model's field
I am new to Django. I am trying to create an app with news, and the companies mentioned in those news, and have created the following models: class Company(models.Model): company_name = models.CharField(max_length=100) company_country = models.CharField(max_length=50) def __str__(self): return self.orgn_name class News(models.Model): news_title = models.CharField(max_length=200) news_link = models.CharField(max_length=100) news_date = models.DateField() news_company = models.ManyToManyField(Company) def __str__(self): return self.news_title Now, a news might have mention of more than one company. How do I account for that, and enter the list of companies in the database entry? I am using the default Sqlite DB right now. E.g. a news can be "Facebook competes with Google in AI space" This news has two companies: Facebook and Google. 1) How do I design my models so that they take multiple values for Company? 2) How do I save those values via shell? 3) How do I query it, so that a query similar to SELECT COUNT (DISTINCT 'Company').... should output Facebook and Google separately, and not as "Facebook, Google"? I am stuck here and desperately need some guidance. TIA