Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reuse a cloudfoundry app without having to rebuild from sratch
I deploy a Django Application with Cloudfoundry. Building the app takes some time, however I need to launch the application with different start commands and the only solution I have today is fully to rebuild each time the application. With Docker, changing the start command is very easy and it doesn't require to rebuild to the whole container, there must be a more efficient way to do this: Here are the applications launched: FrontEndApp-Prod: The Django App using gunicorn OrchesterApp-Prod: The Django Celery Camera & Heartbeat WorkerApp-Prod: The Django Celery Workers All these apps are basically identical, they just use different routes, configurations and start commands. Below is the file manifest.yml I use: defaults: &defaults timeout: 120 memory: 768M disk_quota: 2G path: . stack: cflinuxfs2 buildpack: https://github.com/cloudfoundry/buildpack-python.git services: - PostgresDB-Prod - RabbitMQ-Prod - Redis-Prod applications: - name: FrontEndApp-Prod <<: *defaults routes: - route: www.myapp.com instances: 2 command: chmod +x ./launch_server.sh && ./launch_server.sh - name: OrchesterApp-Prod <<: *defaults memory: 1G instances: 1 command: chmod +x ./launch_orchester.sh && ./launch_orchester.sh health-check-type: process no-route: true - name: WorkerApp-Prod <<: *defaults instances: 3 command: chmod +x ./launch_worker.sh && ./launch_worker.sh health-check-type: process no-route: true -
Boolean True/False/None
Probably stupid or already answered question here, sorry about that. I know by definition a Boolean is supposed to have 2 values but I was wondering what is the good practice in Django to store a "third" None value let's say for optional Boolean fields. So far I use a CharField or a ChoiceField with "yes", "no", "no_data" but I feel like it's not optimal. Is there a better way maybe using a special BooleanField that could store true/false/null or something like that? -
How to rotate image before save in Django?
Now I'm creating a web app which allows user to upload images using Django Rest Framework. I'd like to rotate those images according to EXIF tag and save. At first, I found this way, and it works in local environment. But, now I use Amazon S3 for deployment, then this way doesn't work. So, I'm trying to rotate image before save and struggling... Recent code is below, raising TypeError at /api/work/ 'str' object is not callable when I post new Work object. How to fix it? Or is there other nice way? [models.py] from django.db import models from django.conf import settings from PIL import Image as Img from PIL import ExifTags from io import BytesIO from django.core.files import File import datetime class Work(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=120) made_date = models.DateField(default=datetime.date.today, null=True, blank=True) note = models.TextField(max_length=2000, null=True, blank=True) image = models.ImageField(upload_to='work_pic', default='default_image.png') def __str__(self): return self.title def save(self, *args, **kwargs): if self.image: pilImage = Img.open(BytesIO(self.image.read())) for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break exif = dict(pilImage._getexif().items()) if exif[orientation] == 3: pilImage = pilImage.rotate(180, expand=True) elif exif[orientation] == 6: pilImage = pilImage.rotate(270, expand=True) elif exif[orientation] == 8: pilImage = pilImage.rotate(90, expand=True) output = BytesIO() pilImage.save(output, format='JPEG', … -
Python virtual environment with python 3.7 and Apache: Do I have to compile mod_wsgi?
After many strenuous hours I am still not able to get a virtual environment for a Django project run. My Django project works locally (with runserver, no apache, with python 2.7 and venv). It also has been working before on the development server with Apache but without venv and with default python version 2.7. Now I am trying to use a virtual environment that uses python 3.7. STEP 1: I created a virtual environment with python 3.7: sudo virtualenv -p /usr/bin/python3.7 /var/www/abcd.com/venvs/venv_core cd /var/www/abcd.com/venvs/venv_core/bin source activate sudo ./pip install --upgrade pip cd ../../../ sudo venvs/venv_core/bin/pip install -r requirements.txt (--system-site-packages is turned off by default) The python version 3.7 is already included in Ubuntu 18.04.1. So I used it. (In a prior try to compile python 3.7 myself I got completely lost and had to roll back to a prior snapshot of the virtual machine.) system: Ubuntu 18.04.1 LTS "bionic" included Python versions: 2.7.15rc1 (sys default), 3.6.5 (sys default), 3.7.0b3 Apache/2.4.29 (Ubuntu) https://docs.python.org/3/library/venv.html https://virtualenv.pypa.io/en/stable/reference/ This venv seems to be created correctly. I also adapted the wsgi config (see below). http://modwsgi.readthedocs.io/en/develop/user-guides/installation-issues.html# But when I restart the apache I get the error: ImportError: No module named site https://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html#virtual-environment-and-python-version Django Apache and Virtualenv ImportError: … -
Having external django application using bootstrap without touching templates?
I am using django-allauth application. It has got many views built-in, but none has been configured to use boostrap (ie, css class="form-control" is missing in forms). There are many python libraries to add this "form-control" css class in forms (django-bootstrap4, django-widget-tweaks, django-bootstrap-form etc...) but all requires to have access to the template in order to add specific tags or filters. As django-allauth has got many views, I do not want to override all corresponding templates to add these specific tags/filters : It will be a very long work and will be awful to maintain when upgrading to another django-allauth version. Actually, the only solution I found is to write a middleware that parses and patches HTML code to add bootstrap css classes. It works with all views without having to touch any templates. The main drawback is that it is CPU expensive. Do you know a library that can add bootstrap css classes to forms without having to modify templates and is not based on HTML parsing ? -
TDD in Django, how to unit test my modelform?
I'm new to TDD, and trying to apply TDD practice in a Django project. Based on London school TDD workflow, I'm working outside-in, view layer, form layer and model layer. At form layer, I plan to construct a modelform, with some custom validation methods. I think, based on TDD, I need to only test my custom methods, without touching: the whole ModelForm logic provided by Django, which is a well-tested dependency. the lower model layer, which does not exist yet. But how can I do it? For example, with the following modelform: from django import forms from app import models class MyModelForm(forms.ModelForm): class Meta: model = models.MyModel fields = ("field1", "field2") def clean_field1(self): # custom cleaning logic def clean_field2(self): # custom cleaning logic def clean(self): # custom cleaning logic How can I (or should I) mock MyModel? I've come up with @patch("app.forms.MyModelForm._meta.model") class FormTest(TestCase): #... But maybe it's a little bit insane? And I'm not sure how well the Mock object will work with ModelForm internal logic. For one thing, all form fields are gone, aren't they? How can I unit test these custom methods? By setting self.cleaned_data manually? -
Access name of image in django models
I want to add a watermark to an image in django from database, for this I have to access Image name in String format Currently I am Using this Technique original_pic = Photo.objects.values('original_pic') image = Image.open(original_pic.values()).convert('RGBA') but my 'original_pic' is of dictionary type, It returns data in QuerySet <QuerySet [{'original_pic': 'temp4.jpg'}, {'original_pic': 'facebook.jfif'}, {'original_pic': 'html.png'}, {'original_pic': '1001.jpg'}, {'original_pic': '1002.jpg'}, {'original_pic': '1003.jpg'}, {'original_pic': '1005.jpg'}, {'original_pic': '1007.jpg'}, {'original_pic': '1018.jpg'}, {'original_pic': '1009.jpg'}, {'original_pic': '1010.jpg'}, {'original_pic': '1011.jpg'}, {'original_pic': '1012.jpg'}, {'original_pic': '1016.jpg'}, {'original_pic': 'unity.png'}, {'original_pic': 'linkedin1.jpg'}, {'original_pic': 'android.png'}, {'original_pic': '1027.PNG'}, {'original_pic': 'github.jpg'}]> I want to retrieve data in Plain String Format -
Get query to return list of values instead of objects in graphene-django
My django model looks as follows: class Article(model.Model): slug = models.SlugField(db_index=True, max_length=255, unique=True) title = models.CharField(db_index=True, max_length=255) body = models.TextField() tags = models.ManyToManyField( 'articles.Tag', related_name='articles' ) def __str__(self): return self.title class Tag(model.Model): tag = models.CharField(max_length=255) slug = models.SlugField(db_index=True, unique=True) def __str__(self): return self.tag And my schema.py: class ArticleType(DjangoObjectType): class Meta: model = Article class Query(ObjectType): article = graphene.Field(ArticleType, slug=graphene.String()) def resolve_article(self, info, slug): article = Article.objects.get(slug=slug) return article Querying this model with: query { article(slug: "my_slug") { id title body slug tags { tag } } } Produces: { "data": { "article": { "id": "1", "title": "How to train your dragon 1", "slug": "how-to-train-your-dragon-y41h1x", "tagList": [ { "tag": "dragon", "tag": "flies" } ] } } } **Question: ** How can I customize the returned json output? In particular, tagList is a list of objects where the "tag" key is redundant. I would instead like to return a list of strings such that the output becomes: { "data": { "article": { "id": "1", "title": "How to train your dragon 1", "slug": "how-to-train-your-dragon-y41h1x", "tagList": ["dragon","flies"] } } } How can I do this?? -
Django : Even if my form is valid , I got some fields empty when printing cleaned_data
I have this model form : class sarlform(forms.ModelForm): # sarll=forms.ChoiceField(choices=SARL,widget=forms.RadioSelect(attrs={'class':'switch-field'}),required = False) nbr_associe= forms.ChoiceField(choices = NBR_ASSOCIE,widget=forms.Select(attrs={'onchange':'NbrAssocie()'}),required = False) #gerant_representant= forms.ChoiceField(choices = gerantAssocie(),widget=forms.Select(attrs={'onchange':'gerantAssocie()'}),required = False) #ville= forms.ChoiceField(choices = VILLE,widget=forms.Select(),required = False) autreactiv=forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 7})) class Meta: model=sarl fields=('denomination_social','numero_certificat','adresse','activite','autreactiv','capital_social','nbr_associe') Here is how my model looks like : class sarl(models.Model): denomination_social=models.CharField(max_length=200,blank=True) numero_certificat=models.CharField(max_length=15,blank=True) myfile=models.FileField(blank=True) adresse=models.CharField(max_length=250,blank=True) activite=models.CharField(max_length=100,blank=True) objet=models.CharField(max_length=100,blank=True) autreactiv=models.CharField(max_length=1000,blank=True) ville=models.CharField(max_length=20,blank=True, null=True) exercice_dip=models.BooleanField(default=False,blank=True) capital_social=models.FloatField(max_length=15,blank=True) gerant_representant=models.ForeignKey(PerP,on_delete=models.CASCADE,blank=True, null=True) #filled with id PP if CEO is not an "associé" gerant_sep=models.ForeignKey(gerant_separe,blank=True, null=True,on_delete=models.CASCADE) Typesarl=models.BooleanField(default=False,blank=True) #False = Plusieurs Associés | True = AU nbr_associe=models.CharField(max_length=6,default="--") nbr_gerants=models.CharField(max_length=6,default="--") when I want to post cleaned data of my form on my views.py , my form is valid, and I get all my fields data but I dont get the adresse and ville field. def saveToBase(request): form=sarlform(request.POST) if form.is_valid(): print(request.POST.get('CuisineList')) print("sarl form is valid !") print(form.cleaned_data) print(request.POST['adresse']) form.save() This is what I get from printing cleaned data : {'denomination_social': 'fkrbvirbv', 'numero_certificat': 'bybyb', 'adresse': '', 'ville': None, 'activite': 'gggg', 'autreactiv': 'gregetg', 'capital_social': 140000.0, 'nbr_associe': '2'} I've been stucking here for hours , and really dont get what is the reason of this problem. Any help Please would be awesome. THANK YOU -
Django Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x035D2618>
at the moment i'm going to a Django course, to learn about web programming and as IDLE we're using PyCharm. When I write the following commands to the terminal(cmd) i'm receiving an unicode error, I searched for other topics related to this one but I couldn't find the right answer. I mean I'm just not asking this to ask a question. In the end, i'll send you all commands and tracebacks, My name contains Ö and Ü and its in my C: users folder name too, thats why I thought the problem was because of that, and that's why I just uninstalled python and reinstalled it to a new folder in D: but the problem haven't solved. I'm still receiving same error, after running server with the following code : python manage.py runserver while typing : django-admin startproject myblog_ cd myblog_ python manage.py startapp gonderiler these, I'm not receiving any error, "myblog_" is project name and "gonderiler" is app. name. But when I run server, I receive the following error: also python manage.py migrate didn't fix the issue. Thanks all ! I hope we'll find a solution together.! I just copied all(not only traceback) from cmd to make it more … -
Django query is not returning all the records
I am trying to do a simple query but I just don’t understand why I am only getting 1 row when it should be in this example 2: And I am trying to get all the rows where the externalID = 45454 By doing: context['report'] = Report.objects.filter(externalID = self.kwargs.get('reportID')) I can see on the debug I get SELECT "data_app_report"."id", "data_app_report"."main_contact_id", "data_app_report"."company_id", "data_app_report"."created", "data_app_report"."externalID", "data_app_report"."success", "data_app_report"."amountrequested" FROM "data_app_report" WHERE "data_app_report"."externalID" = '''45454''' And my table looks like I guess I am doing something wrong in the query but I just don’t know what, I thought having filter will allow me to get all of the records -
How to write tests for model in Django?
I want to write tests for Django Models, My Model: class Entry(models.Model): title = models.CharField(max_length=500) author = models.ForeignKey('auth.User') body = models.TextField() created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) I have no idea, How can I make tests for Django model? Thanks in advance -
How I can access to the next page in django 2.0
I have the following scenery. In the first page there are type of products, when choose specific type it sends to the page of products of the specific type, then when I choose the product it should send me to the page of the product where there is full information about the product. But I can't access the last product page. How I should fix this? My code: views.py: def products_fizlitso(request): fizlitso_product = InsuranceProducts.objects.filter(product_type="Физическое Лицо") context = {'fizlitso_product': fizlitso_product} return render(request, 'insurance_products/fizlitso/fizlitso.html', context) def fizlitso_type(request, type_id): product_type = get_object_or_404(InsuranceProducts, id=type_id) context = {'product_type': product_type} return render(request, 'insurance_products/fizlitso/fizlitso_type.html', context) def product_page(request, product_id): product = get_object_or_404(ProductType, id=product_id) context = {'product': product} return render(request, 'insurance_products/fizlitso/product.html', context) here is the urls.py: # ****************************************************************** path('fizlitso/', views.products_fizlitso, name='product_fizlitso'), # ****************************************************************** # ****************************************************************** path('fizlitso/product_type<int:type_id>', views.fizlitso_type, name='fizlitso_type'), # ****************************************************************** # ****************************************************************** path('fizlitso/product_type<int:type_id>/product<int:product_id>', views.product_page, name='product_page'), # ****************************************************************** and here is the django part of the template which holds all the product types: {% for product in fizlitso_product %} <div class="btmspace-80"> <h3>{{ product.product_area }}</h3> <img class="imgr borderedbox inspace-5" src="{% static 'img/imgr.gif' %}" alt=""> <p> {{ product.product_description }} </p> <p> Подробно вы можете узнать <a href="{% url 'main:fizlitso_type' product.id %}">здесь</a></a> </p> </div> {% endfor %} And here the django part of … -
referral by product specific and company specific
I am thinking of creating a referral and reward app where a user will list his/her company with the product they have. A company can use referral program by product specific or just in whole(could not name it properly). For example, I have listed my company called ABC Company and I have a product like smartphone, smart Tvs, Laptops. I would like to market for my company by just saying refer me to 10 people and get something in return(this is non-product specific) or I should be able to market my specific product let's say when user goes to the abc phone XI and there will be refer this phone and get the same phone in return if you refer to more than 50 or if more than 10 then 10% discount etc. This is just an example to demonstrate my project. For now I created the model for Company, Product(with nested category), referral. But I have no idea on how should i be able to keep the referral based on above example like product specific or based on full company. Here is what I have done class Product(models.Model): """ product model """ name = models.CharField(max_length=100, blank=True) company = models.ForeignKey(Company, … -
Relation between 2 django projects on same server
I have 2 django projects caringo and typer running on sockets on uwsgi and serving on nginx. Caringo project should call an api from typer. But caringo cannot call typer url for api. I can open both caringo and typer web sites from my computer on my browser remotely. When i try to open these 2 web sites on the server desktop itself locally, those web sites are not opened. So probably problem is this. Caringo cannot see typer locally. Is there a special configuration for nginx for both django web sites to call each other? -
How can I get the Authentication class (or class name) which is succeeded during authentication in DRF View?
Suppose I have a view as from rest_framework import viewsets class SampleViewset(viewsets.ModelViewSet): serializer_class = SampleSerializer queryset = Sample.objects.all() authentication_classes = (FirstAuthClass, SecondAuthClass, ThirdAuthClass) def get_success_auth_class(self, request, *args, **kwargs): # What logic should I use here ???? return success_auth_class Then, What logic should I use in get_success_auth_class() method? In other words, How can I get the Authentication class (or class name) which is succeeded during authentication in DRF View? -
Django multiply calculated days field with float column
In my DB I had two date field, then I calculated the difference between those two dates using .annotate(delay=F('date_1') - F('date_2')) Now i have to multiply this delay with another column in database F('delay')*F('amount') But getting errors, also tried by appending days still doesn't work .annotate(a=Sum(F('delay')*F('amount'))) 'Delay' is difference between dates and amount is the column present in table which has float data type. -
How can I response my custom list to the request side?
How can I response my custom list to the request side? I use django-rest-framework: class GetCustomListAPIView(APIView): permission_classes = [AllowAny] def get(self, request): list = [ { "user": {"name": "David"}, "passport": 123 }, { "user": {"name": "Den"}, "passport": 124 }, { "user": {"name": "George"}, "passport": 125 }, ] return Response() # what should I write in the Response for returning the list back to request side? How can I return the list to the request side? -
Fetch details through API from the secondary table using Django
I'm new to Django, Having two databases, DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'global_db', 'USER': 'root', 'PASSWORD': 'abc123', 'HOST': '127.0.0.1', 'PORT': '' }, 'usersdb': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'users', 'USER': 'root', 'PASSWORD': 'abc123', 'HOST': '127.0.0.1', 'PORT': '' } } Created required models and serializers separately. setup required views in views.py class. i'm getting the below error 1146, "Table 'global_db.account_categories' doesn't exist" the table actually exists in my secondary database 'users', can anyone please help me out what i'm doing wrong. Thanks in advance. -
Django mezzanine - how to add multicolumn formating option in richtext?
I am using Django mezzanine as CMS. I have site with a lot of rich-text pages. How can I enable some advanced options (particularly multi-column layout for some paragraphs) in the richtext editor in admin interface? -
how to parse elements of a list of dictionary in django template(index.html) using for loop
models.py class Data(models.Model): price = models.CharField(max_length=264,unique=False,blank=True,null=True) shipping = models.CharField(max_length=264,unique=False,blank=True,null=True) netprice = models.CharField(max_length=264,unique=False,blank=True,null=True) points = models.CharField(max_length=264,unique=False,blank=True,null=True) def __str__(self): return str(self.price) views.py def index(request): az_list=list(Data.objects.all()) return render(request,{'az_list':az_list,'loop':range(500)}) index.html {% for i in loop %} {{ az_list.i.price}} {{ az_list.i.shipping}} {{ az_list.i.netprice}} {{ az_list.i.points}} {% endfor %} -
How can I realize a APIView to get my requirement data?
I have two models: class TypeModel(models.Model): type = models.CharField(max_length=12) class Amodel(models.Model): name = models.CharField(max_length=12) type = models.ForeignModel(to=TypeModel) in_use = models.BooleanField(default=False) the Amodel is the main model, it has a type field refer to TypeModel. in the serializers.py: class AmodelSerializer(ModelSerializer): class Meta: model = Amodel fields = "__all__" class TypeModelSerializer(ModelSerializer): class Meta: model = TypeModel fields = "__all__" My requirement is fetch the Amodel data like this, it should be divided by type, I want to get this type data: [ { "type": { name: 'type1' }, "count": { "used": 12, # the in_use is `True` "unused": 24 } }, ... ] -
Django 1.10 Legacy Database - Unable to Retrieve Objects
I have a very small (so far) legacy database which I auto-generate in Django using python manage.py inspectdb > models.py I put this in my python package that holds the app and added to my INSTALLED_APPS setting. I ran: python manage.py makemigrations app_name Migrations for 'app_name': app_name/migrations/0002_auto_20180809_0453.py Next: python manage.py migrate app_name Operations to perform: Apply all migrations: app_name Running migrations: Applying app_name.0001_initial... OK Applying app_name.0002_auto_20180809_0453... OK I checked that the models were created using: python manage.py sqlmigrate app_name 0001, which showed that several models were created. My models.py file looks like this: from __future__ import unicode_literals from django.db import models class Test(models.Model): date = models.FloatField(blank=True, null=True) shift = models.FloatField(blank=True, null=True) timer = models.FloatField(blank=True, null=True) target_produce = models.FloatField(blank=True, null=True) actual_produce = models.FloatField(blank=True, null=True) oee = models.FloatField(blank=True, null=True) class Meta: managed = False db_table = 'Test' I am trying to access my database from views.py. Here is my code: File: views.py from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from lineoee.models import Lineoee1 # Create your views here. def index(request): context = {} lines = Lineoee1.objects.date() # <-- Error here print(lines) return render(request, 'lineoee/index.html',context) I get the atribute error 'Manager' object has no attribute 'date' I tried … -
Django form validation. No errors are displayed
Authorization form forms.py class LoginForm(forms.Form): username = forms.CharField(label='Enter your login') password = forms.CharField(label='Enter your password', widget=forms.PasswordInput) def clean(self): cleaned_data = super(LoginForm, self).clean() username = self.cleaned_data['username'] password = self.cleaned_data['password'] if not User.objects.filter(username=username).exists(): raise forms.ValidationError('User with such login is not registered!') user = User.objects.get(username=username) if user and not user.check_password(password): raise forms.ValidationError('Incorrect password!') Code from views.py def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] login_user = authenticate(username=username, password=password) if login_user: login(request, login_user) return redirect('/') else: form = LoginForm() return render(request, 'registration/login_view.html', {'form': form}) login_view.html {% extends 'base.html' %} {% block content %} <div class="title">Вход</div> <section id="login" class="border"> <form id="login-form" action="" method="POST"> {% csrf_token %} {% for field in form %} {{ field.errors }} <ul> <li>{{ field.label }} *</li> <li> <input class="input" name="{{ field.name }}" type="{{ field.name }}" /> </li> </ul> {% endfor %} <div> <span><input class="block" type="submit" value="Войти" /></span> </div> </form> </section> {% endblock content %} The form does not show a validation error, but simply resets all fields. I can not find the problem in the code ... What here can be wrong .. ??? -
What is article_set ? How does it works?
from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) Now in python shell..... from datetime import date r = Reporter(first_name='John', last_name='Smith', email='john@example.com' r.save() new_article = r.**article_set**.create(headline="John's second story", pub_date=date(2005, 7, 29)) Above code is referenced from Django docs. If there is any misunderstanding please go to this link. [https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/]