Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django version upgrade after Python(3.7) upgrade
After python version upgrade to 3.7, I cannot upgrade Django(to v2.0). Django is still tied with the older version of Python(2.7) When I tried, $ pip install --upgrade django I get the following message: Could not fetch URL https://pypi.python.org/simple/django/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Requirement already up-to-date: django in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages Could not fetch URL https://pypi.python.org/simple/pytz/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:661) - skipping Requirement already up-to-date: pytz in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pytz-2017.2-py2.7.egg (from django) Do you have any suggestions for this? Thank you. -
ModuleNotFoundError: No module named 'widget_tweaks'
I'm writing project using docker and django (2.1). I've installed module 'django-widget-tweaks' inside a container and added 'widget_tweaks' to INSTALLED_APPS. When I start project using docker-compose up everything works well, but when I want to run something like docker-compose run <container name> python manage.py test in another terminal an error occurs. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'widget_tweaks' But when I directly run the same command python manage.py test inside a docker container, it works. widget-tweaks has been installed both on container and on my machine. Could you advice something to solve the problem? Thanks in advance! -
Column Already Exist Error on Django Rest Framework on Heroku Migration
I have updated my model, but I couldn't do the migrations, the problem is: I am getting an error like: column "blah blah" of relation "blah blah blah" already exists The mentioned column should exist in DB, but it shouldn't exist on migration file because I did not do any addition or modification about that model field and it was already successfully created in one of the previous migrations, even used frequently without any error. When I do the migration with --fake, this time it doesn't create the really unexisting field of migration file which is defined with that model update. Deployed on Heroku, it may be caused by rollbacks of code layer, since after rollbacks code gets to older versions but DB stays same. What is the best way without losing any data from production DB? Following is a screenshot of the bash; timezone, endtime and start time fields already exist on model and DB before this migration, created on one of the previous successful migrations Click here to screenshot of Heroku Bash when I try to run migrations Thanks -
How can I integrate a chatbot on an existing Python and Django-based e-commerce?
I'm new to django and I'm building E-commerce Site with AI Bot backend danjgo. I have knowledge of Machine Learning. I don't want to use API, create using python library. -
Django - save dynamically added forms to DB
I have the following dynamically added forms: The both belong to one forms.modelForm ~ ComponentsForm(), and they were dynamically added on the screen by clicking + button on the screen using jQuery. I want to save these objects to DB by overriding my post() method in CBV. With my current set of codes, clicking submit button prints the following queryDict: <QueryDict: {'csrfmiddlewaretoken': [# foo_token], 'item_description': ['aaaaaaaaa', 'bbbbbbbbb'], 'num_of_jts': ['aaaaaaaaaaa', 'bbbbbbbbb'], 'length': ['aaaaaaaaaaaa', 'bbbbbbbbbb'], 'cum_length': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbb'], 'outer_d': ['aaaaaaaaaaaaa', 'bbbbbbbbbbbbbbb'], 'inner_d': ['', ''], 'drift_d': ['', ''], 'od_cplg': ['', ''], 'top_thread': ['', ''], 'air_wght': ['', ''], 'make': ['', ''], 'sn': ['', ''], 'bha_component': ['Submit']}> As you can see, each field list has two items, because there are two dynamically added form instances on the screen. Upon clicking submit button, I want to create new objects if it doesn't already exists in DB, or save changes to DB if it already exists. How can I achieve this? Someone told me to use formsetFactory, but I don't think that's what I want, as these are dynamically added elements, and, it formset won't automatically create new objects in DB for each dynamically added elements. -
How to get the form choice field values?
Form._bound_fields_cache['limit'].field.choices[var][1] I want to get the [][1] this value from each choice field how to get it. I tried as above where choice is need to be iterated but i am not getting it. and need to append some string to it. Thank you! -
Django Forms: Cannot show Validation Error
I have a Django Form where I allow the user to submit a value only if his password matches a predefined password set by me : Pass_matcher Validation works fine, such that if passwords match, value is entered and stored and if not, nothing happens. However I want that if passwords do not match, I show a simple custom warning message. I looked at other SO questions such as here and here, but I can't seem to get it right. Note: If the user enters the correct password I do not want to redirect to another page. forms.py from django import forms class TactForm(forms.Form): password = forms.CharField(widget=forms.PasswordInput( attrs = { 'class' : 'form-control mb-2 mr-sm-2 mb-sm-0', 'placeholder' : 'Enter Password:', 'id' : 'inlineFormInput', 'required' : 'true' } ), required = True, label='Tact Password', max_length=100) tacttime = forms.CharField(widget=forms.TextInput( attrs = { 'class': 'form-control mb-2 mr-sm-2 mb-sm-0', 'placeholder': 'Enter Tact Time:', 'id' : 'inlineFormInput2' } ),label='Tact Time', max_length=100) def clean(self): cleaned_data = super(TactForm,self).clean() password = cleaned_data.get('password') current_tact = cleaned_data.get('tacttime') if password != 'Pass_matcher': print('incorrect') #this prints to console if incorrect raise forms.ValidationError('Incorrect Password') # this does not work else: print('correct') #this prints to console if correct return cleaned_data views.py def details(request): form β¦ -
Model population using django and python
I am new to Django and planning to design a wizard that will ask the user to populate few values . lets say i have two models Model 1 : col1 , col 2 Model 2 : col1(FK), col2 I display model 1 create view and user enters some values, which then navigates to model 2. In model 2 i get a drop down for col 1 as it is a foreign key. Can i auto populate this value ? One more question, if anyone can get me a lead. I need a screen that has a plus button to populate multiple rows to the model. What i am really looking for is , if the user wants to add additional details he just have to click a button and new row appears , Do i have to do this using java script ? Also i was using a progress bar using bootstrap that shows the remaining screens. -
How hide/show a field upon selection of a radio button in django admin?
models.py from django.db import models from django.contrib.auth.models import User STATUS_CHOICES = ((1, 'Accepted'),(0, 'Rejected'),) class Leave(models.Model): ---- ---- ---- ---- status = models.IntegerField(choices=STATUS_CHOICES, default = 0) reason_reject = models.CharField(('reason for rejection'),max_length=50, blank=True) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Leave @admin.register(Leave) class LeaveAdmin(admin.ModelAdmin): ------ ------ ----- def get_readonly_fields(self, request, obj=None): # the logged in user can be accessed through the request object if obj and request.user.is_staff: readonly_fields = [f.name for f in self.opts.fields] readonly_fields.remove('status') readonly_fields.remove('reason_reject') return readonly_fields def get_fields(self, request, obj=None): fields = [f.name for f in self.opts.fields] if obj.status == 1: fields.remove('reason_reject') return fields class Media: js = ('/static/admin/js/admin.js') radio_fields = {"status": admin.HORIZONTAL} I have this def get_readonly_fields function so that the admin could edit only those fields (status and reason_reject) and this def get_fields(self, request, obj=None) function so that upon selecting status (accepted/rejected), the next field reason_reject should appear. This worked only after selecting the status and saving the form. I've given status as radio_fields rather than select boxes since only one of them should be selected. I've tried even by using Jquery as well. Please correct me. admin.js django.jQuery('#id_status').change(function(){ if(django.jQuery('#id_status:selected').text() == 'Accepted') { django.jQuery(".form-row.field-reason_reject").hide(); } else { django.jquery(".form-row.field-reason_reject").show(); } } ); -
Django - Static images do not load, throw 404 error in console
I've been trying to solve this error for a very long time. I have a lot of static images that I am trying to open through my website. However, none of the static images will load, and when I look in the console, I see the error Failed to load resource: the server responded with a status of 404 (Not Found) Does anyone know why this is happening? I have ran collectstatic multiple times, restarted the server, done everything. What's weirder is, the code works great on my own server. When I run it on my digital ocean droplet, none of the images load. urls.py from django.contrib import admin from django.urls import path import posts.views import sitepages.views import hackathons.views import projects.views import skills.views from django.conf.urls.static import static from django.conf import settings from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), #path('blog/', posts.views.blog, name = "blog"), #path('posts/<int:post_id>/', posts.views.post_details, name="post_details"), path('about/', sitepages.views.about,name="about"), path('awards/',sitepages.views.awards,name="awards"), path('skills/',skills.views.skills,name="skills"), path('skills/<int:skill_id>/', skills.views.skill_details,name="skill_details"), path('projects/',projects.views.project,name="projects"), path('hackathons/',hackathons.views.hackathons,name="hackathons"), path('',sitepages.views.home,name="home"), #path('hobbies/',sitepages.views.hobbies,name="hobbies"), path('internships/',sitepages.views.internships,name="internships"), path('project_details/<int:project_id>/', projects.views.project_details,name="project_details"), path('hackathon_details/<int:hackathon_id>/', hackathons.views.hackathon_details, name="hackathon_details") ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Static section of settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = ( STATIC_ROOT ) MEDIA_URL = '/media/' MEDIA_ROOT = '/home/pranav/pranavblog/media' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] Please let me know if β¦ -
Django: Paginator error: object of type 'User' has no len()
I'm learning to use a paginator as my list are getting really long! I'm having trouble implementing it as I am getting an error. I notice that if I remove paginate_by = 10 then the error goes away, but I'm pretty sure this is necessary to paginate. Why is the get_queryset conflicting with the paginator. class NotificationsListView(ListView): template_name = "notices/list.html" paginate_by = 10 def get_context_data(self, *args, **kwargs): context = super(NotificationsListView, self).get_context_data(*args, **kwargs) qs = self.get_queryset().notifications.all() paginator = Paginator(qs , self.paginate_by) page = self.request.GET.get('page') try: notification_pages = paginator.page(page) except PageNotAnInteger: notification_pages = paginator.page(1) except EmptyPage: notification_pages = paginator.page(paginator.num_pages) context['notifications'] = notification_pages return context def get_queryset(self, *args, **kwargs): request = self.request return User.objects.get(pk=self.request.user.pk) Traceback: File "myapp\lib\site-packages\django\core\paginator.py" in count 85. return self.object_list.count() During handling of the above exception ('User' object has no attribute 'count'), another exception occurred: File "myapp\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "myapp\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "myapp\lib\site-packages\django\views\generic\base.py" in dispatch 89. return handler(request, *args, **kwargs) File "myapp\lib\site-packages\django\views\generic\list.py" in get 157. context = self.get_context_data() File "myapp\src\notices\views.py" in get_context_data 18. context = super(NotificationsListView, self).get_context_data(*args, **kwargs) File "myapp\lib\site-packages\django\views\generic\list.py" in β¦ -
Requested user profile present at two urls
For logged-in user the profile url is path('profile/', profile, name='profile'), For profile views the url is re_path(r'^profile/(?P<pk>\d+)/$',UserProfileView,name='my_profile'), but when we try to access the loggined user by '/profile/user_pk' than it was conflicting one profile present at two urls views.py @login_required def profile(request): args={'user':request.user} return render(request,'account/profile.html',args) def UserProfileView(request,pk): if pk==request.user.pk: raise(Http404) else: user = get_object_or_404(User,pk=pk) return render(request,'account/profile.html',{'user':user}) something like if requested pk is same as profile pk than raise Http else show other profile but now working still showing all profile as it was showing. -
How to enforce only one running instance of a process in python Django framework?
I have a python Django manage command that should be called upon receiving an input file but this command is not safe for parallel calls. So an input file should be processed only and only when there is no other file being processed. One solution that I have is to use a lock file. Basically, create a lock file at the start of the process and delete it at the end. I'm worried that if the process crashes the lock file won't be deleted and consequently none of the other files would be processed until we manually remove that lock file. The solution doesn't need to be specific for Django or even python, but what is the best practice to enforce that only one instance of this process is being run? -
wsgi.application failure on install of django-hosts
I'm attempting to install django-hosts. I've added django-host to my installed apps, added the necessary code at the start and end of the middleware section and I've defined ROOT_HOSTCONF and DEFAULT_HOST as per the instructions located here: https://django-hosts.readthedocs.io/en/latest/ I'm now getting the following error when I try to run the server on my local machine: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000002240DA40A60> Traceback (most recent call last): File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\servers\basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\jason\Desktop\jason\jasonsproject\wsgi.py", line 16, in <module> application = get_wsgi_application() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\wsgi.py", line 140, in __init__ self.load_middleware() File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 37, in load_middleware middleware = import_string(middleware_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\jason\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen β¦ -
Google OAuth 2.0 keep trying to callback using "http" url
I am trying to set up Google OAuth 2.0 on my homepage. Other things seem to be well set up, but CallBack url is a problem. I'm using "https" and also entered my callback url that starts with https in Google Oauth 2.0 console, but OAuth is still trying to callback configured with http url. How do I fix it? If I go directly into the callback redirection url starting with https, it works fine. -
How to set data-url attribute for an element using JavaScript?
I have a DataTables function like this: $(document).ready(function() { //DataTables Initialization let tasks_table = $('#tasks_table').DataTable({ "language": { "emptyTable": "There are no Tasks. Try changing the filter options." }, "processing": true, "serverSide": true, "ajax": { "url": "/__admin/crm/tasks_list/", "type": "GET", }, createdRow: function( row, data, dataIndex ) { let pk = data.id; let change_status_url = "{% url 'task_change_status' 1234 %}".replace(/1234/, pk.toString()); }, "columns": [ {"data": null, "defaultContent": '<div class="i-checks"><input type="checkbox" id value="" data-url=change_status_url> <i></i></div>' }, ] How do I set the default content element's data-url to the change_status_url variable? -
Django 2.0 Redirect with kwargs
I am a trying to pass kwargs but I think I have a URL path error? I am using the updated Django 2 URLS. return redirect ( 'enroll:select_prod', slug = e.slug, kwargs = { 'a': a, 'p': p, 's': s } ) this is the URL urlpatterns: path('select_prod/<slug:slug>/', views.select_prod, name = 'select_prod' ), And where it is redirected to: def select_prod ( request, slug, *arg, **kwargs ): and this is the error I get Reverse for 'select_prod' with keyword arguments '{'slug': 'cC1gBIk4Fwh7Nr5xRv', 'kwargs': {'a': '5', 'p': ['6', '7'], 's': []}}' not found. 1 pattern(s) tried: ['enroll\\/select_prod\\/(?P<slug>[-a-zA-Z0-9_]+)\\/$'] What am I doing wrong? Thanks. -
Serialize external esponse with Django Rest Framework
I am trying to consume the github api using python-requests and return the response on a generics.ViewSet. But instead of the user information I only got a lot of {}. The view: class GitHubConsumerViewSet(viewsets.GenericViewSet): serializers_class = serializers.UserSerializer path = "https://api.github.com/users" # pagination = pagination_class() def get_queryset(self, *args, **kwargs): pass def list(self, request): response = requests.get("{}users".format(self.path)) serializer = self.serializers_class(response.text, many=True) return Response(serializer.data, status=status.HTTP_200_OK) The serializer: class UserSerializer(serializers.Serializer): login = serializers.CharField(required=False) id = serializers.IntegerField(required=False) node_id = serializers.CharField(required=False) avatar_url = serializers.URLField(required=False) gravatar_id = serializers.IntegerField(required=False) url = serializers.URLField(required=False) html_url = serializers.URLField(required=False) followers_url = serializers.URLField(required=False) gists_url = serializers.URLField(required=False) starred_url = serializers.URLField(required=False) subscriptions_url = serializers.URLField(required=False) organizations_url = serializers.URLField(required=False) repos_url = serializers.URLField(required=False) events_url = serializers.URLField(required=False) received_events_url = serializers.URLField(required=False) type = serializers.CharField(required=False) site_admin = serializers.BooleanField(required=False) Any hint? -
OSError while updating pytorch
When I tried to update my pytorch version to 0.4 using the following command line conda install pytorch=0.4.0 -c pytorch I got the following error: Solving environment: done ##Package Plan## environment location: /anaconda added / updated specs: - pytorch=0.4.0 The following NEW packages will be INSTALLED: blas: 1.0-mkl intel-openmp: 2018.0.3-0 libcxx: 4.0.1-h579ed51_0 libcxxabi: 4.0.1-hebd6815_0 libgfortran: 3.0.1-h93005f0_2 mkl_fft: 1.0.4-py27h5d10147_1 mkl_random: 1.0.1-py27h5d10147_1 ninja: 1.8.2-py27h04f5b5a_1 numpy-base: 1.15.0-py27h8a80b8c_0 pytorch: 0.4.0-py27_cuda0.0_cudnn0.0_1 pytorch The following packages will be UPDATED: mkl: 2017.0.3-0 --> 2018.0.3-1 numpy: 1.13.1-py27_0 --> 1.15.0-py27h648b28d_0 Proceed ([y]/n)? y Preparing transaction: done Verifying transaction: done Executing transaction: failed ERROR conda.core.link:_execute(502): An error occurred while uninstalling package 'defaults::numpy-1.13.1-py27_0'. OSError(13, 'Permission denied') Attempting to roll back. Rolling back transaction: done OSError(13, 'Permission denied') I saw online that I should use the chown functionality but I am not sure how to use it. What should I do? -
Implementing Django ForeignKey-like subqueries without ForeignKey
I have a non-ForeignKey ID from an external system that acts as my join key. I'd like to do Django ORM style queries using this ID. My desired query is: results = MyModel.objects.filter(level='M', children__name__contains='SOMETHING') My model looks like this: class MyModel(BaseModel): LEVELS = ( ('I', 'Instance'), ('M', 'Master'), ('J', 'Joined') ) level = models.CharField(max_length=2, choices=LEVELS, default='I') parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL ) master_id = models.CharField(max_length=200) name = models.CharField(max_length=300, blank=True, null=True) This works fine with parent as a field, but parent is redundant with the master_id field: master_id indicates which children belong to which master node. I'd like to get rid of parent (primarily because the dataset is fairly large and setting the parent IDs when importing data takes a long time). The SQL equivalent of what I'm looking for is: SELECT DISTINCT( s_m.master_id ) FROM mytable s_m JOIN mytable s_i ON s_i.level = 'I' and s_m.level='M' AND s_i.master_id == s_m.master_id WHERE s_i.name like '%SOMETHING%'; I believe there's a way to use Manager or QuerySet to enable clean querying of children (in this case, the children's names) within the Django ORM framework, but I can't figure out how. Any pointers would be appreciated. -
How do make an admin see only articles published by a particular reporter
I created an admin group for different users and I want each of the admin in the group to be able to view only article that are written by them. -
How to use forms.HtmlField for in Django forms.Form
I am building an api to send mail. In the view i want to validate the post data using django form. Here is my query: How to use forms.HtmlField for in Django forms.Form I want to change my html_message from TextField to HtmlField class SendMailForm(forms.Form): subject = forms.CharField() message = forms.TextField() recipient = forms.EmailField() html_message = forms.TextField() -
Django Heroku Images Not Loading
I've seen this question in other places, but I have the correct whitenoise and Django settings (from what I can see) and my images are still not loading correctly. Here are my settings: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # other settings... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(STATIC_ROOT, 'images') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) My project: root βββ Procfile βββ README.md βββ db.sqlite3 βββ manage.py βββ mineral_catalog βββ mineral_detail βββ minerals.json βββ requirements.txt βββ static βββ staticfiles βββ images βββ Wikipedia-icon.png βββ minerals βββ templates βββ venv Template where url is used: {% block content %} <div class="grid-100 mineral__container"> <h1 class="mineral__name">{{ mineral.name }}</h1> <div class="mineral__image-bg"> {% load static %} <img class="mineral__image" src="{% static mineral.static_url %}"> <p class="mineral__caption">{{ mineral.image_caption }}</p> </div> An example mineral.static_url would be: 'images/minerals/abelsonite.jpg' -
Importing celery task within Django view
I am trying to execute a celery task that among other things, communicates with a specific Django view with a pipe. I have been trying all day to import the celery tasks file (tasks.py) from the Django views (views.py) without any success. I have also checked the file permissions but this was not the case. I have added to sys.path the path of the file desired to import (tasks.py), and then import it, but I keep getting an ImportError. However, when trying to import another script on the same folder (script1), the import succeeds. views.py ... sys.path.append('/home/celery') import script1 #SUCCEEDS # Trying to import "/home/celery/tasks.py" here import tasks #FAILS ... tasks.py ... @app.task def start_operation(client,**kwargs): # Pipe comes here ... The celery directory structure is the following: /home βββ celery βββ script1.py tasks.py And the Django proyect directory structure: /myapp βββ myapp βββ views.py Thanks in advance. -
Django Oatuh 2 REST Framework - new user registration
I am building an Django app based on the REST framework that uses Oauth2 access tokens for security. Requesting an access token from the standard endpoint /token works fine for superusers that I have created with ./manage.py createsuperuser, but when I try and create a normal user using an API endpoint and then request access, the /token endpoint says the credentials are invalid. I'm not using custom implementations of anything. How do I get the /token endpoint to validate credentials for new users created via API? # views.py # class UserSignUp(generics.CreateAPIView): permission_classes = [permissions.AllowAny, ] serializer_class = UserRegistrationSerializer And serializers: # serializers.py # from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope from rest_framework import generics, permissions, serializers class UserRegistrationSerializer(serializers.ModelSerializer): permission_classes = [permissions.AllowAny, ] #user model is the same, this serializer allows anyone to create a new user class Meta: model = User #username is a users email address fields = ('id', 'email', 'username','password','first_name','last_name')