Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ! -
Django Maths Editor
I am django newbie and working on a math based project. I need to save texts involving mathematical symbols like integral, sigma, product etc. At the same time, I also need to emphasize or bold some texts (and do all kinds of rich text editing) and include figures that explains a mathematical concept. At present, I am just saving all the fields in a CharField (with dummy texts and without including any mathematical symbol) and have no idea how to include such a field. If you have any idea/hint or you have worked on similar projects, please help. -
Filter one-to-many relationship
I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view class Aliens(models.Model): class Meta: db_table = 'aliens' verbose_name = ('Introduction Event') verbose_name_plural = ('Introuction Events') ordering = ['alien'] alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species", on_delete=models.CASCADE, null=True, blank=True) #SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True) group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE, blank=True, null=True, default='') firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True) med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE, null=True, blank=True) origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='', verbose_name=u"Origin") status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='', verbose_name=u"Establishement") created_by = CurrentUserField() created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now()) photo = models.ImageField(upload_to='photos', blank=True, null=True) vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways") updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now()) updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated', default=CurrentUserField(), null=True) notes = models.TextField(verbose_name='Notes', blank=True, null=True) db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True) def __str__(self): # __unicode__ on Python 2 return self.alien.SpeciesName class Distributions(models.Model): class Meta: db_table = 'distributions' verbose_name = ('verified occurence') verbose_name_plural = ('verified occurences') alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions', on_delete=models.CASCADE, null=True, blank=True) country = models.OneToOneField(Country, on_delete=models.CASCADE, … -
Count number of objects by date in daterange
In a Django project, I have these simplified models defined: class People(models.Model): name = models.CharField(max_length=96) class Event(models.Model): name = models.CharField(verbose_name='Nom', max_length=96) date_start = models.DateField() date_end = models.DateField() participants = models.ManyToManyField(to='People', through='Participation') class Participation(models.Model): """Represent the participation of 1 people to 1 event, with information about arrival date and departure date""" people = models.ForeignKey(to=People, on_delete=models.CASCADE) event = models.ForeignKey(to=Event, on_delete=models.CASCADE) arrival_d = models.DateField(blank=True, null=True) departure_d = models.DateField(blank=True, null=True) Now, I need generate a participation graph: for each single event day, I want the corresponding total number of participations. Currently, I use this awful code: def daterange(start, end, include_last_day=False): """Return a generator for each date between start and end""" days = int((end - start).days) if include_last_day: days += 1 for n in range(days): yield start + timedelta(n) class ParticipationGraph(DetailView): template_name = 'events/participation_graph.html' model = Event def get_context_data(self, **kwargs): labels = [] data = [] for d in daterange(self.object.date_start, self.object.date_end): labels.append(formats.date_format(d, 'd/m/Y')) total_participation = self.object.participation_set .filter(arrival_d__lte=d, departure_d__gte=d).count() data.append(total_participation) kwargs.update({ 'labels': labels, 'data': data, }) return super(ParticipationGraph, self).get_context_data(**kwargs) Obviously, I run a new SQL query for each day between Event.date_start and Event.date_end. Is there a way to get the same result with a reduced number of SQL query (ideally, only one)? I tried many aggregation … -
Django: how to use a DB parameter in a default attribute of model field?
I have created a (kind of) singleton to put all the app parameters in my database: class SingletonModel(models.Model): def save(self, *args, **kwargs): self.pk = 1 super(SingletonModel, self).save(*args, **kwargs) @classmethod def load(cls): return cls.objects.all().get() class Meta: abstract = True class AppParameters(SingletonModel, models.Model): DEFAULT_BALANCE_ALERT_THRESHOLD = models.PositiveIntegerField(default=5) # other parameters... It worked pretty well, until I tried to use one of these parameters in a default attribute of a model field: class Convive(models.Model): balance_alert_threshold = models.IntegerField( default=AppParameters.load().DEFAULT_BALANCE_ALERT_THRESHOLD, blank=True, null=True) This seemed to work too, but when I use a script to reinitialise local data, the first manage.py migrate produce a DoesNotExist since my Singleton does not exist yet. It happens because of a file importing Convive model. How would you solve this? Is there a way to "delay" the evaluation of the default field? Thanks.