Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Disable uniqueness/fk constraints before django's loaddata for Postgresql 9.6/10
I am trying to migrate data from one db to another. Previous was on peewee ORM and new one on Django. I've ported schema code and successfully run dumpdata. Now I need to run loaddata to restore from it. Problem is that DB is pretty bad, there's a lot of uniqueness/fk violationss there for legacy reasons, and I don't really want to clean it before restore. I would like to be able to just disable all checks for some time and upload as is. I tried ALTER TABLE table_name DISABLE TRIGGER ALL but from the info on the Internet I think it only disables FK checks. Unfortunately I keep receiving IntegrityError's with uniqueness violations. How can I disable uniqueness check temporarily on Postgres? Or all at once, if possible. Thanks. Postgres 9.6/10, Django 1.11.9. -
Validating email in django query
How can I validate a email field and update another field based on that in a single 'django' query. Can I do it with Regex. -
Can we use algolia search with patameter, using instance.js
Can we use algolia search with parameters, using instance.js { "institute_type": "Private", "type": "Coaching", "approved_by": "NIIT", "name": "Supply Chain Management Training Program", "college_facilities": "Guided Assignments for hands-on learning", "established": "2018-01-15", "country": "India", "address": "Delhi", "course_": "", "slug": "supply-chain-management-training-program", "image": "images/supply-chain-520.jpg", "state": "Delhi", "cities": "New Delhi", "location_type": "Domestic", "objectID": "6" } search with "type": "Coaching", and "type": "College", -
Group By each date in Django 2
I have a model called Log which has a datetime field created_at. What I want to do is to calculate the number of Logs for each date. I tried to do this: from django.db.models.functions import TruncDate Log.objects.annotate(date=TruncDate('created_at')).values('date').annotate(c=Count('id')) This is giving me the following: {'date': datetime.date(2018, 1, 17), 'count': 1}, {'date': datetime.date(2018, 1, 17), 'count': 1}, {'date': datetime.date(2018, 1, 17), 'count': 2} That is, the date is not unique. The result I want would be this: {'date': datetime.date(2018, 1, 17), 'count': 4}, {'date': datetime.date(2018, 1, 18), 'count': 2} How could approach this problem? -
Django vs PyQt for developing a simple sqlite frontend
I have been using Python for a while as a scripting language, but I am looking to improve on my knowledge as I would like to write a program that I use to manage my productions (I am a filmmaker). The problem is, at the moment, I don't have enough time to devote to learning everything about Python, so I need to choose specifically what I want to pursue. Here is what I want the program to do: 1) Act as a database of the assets and scenes I am working on. 2) Manage my project directory enforcing naming conventions, creating folders based on the scene names and assets provided by the database. 3) Use sqlite for the database, as I would prefer to have the database as a file saved locally with each project, in case I want to move the project between computers. 4) Have a GUI, even a simple one, to make interaction with the program easier. Initially, I was looking into PyQt, but while searching around, I have seen someone suggesting a web interface instead (GUI interface for sqlite data entry in Python). The questions I have: 1) I know a web interface will work with … -
Reducing cost for searching in a SQL Database using Django query
I am making an app that will search for similar drugs using the logic and models that if a drug is in a particular set of classes then other drugs that are in those and only those classes only then it will return those drugs. Here is the relevant code and dummy data - views.py class GetSimilarDrugs(APIView): def get(self, request, format=None): #import pdb #pdb.set_trace() get_req = request.GET.get('drugid', '') simi_list = [] comp_class = DrugBankDrugEPClass.objects.filter(drug_bank_id = get_req).values_list('epc_id', flat=True).distinct() for drg_id in DrugBankDrugEPClass.objects.values_list('drug_bank_id', flat = True).distinct(): classtocomp = DrugBankDrugEPClass.objects.filter(drug_bank_id = str(drg_id)).values_list('epc_id', flat=True).distinct() complist = list(comp_class) tolist = list(classtocomp) if complist == tolist: simi_list.append(drg_id) return Response({'result':simi_list}) models.py class DrugBankDrugEPClass(models.Model): drug_bank = models.ForeignKey(DrugBankDrugs, on_delete=models.CASCADE) epc = models.ForeignKey(DrugBankEPClass, on_delete=models.CASCADE) Dummy SQL Data id | drug_bank_id | epc_id | +------+--------------+--------+ | 1 | DB12789 | 1 | | 2 | DB12788 | 2 | | 3 | DB00596 | 3 | | 4 | DB09161 | 4 | | 5 | DB01178 | 5 | | 6 | DB01177 | 6 | | 7 | DB01177 | 6 | | 8 | DB01174 | 7 | | 9 | DB01175 | 8 | | 10 | DB01172 | 9 | | 11 | DB01173 | 10 … -
Wagtail Embed objects get wrapped in the DIV having the inline style padding-bottom: 56.25%
Essentially given the following template: {% for slide in value.carousel %} <div> {% include_block slide.value %} </div> {% endfor %} Wagtail would render: <div> <div style="padding-bottom: 56.25%;" class="responsive-object"> <iframe>....</iframe> </div> </div> Does anyone know where has the style="padding-bottom: 56.25%;" come from? How to edit/remove it? I tested it with youtube and vimeo both of whitch had that weird padding-bottom attribute set. Also to ensure that browser nor javascript are playing games with me I've tested it with curl. Using: wagtail==1.13.1 -
What are migrations exactly?
I started learning Django, and I did not understand the concept of migrations and why are they needed? Could anyone explain it in detail and clearly? -
Django: how to render form field without double quotes
Here is what I'm trying to achieve. I want to replace 3 static html inputs (checkboxes) with django form fields (forms.Form). When I render this piece of django template (line 43 for example): 38 <button id="visitas-mes-opcoes" class="btn btn-default col-xs-12" type="button" data-toggle="popover" 39 title="<label class='text-info'>Opções</label>" 40 data-content=" 41 <div id='opcoes-checkbox' class='checkbox'> 42 <label> 43 {{ form_pesquisar_visitas.maquinas_usadas }} 44 <input id='maquinas-usadas' class='checkbox-option' name='maquinas-usadas' type='checkbox' value='1'> 45 Máquinas Usadas 46 </label> 47 <hr style='margin: 8px -10px 8px -30px; width: 180px;'/> 48 <label> 49 <input id='vendas-efetuadas' class='checkbox-option' name='vendas-efetuadas' type='checkbox' value='1'> 50 Vendas Efetuadas 51 </label> 52 <hr style='margin: 8px -10px 8px -30px; width: 180px;'/> 53 <label> 54 <input id='vendas-perdidas' class='checkbox-option' name='vendas-perdidas' type='checkbox' value='1'> 55 Vendas Perdidas 56 </label> 57 </div>"> 58 <span class="glyphicon glyphicon-collapse-down"></span> 59 </button> I get the following result: But I was expecting something as the original html: Seems to me django is introducing some double quotes during the field rendering. Anyone knows how to work around this? -
How to add limited number of images per model in django?
I am trying to create an model for a student profile where the student can enter images to show images for their achievements. But I want to restrict the student from entering more than 5 images and one image compulsorily . How do I do that in Django? -
Django cache_page get last refresh time
I am using @cache_page on a view like this: @cache_page(60 * 60 * 24) def my_view(request): # my code return render(request, 'template.html', context) I would like to show in the template the last time the view has been refreshed (basically the last time the view was loaded without cache), how can I do that? -
django F ceil divison
I'm making annotate expression, and I don't khow how to realize what I expect. The model has 3 integer fields "AA","BB","CC" and my goal is to calculate those 3 like int(math.ceil(float(AA) / (BB)) *CC) If AA=4,BB=2,CC=3, then the answer is 6. *case1 And AA=5,BB=2,CC=3, it takes 9. *case2 annotate(ans=F("AA")/F("BB")*("CC")) This is enough for case1 because AA/BB is not round off, but in case2, the answer takes 6. I looked up this solution and found some ways. But I couldn't make it... Anyone knows solutions? -
How do I make a multiplayer concurrent game in Django?
Noob here. I'm trying to create a multiplayer game, in each team there would be 3 people. Person B submits after Person A and Person C after Person B. How do I achieve this? Preferably in python (Django). -
Django Cookiecutter
I am trying to use Cookiecutter on a Digital Ocean server. (Not using Docker) I followed the direction to install on Ubuntu 16 with Django, Postgres and Gunicorn. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 I can not get past the allowed host error. DisallowedHost at / Invalid HTTP_HOST header: '128.199.100.100:8000'. You may need to add '128.199.100.100' to ALLOWED_HOSTS I have the setting in production.py ALLOWED_HOSTS = env.list ( 'DJANGO_ALLOWED_HOSTS', default = [ '128.199.100.100' ] ) Do I need to change any setting to make it a production environment? The only documentation on the Cookiecutter site is for pythonAnywere and Docker. http://cookiecutter-django.readthedocs.io/en/latest/deployment-on-pythonanywhere.html I just want a simple DO install. Can not find any documentation? Thank you. -
django Restframework _ updating instance with unique=True fileds
I have a model that has a unique field. models.py class A(models.Model): phonenumber = models.CharField(max_length=17,unique=True) serializers.py class ASerializer(serializers.ModelSerializer): class Meta: model = A fields = "__all__" def create(self, validated_data): return A.objects.create(**validated_data) def update(self, instance, validated_data): instance.phonenumber = validated_data.get('phonenumber', instance.phonenumber) instance.save() return instance in updating instance of model A .if phonenumber be the same as before.the validation error comes up.this field already exists in database.how can i exclude instance from validation error.and I already tried : extera_kwargs = { 'phonenumber' : {'validators': []}, } -
Django Rest Framework, passing parameters with GET request, classed based views
I would like a user to send a GET request to my Django REST API: 127.0.0.1:8000/model/?radius=5&longitude=50&latitude=55.1214 with his longitude/latitude and radius, passed in parameters, and get the queryset using GeoDjango. For example, currently I have: class ModelViewSet(viewsets.ModelViewSet): queryset = Model.objects.all() And what I ideally want is: class ModelViewSet(viewsets.ModelViewSet): radius = request.data['radius'] location = Point(request.data['longitude'],request.data['latitude'] query set = Model.objects.filer(location__distance_lte=(location, D(m=distance))).distance(location).order_by('distance') Now a couple of immediate errors: 1) request is not defined - should I use api_view, i.e. the function based view for this? 2) DRF page says that request.data is for POST, PUT and PATCH methods only. How can send parameters with GET? -
Django how to find view by url
I see a page in django, but i can't find it in the project templates or any folder around it by doing search by string in files, is there a way to find these html templates from a specific page by url? or there is any other way to find them? maybe they are somehow encoded idk... -
Docker container runs with docker-compose up but doesn't with docker run
First attempt into docker and I've hit a wall. I don't understand how the docker works and when my local machine is "detached" from the container. At the end the project runs with docker-compose run, but doesn't with docker run because it cannot connect to postgres. When I run docker-compose run with these settings everything works: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': '5432', } } docker-compose.yml version: '2' services: db: image: postgres environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password ports: - '5432:5432' redis: image: redis ports: - '6379:6379' celery: build: context: . dockerfile: Dockerfile env_file: common.env command: celery -A saleor worker --app=saleor.celeryconf:app --loglevel=info volumes: - .:/app:Z links: - redis depends_on: - redis search: image: elasticsearch:5.4.3 mem_limit: 512m environment: - "ES_JAVA_OPTS=-Xms512m -Xmx512m" ports: - '127.0.0.1:9200:9200' web: build: . command: python manage.py runserver 0.0.0.0:8000 env_file: common.env depends_on: - db - redis - search ports: - '8000:8000' volumes: - .:/app:Z makemigrations: build: . command: python manage.py makemigrations --noinput volumes: - .:/app:Z migration: build: . command: python manage.py migrate --noinput volumes: - .:/app:Z However, if I run docker build -t db_test . docker run -p 4000:8000 db_test Dockerfile: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN \ … -
django elastic search index for many for many field
I have successfully integrate elastic search in one of my django project by following this tutorial, elastic search with django the easy way i have following model structure, class Product(models.Model): product_id = models.IntegerField(default=0) product_name = models.CharField(max_length=100) description = models.CharField(max_length=500, null=True, blank=True) product_tag = models.ManyToManyField(Tag) product_unit = models.ForeignKey(Unit) def __str__(self): return str(self.product_name) class ProductKeyword(models.Model): name = models.CharField(max_length=100) product = models.ManyToManyField(Product, related_name="products") date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return str(self.name) def search_indexing(self): obj = ProductKeyWordIndex( meta={'id': self.id}, name=self.name, product=self.product.product_name, date_created=self.date_created, date_updated=self.date_updated, ) obj.save() return obj.to_dict(include_meta=True) where i have create a search_indexing method for a ProductKeyword model for elastic search indexing. when i try to create a new ProductKeyword objects, raise the following error, AttributeError: 'ManyRelatedManager' object has no attribute 'product_name' at search_indexing method where i am indexing self.product.product_name, where self.product is a m2m field, in mention, the same method work perfectly for foreign field. i have tried as following by updating the search_indexing method to solve the problem, def search_indexing(self): obj = ProductKeyWordIndex( meta={'id': self.id}, name=self.name, product=self.product.product_set.all(), date_created=self.date_created, date_updated=self.date_updated, ) obj.save() return obj.to_dict(include_meta=True) but raising the following error, AttributeError: 'ManyRelatedManager' object has no attribute 'product_set' -
How to get url of task with task id of viewflow
I want the flow url with task id of viewflow For example : http://127.0.0.1/workflow/helloworld/helloworld/12/approval/23/ -
Django dynamic header for global variable
Is there any way i can use dynamic header and footer. In my project so that i can define global variable also dynamic variable data per page. <body> <header> <My dynamic header template> </header> <content> <Page template> <content> <footer> <My dynamic footer template> <footer> -
|django| Model matching query does not exist
I received error: WARNING:logger:invoice_settings_create_new_invoice ERROR: Invoice matching query does not exist. This is error I receive when try to call .save() method for object: object = Invoice(name=so_name) for fieldname, fieldvalue in invoice_data['fields'].items(): if fieldvalue['type']=='relto': model_rel = object._meta.get_field(fieldname).rel.to setattr(object, fieldname, model_rel().objects.get(pk=int(fieldvalue['value']))) else: if (object._meta.get_field(fieldname).get_internal_type() == 'IntegerField'): setattr(object, fieldname, int(fieldvalue['value'])) if (object._meta.get_field(fieldname).get_internal_type() == 'DecimalField'): setattr(object, fieldname, float(fieldvalue['value'])) if (object._meta.get_field(fieldname).get_internal_type() == 'DateField'): setattr(object, fieldname, datetime.datetime.strptime(fieldvalue['value'], "%d.%m.%Y").date()) object.save() I didn't use something complicate. I create new object. Set value for fields of object. Tried to save it. And received an error. Why is it happening? How i can fix it? -
Deploy Django 2.0 on Apache 2.2 at ubuntu 12.04
My enviroment: ubuntu 12.04 / python3.6.4 / django 2.0 / apache 2.2.22 I want to deploy django on apache I followed django official but still not work. I want to deploy at www.domainname.com/django/ my httpd.conf WSGIScriptAlias / /home/username/django/mysite/wsgi.py WSGIPythonHome /home/username/django/virtual_env WSGIPythonPath /home/username/django <Directory /home/username/django/mysite> <Files wsgi.py> Order deny,allow Allow from all </Files> </Directory> but it doesn't work. I can see 'It works' at 127.0.0.1/ but nothing in 127.0.0.1/django/ How can I set for deploy my django site? -
password_set signal not working in Django allauth
What I am trying to do ? I am trying to redirect a new user to login dialog after user sets a password for the first time. (I am doing this because the movement user sets a password Django implicitly logout the user) What is the problem ? For some reason the password_set signal doesn't seem to work. i.e the sender function loginAfterPassChange doesn't get executed. My Code: How do I set password views.py: @receiver(user_logged_in) def getFirstTimePass(user, request, **kwargs): #this works if user.profile.provider != '' and user.profile.firstTimeLogin: user.profile.firstTimeLogin = False user.profile.save() raise ImmediateHttpResponse(render(request, 'index.html', {'type': user.profile.provider, 'email': user.email})) @receiver(password_set) def loginAfterPassChange(request, user, **kwargs): #this doesn't work data = {'msg': 'Please login with your new password.'} return HttpResponse(data) def setPassword(request): #this works data = {'errMsg': 'Something went wrong.'} if not request.user.has_usable_password(): password = request.POST.get('password') request.user.set_password(password) request.user.save() data['errMsg'] = '' return JsonResponse(data) urls.py: from django.conf.urls import url from .import views urlpatterns = [ url(r'^updatePro', views.setPassword, name='updatePro') ] models.py: class Profile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) provider = models.CharField(max_length=256, default='') firstTimeLogin = models.BooleanField(default=True) if user.profile.provider != '' Check to see if user is logged in with social account or local account. -
Django : mptt_instance.delete() mess my tree
I make a Django Webapp, that uses tree of nested categories (I use MPTT for that). I would like to allow the user to delete the category that he/she wants, no matter where the category is in the tree. I tried a form with a "category.delete()" method, it deletes the category in my database but nothing is updated for ancestors and children, so when I try to comeback to my categories_list page, I get an error If I delete the exact same category through django admin panel, the category is deleted as well, but the database is perfectly updated, so when I go to my categories_listing page, It works perfectly. So my question is : What does django Admin "delete" action, that category.delete() doesn't ? Thank you !