Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PermissionError: [Errno 13] Permission denied: '/app/manage.py' when trying to create project with docker-compose
I was following a tutorial on how to create Django REST Framework API with Docker and succeeded to run the project on the first attempt, but then it's not possible to recreate it due to PermissionError. The directory structure looks in the following way: project_directory - Dockerfile - docker-compose.yml - requirements.txt - app/ # this directory was created manually Successful configuration looks this way: Dockerfile: FROM python:3.7-alpine LABEL author="aqv" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache postgresql-client RUN apk add --update --no-cache --virtual .tmp-build-deps \ gcc libc-dev linux-headers postgresql-dev RUN pip install -r /requirements.txt RUN apk del .tmp-build-deps RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user USER user requirements.txt: Django>=2.1.3,<2.2.0 djangorestframework>=3.9.0,<3.10.0 psycopg2>=2.7.5,<2.8.0 docker-compose.yml: version: "3" services: app: build: context: . ports: - "3005:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=app - DB_USER=postgresuser - DB_PASS=<pass> depends_on: - db db: image: postgres:10-alpine environment: - POSTGRES_DB=app - POSTGRES_USER=postgresuser - POSTGRES_PASSWORD=<pass> First step was running (1) docker build . in the project directory, then came (2) docker-compose build (which made the 1st command redundant, but didn't break anything) and … -
Generate and save hash based on uploaded file
Currently I am able to upload files in Django Admin using a FileField. What I want to achieve is: Creating a hash based on the uploaded file and save it as a field Determine the file_size of the uploaded file and save it as a field My models.py class File(models.Model): file_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) file_name = models.CharField(max_length=256) file_mime = models.CharField(max_length=20) file_size = models.PositiveIntegerField(blank=True, null=True, editable=False) file_hash = models.CharField(max_length=256, unique=True, blank=True, editable=False) data = models.FileField(upload_to=get_dynamic_path) customer_uuid = models.ForeignKey(Customer, on_delete=models.CASCADE) I tried to override the save() method like this: # models.py def save(self, *args, **kwargs): super(File, self).save(*args, **kwargs) f = self.data.open('rb') h = hashlib.sha1() if f.multiple_chunks(): for chunk in f.chunks(): h.update(chunk) else: h.update(f.read()) f.close() self.sha1 = h.hexdigest() self.file_size = self.data.size super(File, self).save(*args, **kwargs) When I upload a file, it uploads just fine but the file_size and file_hash fields are empty. What do I need to change in order to: Succesfully generate a hash based on the uploaded file and save it in the file_hash field. Determine the file size of the uploaded file and save it in the file_size field. Thanks! -
Recursively querying a many-to-many relationship
I'm trying to build a family tree in Django and I can't figure out how to reference an object's children, and the children's children of the object's children, and so on. . This is my model with the function I'm using to try to get the family tree: class Member(models.Model): referrals = models.ManyToManyField("self", symmetrical=False) def tree(self): refs = {} for ref in self.referrals.all(): refs[ref] = ref.tree() return refs This seems to work, however, if the children also has children, then it says the following: maximum recursion depth exceeded while calling a Python object Ideally, I want the tree function to return a string object that is a nested list, so I can just place the result in the template, as follows: <ul> <li>Member A</li> <li>Member B <ul> <li>Member BA</li> <li>Member BB</li> </ul> </li> <li>Member C</li> </ul> Would appreciate any suggestions, thanks -
Create Form and update using same view in django
I am trying to use same view for creating form and updating any object. My code is as below, I tried in many ways nothing is working, since I am excluding the shof from form and adding it after form.is_valid() it makes lot of confusion. If I update it creates new object. please help fix this, @csrf_protect @login_required def addmenu(request, qs, ql=None): v = vdview(request, qs) ctgobj = get_object_or_404(v.shopcategs, pk=ql) if ql else None # ctgobj = ShopCtg(shop=v.shof) if ql: form = ShopCtgForm(instance=ctgobj) else: form = ShopCtgForm(data= request.POST) if request.method == 'POST': if form.is_valid(): form.save(commit=False) f.shop = v.shof f.save() #form.save_m2m() return redirect('vendor-shop', qs) #thing='%s added' %f.name) else: pass #else: # form = ShopCtgForm() return render(request,'vendorshop.html', {'shop':v.shof, 'shopcategs':v.shopcategs, 'form': form, 'heading':'Create New Category', 'createcateg': 'createcateg', 'pkaddmenupk':'y' } ) -
Why do I receive lots of ConnectionResetErrors with chromedriver?
When running tests on a django site using selenium and chromedriver, I receive lots of ConnectionResetErrors. The full error output is included at the bottom. Note that tests pass fine even so - the issue is the flood of exception messages in the console. No ConnectionResetErrors occur when using geckodriver. If I run any single test, the error does not occur, but when I run all tests the console output is flooded with these errors. I have already looked over answers to similar questions, but I have not been able to find any good solution that is applicable. My test cases extend a common class which handles setUp and tearDown. This common class in turn extends StaticLiveServerTestCase. The relevant part of the setUp method is: self.chromedriver = chrome.webdriver.WebDriver(executable_path=r"chromedriver.exe") self.chromedriver.implicitly_wait(10) No other lines of code affect the configuration of the self.chromedriver object. I have tried calling self.chromedriver.quit() in the tearDown method, but this just seems to causes more of the same kind of error message. It also causes an error message when a single test is run. What is causing the flood of ConnectionResetErrors? The versions are: > python -c "import selenium; print(selenium.__version__)" 3.141.0 Chrome: 73.0.3683.103 > chromedriver --version ChromeDriver 73.0.3683.68 … -
How to upgrade sqlite3 version from 3.7.17 to > 3.8
Trying to launch new django app but get error- django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). i already installed sqlite 3.27 and its in /usr/local/bin i tried suggested procedure here- How to upgrade sqlite 3.8.2 to >= 3.8.3 but no luck [ec2-user@ip-]$ sqlite3 SQLite version 3.27.2 2019-02-25 16:06:06 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> but when i do python3 manage.py migrate or runserver i get raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) I expect for django2 to take path of executable sqlite3 version that is sitting in /usr/local/bin. -
Check if object_id occurs more than once in queryset.annotate Case When parameter
I feel like i am very close yet i cant find an answer. Documentation field look up doesnt really help in my case What my query looks like now date_delta = 2 queryset.annotate(owner_name=F('owner_id__name')).values('owner_name', 'owner_id').annotate( views = Sum(Case(When(owner_id__gt=1, then=F('views') / date_delta)), default=('views'), output_field=IntegerField() ), views_u = Sum(Case(When(owner_id__gt=1, then=F('views_u') / date_delta)), default=('views_u'), output_field=IntegerField() ) , shares= Sum(Case(When(owner_id__gt=1, then=F('shares') / date_delta)), default=('shares'), output_field=IntegerField() ), interaction_rate = Sum(Case(When(owner_id__gt=1, then=F('interaction_rate') / date_delta)), default=('interaction_rate'), output_field=IntegerField() ), mean_age = Sum(Case(When(owner_id__gt=1, then=F('mean_age') / date_delta)), default = ('mean_age'), output_field=IntegerField() ) ) I realised that it will work fine, but it will be wrong, since if owner_id is great it will divide by date_delta, where in my case I want if owner_id occurence in queryset more than once. I have tried owner_id__count__gt but that doesnt exist :( I would love to know if there is a way to count owner_id occurence in my annotate Case(When()) queryset. that will literally solve my problem. if it's greater than 1 than we divide by date_delta, else we leave it as it is -
Why many-to-many with two modelforms not save correctly?
I have two models, one with many to many field. Two modelforms (because one have a leaflet widget), and I need these forms to be shown individally by field in template. I get them to display correctly but the form is not saved. I think there must be an error in the views, but I can not find it models.py class Contribuyente(models.Model): nombre = models.CharField(max_length=20) CONTRIBUYENTES = ( ('Pr', 'Productor'), ('VI', 'Vendedor de insumos'), ('E', 'Empresa'), ('I', 'Institución'), ) tipo_de_contribuyente = models.CharField(max_length=2, choices=CONTRIBUYENTES, primary_key=True, help_text="¿Quién sos?") def __str__(self): return self.tipo_de_contribuyente class Ensayo(models.Model): CONTRIBUCION = ( ('H', 'Hibridos_Maiz'), ('VS', 'Variedades_Soja'), ('F', 'Fertilizantes'), ('H', 'Herbicidas'), ('I', 'Insecticidas'), ('F', 'Fungicidas'), ('C', 'Coadyudantes'), ('In', 'Inoculantes'), ) nombre_contribucion = models.CharField(max_length=280) tipo_de_contribucion = models.CharField(max_length=2, choices=CONTRIBUCION, primary_key=True, help_text="Seleccioná sobre que contribuís") fecha = models.DateField(default=datetime.date.today) contribuyentes = models.ManyToManyField(Contribuyente) archivos = models.FileField(upload_to='archivos_de_ensayos/', null=True, blank=True) texto = models.TextField() geom1 = models.MultiPointField(null=True) def __str__(self): return self.tipo_de_contribucion forms.py class ContribuyenteForm(ModelForm): class Meta: model = Contribuyente fields = ['nombre', 'tipo_de_contribuyente'] class CustomLeafletWidget(LeafletWidget): geometry_field_class = 'YourGeometryField' class EnsayoForm(ModelForm): class Meta: model = Ensayo fields = ['tipo_de_contribucion','nombre_contribucion', 'fecha','archivos','texto','geom1'] exclude = ['contribuyentes'] widgets = { 'fecha': forms.DateInput(attrs={'class': 'datetime-input'},), 'geom1': CustomLeafletWidget() } labels = { 'texto': _('Texto de aporte'), 'archivos': _('Archivos:'), } help_texts = { 'texto': _('Escribe … -
Django admin override changelist url
I've a proxymodel in the admin and want to change it's default changelist_view from: django.contrib.admin.options.changelist_view "myapp_mymodel_changelist" to "myapp_Othermodel_changelist" I've tried to override the method: class mymodelAdmin(admin.ModelAdmin): def changelist_view(self, request, extra_context=None): return OthermodelAdmin.changelist_view(self,request, extra_context=None) but still get back to same changeview. I I override urls: def urls(self): urls = self.get_urls() urls =+ OthermodelAdmin.urls() return urls it says thereis a circular url how can I do the redirect? -
How to find user from websocket request?
In django channels 2.1.2 we can get the authenticated logged in user by following: class ChatConsumer(AsyncConsumer): async def websocket_connect(self,event): logged_in_user = self.scope['user'] How do i find logged in user in case of channels 1.1.8 when inheriting WebsocketConsumer from channels.generic.websockets class ChatConsumer(WebsocketConsumer): def connect(self, message, **kwargs): logged_in_user = ? -
Tornado testing with timeout response
actually i've 2 tornado running on 1 machine and from time to time they got frozen. I'm coding a script to test the response of them or the timeout but with no luck. I tried python3 -m tornado.testing tornado.test.web_test wich works fine and give me some test results, so i was wondering if there is a way to make a ping to a tornado and get a response maybe from a .py file or directly from console. Any ideas will be appreciated. Thanks -
ValueError when assigning m2m relationship after data saved - invalid literal for int() with base 10: 'Music'
I'm creating an object 'Show' with many attributes. One of its attributes is 'categories' which is a Many to Many field, related to another object 'Categories'. Before I create the 'Show' (by taking data from a passed in object), I'm creating the categories for which that Show will be assigned, like this: for each_category in parsed_podcast.categories: Category.objects.get_or_create(title=each_category, slug=slugify(each_category), full=each_category, ) The above code is creating objects in my Category model, I can check and see that they are there. Once they are there, next I create the Show object, with lots of attributes which I've stripped because they're not relevant: try: podcast_instance = Show.objects.get(title=parsed_podcast.title) except Show.DoesNotExist: podcast_instance = Show(title=parsed_podcast.title, slug=slugify(parsed_podcast.title), image_title=parsed_podcast.image_title, image_url=parsed_podcast.image_url, ..... ) podcast_instance.save() All of this is working fine, until I now try to assign the category (from parsed_podcast.categories) to the newly created Category created in the first step, like so: for each_category in parsed_podcast.categories: print('The category in the parsed podcast is {}'.format(each_category)) podcast_instance.categories.add(each_category) I can never assign the category - it always just remains as an option when I check the Django Admin on the model. I want to assign it programmatically but I get I get back an error saying: ValueError: invalid literal for int() with … -
Specifiy another location for Behave step definitions in PyCharm
At work, we have accumulated quite some step definitions in our bigger projects that somehow overlap. Hence, we decided that we want to factor out the step definitions into a separate package and use this accross multiple Django apps. My idea was to create the features/steps directoy in any Django app that wants to use the package with the following contents: from our_testing_package.steps import * While this works with behave without a problem, we loose the convenient and great features of the BDD integration that PyCharm offers, e.g. autocompletion and generation of step definition from our feature file. Especially the first is crucial with this many step definitions. I suppose PyCharm simply looks into each python file inside the features/steps directory and analyses the text inside them by looking for step definitions. Is there a possiblity to tell PyCharm that there is another folder with step definitions or if I have to adapt my python code in a way that PyCharm can follow the link to the external package? -
I cannot pull objects from database anymore
i am new to python & django. i tried to make a blog (bootstrap template) and the first 4 pages are working with the database and models that i've created. but for the 5th page i somehow cannot pull any data from the objects that i've made in de admin page of django. i deleted the migrations and redo them several times. even flushed the database and cache. it seems like my models are capable just to 4 classes and not more this is my overmij.html where i tried to pull data (in this case some content from the admin) like the previous pages and it doesn't work. overmij.html (doesn't show any content) <h1>overmij</h1> {{info.content}} exercise.html <!-- Main Content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="post-preview"> {% for exercise in exercises %} <a href="{% url 'web_app:exercise_detail' exercise.id %}"> <h2 class="post-title"> {{exercise.title}} </h2> </a> <p class="post-meta">Posted by Med {{exercise.published}}</p> <hr> {% endfor %} </div> <hr> <!-- Pager --> <div class="clearfix"> <a class="btn btn-primary float-left" href="{% url 'web_app:index' %}">&larr; Go to Articles </a> </div> </div> </div> </div> views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Article, Exercise from .models import Overmij def index(request): … -
Accessing Model Data in another model
Hello i have created a simple model and now i want to access the data in another model to view it later on. My model looks like this: from django.db import models class A(models.Model): asd = models.CharField(max_length=50,default="DEFAULT VALUE") def __str__(self): return(self.asd) Now i want a second model in which i get the data from the first model and add each element to a list or something like that. For Background i am doing this like so, so i can create a drop down widget with choices that can be changed and added to in the admin page. -
Reverse for 'quiz_change' with arguments '('',)' not found. 1 pattern(s) tried: ['suppliers/quiz/(?P<pk>[0-9]+)/$']
urls.py from django.urls import include, path from .views import classroom, suppliers, teachers urlpatterns = [ path('', classroom.home, name='home'), path('suppliers/', include(([ path('', suppliers.QuizListView.as_view(), name='quiz_list'), path('interests/', suppliers.SupplierTruckView.as_view(), name='supplier_trucks'), path('taken/', suppliers.TakenQuizListView.as_view(), name='taken_quiz_list'), path('quiz/<int:pk>/', suppliers.take_quiz, name='take_quiz'), path('quiz/edit/<int:pk>/', suppliers.edit_quiz, name='edit_quiz'), # teachers modules path('quiz/add/', suppliers.QuizCreateView.as_view(), name='quiz_add'), path('quiz/confirm/<int:pk>/', suppliers.QuizUpdateView.as_view(), name='quiz_change'), path('quiz/<int:pk>/delete/', suppliers.QuizDeleteView.as_view(),name='quiz_delete'), path('quiz/<int:pk>/question/add/', suppliers.question_add, name='question_add'), path('quiz/<int:quiz_pk>/question/<int:question_pk>/', suppliers.question_change, name='question_change'), path('myposts', suppliers.QuizListView1.as_view(), name='quiz_change_list'), path('quiz/<int:pk>/results/', suppliers.QuizResultsView.as_view(), name='truck_results'), ], 'classroom'), namespace='suppliers')), views.py class QuizUpdateView(UpdateView): model = Activetruck fields = ('name', 'subject', 'origin', 'destination','total_trucks','scheduled_date','offered_price',) context_object_name = 'quiz' template_name = 'classroom/suppliers/quiz_change_form.html' def get_context_data(self, **kwargs): kwargs['questions'] = self.get_object().questions1.annotate(answers_count=Count('answers1')) return super().get_context_data(**kwargs) def get_queryset(self): return self.request.user.activetruck.all() def get_success_url(self): return reverse('suppliers:quiz_change', kwargs={'pk': self.object.pk}) when my django app try to access the undermentioned URL: path('quiz/confirm//', suppliers.QuizUpdateView.as_view(), name='quiz_change'), it shows NoReverseMatch error. I am unable to figure out where this is coming from. Should I add the traceback too ? -
Using ArrayField and adding 'django_postgres_extensions' to INSTALLED_APPS causes LookupError: No installed app with label 'admin'
I am using postgres with Django and one of the fields in the model should be an Array. When I was trying to use it I was recommended that I use "django_postgres_extensions" so I ran "pip install django_postgres_extensions" and even added 'django_postgres_extensions' to INSTALLED_APPS to settings.py. from django_postgres_extensions.models.fields import ArrayField from django.conf import settings from django.db import models class Passenger(models.Model): firstName = models.CharField(max_length=255, null=False, blank=False, default="default") lastName = models.CharField(max_length=255, null=False, blank=False, default="default") encodings = ArrayField(models.IntegerField(), default=[], form_size=10, blank=True) photo = models.ImageField(upload_to="passenger/", null=True, blank=True) Each time I run "python manage.py runserver", I get the following error: Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Kyoko\AppData\Local\Programs\Python\Python36-32\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 … -
Django SSL redirection on Heroku: 'Too many redirects'
I have a web app deployed to Heroku with a custom domain name which DNS is managed through CloudFlare. What I want to do is redirect HTTP requests to HTTPS. After setting SECURE_SSL_REDIRECT to True, according to Django's documentation, I encounter a Too many redirects (or site redirected you too many times) error while accessing the site via the custom domain. This is what I have in my settings.py file: SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('X-Forwarded-Proto', 'https') Note that this redirect works with the myapp.herokuapp.com domain. I am using DNS + Proxy on CloudFlare, and SECURE_PROXY_SSL_HEADER is set according to Heroku's documentation. Here is the Heroku log: 2019-04-17T11:21:08.514202+00:00 heroku[router]: at=info method=GET path="/" host=staging.mywebsite.com request_id=cf90ab0c-0895-4faf-aeea-5ee5fe5f970d fwd="115.87.132.194,172.68.242.176" dyno=web.1 connect=0ms service=2ms status=301 bytes=228 protocol=http -
How to implement shortcut keys in Django using jquery?
I have been working for a accounting based project using Django-2.0.6 and python-3.6. I want to implement shortcut keys in my project using jquery. I have tried a library known as django-keyboard-shortcuts but it doesnot supports python3. So I want to do it using jquery or any other option(if is there). For example: If I press Cntrl + R or any other combination from my keyboard it will redirect me to the desired url given in the combination. Any idea how to do it? Thank you -
Search field on generic foreign key field
I am trying to add a search field to the Django admin model CreditsAdmin that will allow me to search the email of related customer objects. The Customer object has a generic foreign key to many different typed of object all of which have an email. I've already tried defining the function customer_email on the Customer object and using it as a search field, but this gives the error Related Field got invalid lookup: customer_email class Customer(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') @property def customer_email(self): return str(self.content_object.email) class Credits(models.Model): credits_remaining = models.IntegerField() current_period_start = models.DateTimeField() current_period_end = models.DateTimeField() customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class CreditsAdmin(admin.ModelAdmin): list_display = ( 'current_period_start', 'current_period_end', 'customer_name', 'credits_remaining', ) search_fields = ('customer__customer_email',) I'd like to be able to search the emails of related generic objects on the Customer model from the CreditsAdmin interface. In particular, one of the content_types that the customer objects relate to is django's auth.User model, but there are also others. -
How to send file requested by user from front end as response using drf
When a user clicks on value, i am posting that value to api where it has search for a file and return the file. I am posting the value to backend and reading it, but when i tried to display data in the front end, it is showing an error. How can a search for file and send file requested by user using drf? -
how to pass array value and array label in javascript function for graph
I have code but code have values and labels for each plot .I want to plot array values and labels in graph . How to pass values and labels from array ? chartObj = FusionCharts( 'msspline', 'ex1', '600', '400', 'chart-1', 'json', """{ "chart": { "caption": "Support Tickets : Received vs Resolved", "yaxisname": "# of Tickets", "subcaption": "Last week", "numdivlines": "3", "showvalues": "0", "legenditemfontsize": "15", "legenditemfontbold": "1", "plottooltext": "<b>$dataValue</b> Tickets $seriesName on $label", "theme": "fusion" }, "categories": [ { "category": [ { "label": "dated[i]" }, { "label": "Jan 2" }, { "label": "Jan 3" }, { "label": "Jan 4" }, { "label": "Jan 5" }, { "label": "Jan 6" }, { "label": "Jan 7" } ] } ], "dataset": [ { "seriesname": "Received", "data": [ { "value": "55" }, { "value": "45" }, { "value": "52" }, { "value": "29" }, { "value": "48" }, { "value": "28" }, { "value": "32" } ] }, { "seriesname": "Resolved", "data": [ { "value": "50" }, { "value": "30" }, { "value": "49" }, { "value": "22" }, { "value": "43" }, { "value": "14" }, { "value": "31" } ] } ] }""") -
Celery version compatibility issue
I am not able to configure the already existing django project.The project is handled with fabric and using commands I have installed all the packages and I am getting "ImportError: cannot import name Celery" error in my code as shown here in this [Image]. 1 The directory structure is as below: - proj/ - manage.py - fabfile.py - proj/ - __init__.py - celery.py - settings.py - urls.py The celery.py import os from celery import Celery from django.conf import settings from dotenv import load_dotenv load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.development') app = Celery('electric_soul') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) The ini.py file is: # -*- coding: utf-8 -*- __version__ = '1.0.1-dev' __version_info__ = tuple([int(num) if num.isdigit() else num for num in __version__.replace('-', '.', 1).split('.')]) from .celery import app as celery_app # noqa Tried: I have changed the name of celery.py I have added the from __future__ import absolute_import, unicode_literals at first line on ini.py and celery.py. -
How to fix 'Settings' object has no attribute 'CASSANDRA_FALLBACK_ORDER_BY_PYTHON'
I'm setting cassandra engine in django project, I successfully run server but when I click model of myapp in admin site I got error Settings' object has no attribute 'CASSANDRA_FALLBACK_ORDER_BY_PYTHON I first sync cassandra then migrate it,after that i runserver there are no error but in admin site when i want to put data in my modeli got this error For database I use django_cassandra_engine DATABASES = { 'default': { 'ENGINE': 'django_cassandra_engine', 'NAME': 'db', 'TEST_NAME': 'Test Cluster', 'HOST': '127.0.0.1 ', 'POST': '9042', 'OPTIONS': { 'replication': { 'strategy_class': 'SimpleStrategy', 'replication_factor': 1 }, 'connection': { 'consistency': ConsistencyLevel.LOCAL_ONE, 'retry_connect': True # + All connection options for cassandra.cluster.Cluster() }, 'session': { 'default_timeout': 10, 'default_fetch_size': 10000 # + All options for cassandra.cluster.Session() } } } and I have model like from cassandra.cqlengine import columns from django_cassandra_engine.models import DjangoCassandraModel class mymodel(DjangoCassandraModel): name = columns.Text(required=True) phone = columns.Integer(primary_key=True) in my terminal i get Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django_cassandra_engine/models/__init__.py", line 745, in order_by *self._get_ordering_condition(col)) File "/usr/local/lib/python3.7/dist-packages/cassandra/cqlengine/query.py", line 1133, in _get_ordering_condition raise QueryException("Can't resolve the column name: '{0}'".format(colname)) cassandra.cqlengine.query.QueryException: Can't resolve the column name: 'pk' File "/usr/local/lib/python3.7/dist-packages/django/conf/__init__.py", line 80, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'CASSANDRA_FALLBACK_ORDER_BY_PYTHON' I also use rest_framework for … -
How to integrate a biometric device with a django web application?
I am trying to intergrate the Biometric device ZKteco-F18 with my django web application. I need to access the user database and attendance from the device as well as add new users from the web app. Can anyone suggest a python library or any similar options for this problem ? Already tried using zklib library.But it doesnt fetch the data properly.