Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there remarkable performance difference between this django app model construction?
First case, app_1 - post_model_1 app_2 - post_model_2 (has Foreign Key Field to post_model_1) app_3 - post_model_3 (has Foreign Key Field to post_model_1) Second case, app_1 - post_model_1, post_model_2 (has Foreign Key Field to post_model_1), post_model_3 (has Foreign Key Field to post_model_1), If i do queryset like getting all related posts(whatever it is post_model_2, or post_model_3) to post_model_1 using ForeignKeyField, Is there performing difference between First case and Second case? If it is, which is faster? -
Django - filter against current admin (user) in DRF
When i log in with a admin to see a chart of all members and admins for the current admin-association it gives me the right numbers. But when i log in with another admin with another association it gives me the same result as the last admin logged in. I want it to give me the current numbers in the chart for the current admin-association. Looked for similar problem here and not found any that can solve my issue. Still new to this and appreciate all your help, folks! models.py class Administrator(AbstractUser): ... association= models.ForeignKey(Association) class Meta: db_table = 'Administrator' class Member(models.Model): ... association = models.ForeignKey('Association') class Meta: db_table = 'Member' class Association(models.Model): asoc_name = models.CharField(max_length=50, null=True, blank=True) class Meta: db_table = 'Association' views.py class ChartView(View): def get(self, request, *args, **kwargs): return render(request, 'chart/ChartView.html', {}) class ChartData(APIView): authentication_classes = (authentication.BasicAuthentication, JSONWebTokenAuthentication) permission_classes = (permissions.IsAuthenticated,) def get(self, request, format=None): qs_count = Administrator.objects.filter(association=self.request.user.association).count() qs_count1 = Member.objects.filter(association=self.request.user.association).count() labels = ["Board", "Members"] default_items = [qs_count, qs_count1] data = { "labels": labels, "default": default_items, } return Response(data) -
Django website giving trouble serving static files
I am working on a multi-app website. And I have bunch of noob questions. My dir structure looks like as below: /var/www/html/portal src/ manage.py portal/ static/ admin/ css/ img/ js/ fonts/ templates/ base.html homepage.html venv/ Is my dir structure as per as Django standards? Are my STATIC files settings correct? STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Or should it be STATIC_URL = '/static/' STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') Should I collectstatic after copying all my static files such as css,js etc or I can do it before copying files in those dirs? If I do collectstatic without mentioning STATIC_ROOT I get an exception django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. But when I replace STATICFILES_DIRS with the following, my .css files stop serving. What am I doing wrong? STATIC_ROOT = os.path.join(PROJECT_DIR, 'static') -
Celery not queuing tasks to broker on remote server, adds tasks to localhost instead
celery.py # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project', broker='amqp://foo:bar@remoteserver:5672', backend='amqp') # app = Celery('project') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py (in the app folder) from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task def addnum(x, y): return (x + y) When I call this task : addnum.delay(3, 5) It returns: <AsyncResult: 82cb362a-5439-4c1c-9c64-b158a9a48786> but celery worker just sits there waiting for tasks but doesn't receive any: [2017-03-17 13:48:36,869: INFO/MainProcess] celery@gauravrajput ready. The problem is that the tasks are not being queued to the remote rabbitmq server. When I initialize Celery as: app = Celery('project') and then start Celery worker, it started to receive and complete tasks. [2017-03-17 14:02:13,558: INFO/MainProcess] celery@gauravrajput ready. [2017-03-17 14:02:13,560: INFO/MainProcess] Received task: app.tasks.addnum[82cb362a-5439-4c1c-9c64-b158a9a48786] -
Django, Python inheritance: Exclude some fields from superclass
I have inheritance between Employee and Manager classes. Employee - superclass, Manager - subclass. class Employee(models.Model): ### name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=50, null=False) ### class Manager(Employee): department = models.CharField(max_length=50) ### here I don't want the 'name' and 'address' fields of Employee class. (I want other fields of Employee and department field of this class to be stored in Manager table in database) ### how can achieve this. Thans in advance. -
IntegrityError - Column cannot be null DJANGO
Everything works good in views and templates. When Ive made serializer and then APIVIew something wrong happend. GET method is ok, but POST is not. When I try to add food I get IntegrityError like this: (but in admin panel and GUI you can add food normally so its not problem with model the problem must be with serializer) IntegrityError at /food_list_serializer/ Column 'kcal' cannot be null MODEL look like this: class Food(models.Model): name = models.CharField(max_length=124) kcal = models.FloatField() proteins = models.FloatField() carbs = models.FloatField() fats = models.FloatField() grams = models.FloatField(default=100, validators=[MinValueValidator(1)]) SERIALIZER: class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__' VIEWS: class FoodListSerializer(APIView): def get(self, request, format=None): food = Food.objects.all() serializer = FoodSerializer(food, many=True, context={'request': request}) return Response(serializer.data) def post(self, request): food_create = Food.objects.create() serializer = FoodSerializer(food_create, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
django DateTimeField in form (initial value)
I have little problem with initial value of DateTimeField in Django forms. I have declaration in forms.py class FaultForm(forms.ModelForm): ... date_time = forms.DateTimeField(initial=datetime.now().strftime("%Y-%m-%d %H:%M:%S"), required=False) ... I have declaration in models.py class Fault(models.Model): ... # date time date_time = models.DateTimeField(default=datetime.now().strftime("%Y-%m-%d %H:%M:%S")) ... Problem is with returning appropriate time. When I add a few objects to my database with initial/default datetime from my forms.py I have exactly the same time for every object. But when I add objects with datetime from template, I have good datetime for every object which is in database. I have to tell my function to returning datetime is exactly the same in both of situation, but maybe problem is with generating the form?? We have the same time because we generate form once, or something like this?? I don't know what to do with this, because I would like to use initial value from forms and don't have to do it again in template. Ony ideas?? Bug?? Other datetime function?? Other way to solve this little problem?? Please help me :) -
show ReferForm if the user has already requested for invitation
I want to implement a feature for growth hacking where a user gets to signup only after admin accepts his/her invitation. The general flow of this feature is At first the user is shown a request invitation form where he has to fill his/her email address. If he request for invitation his/her email address is saved to db. If he now open the page, instead of request invitation form he/she should see ReferForm. How can I do it? class Invitation(models.Model): email = models.EmailField(unique=True, verbose_name=_('e-mail Address')) invited_by_email_address = \ models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) custom_invite_code = models.UUIDField(default=uuid.uuid4, unique=True) points = models.PositiveIntegerField(default=0) invite_accepted = \ models.BooleanField(verbose_name=_('invite accepted'), default=False) request_approved = models.BooleanField(default=True, verbose_name=_('request accepted')) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return 'Invite: {0}'.format(self.email) class InviteForm(forms.Form, CleanEmailMixin): email = forms.EmailField(label=_('E-mail'), required=True) def save(self, email): print ('email', email) return Invitation.objects.create(email=email) class ReferForm(forms.Form, CleanEmailMixin): email = forms.EmailField(label=_('Receiver E-mail'), required=True) invited_by_email_address = forms.EmailField(label=_('sender E-mail' ), required=True) def save(self, email, invited_by_email_address): return Invitation.objects.create(email=email, invited_by_email_address=invited_by_email_address) class RequestInvitation(LoginRequiredMixin, FormView): template_name = 'home.html' form_class = InviteForm def get_custom_invite_code(self): custom_invite_code = str(uuid.uuid4()) try: id_exists = \ Invitation.objects.get(custom_invite_code=custom_invite_code) get_custom_invite_code() except: return custom_invite_code def form_valid(self, form): email = form.cleaned_data.get('email') invite_instance = form.save(email) invite_instance.invited_by_email_address = self.request.user invite_instance.custom_invite_code = \ self.get_custom_invite_code() print ('invite_instance.custom_invite_code', invite_instance.custom_invite_code) invite_instance.save() … -
Cannot call service in my index.html file; Django error
I am currently working on implementing multiple themes in my web application using bootswatch. The user can choose what css theme they would like to see on the web application by choosing from a pick-list. I have written a service, kjTheme, to handle this. Ideally, when a user chooses a new theme (say, "Cyborg") in the front-end, my index file will use the line of code: <link rel="stylesheet" type="text/css" href="" data-ng-href={{ $kjTheme }}"/> To reference my service. My service then references the corresponding css file path (i.e. '/libs/bootswatch/cyborg/bootstrap.min.css'). However, I am running into a Template Syntax Error. Exception Value: Could not parse the remainder: '$kjTheme' from '$kjTheme' And the exception location points to my django\template\base.py Any ideas as to what I'm doing wrong, or what I could check to get me on the right path? Thank you! -
froala editor not working in django templates
i am making a blog site. So, i installed froala wysiwyg text editor, the problem that i am getting is that froala toolbar is visible in admin but not in templates. here is what i am doing my models.py from froala_editor.fields import FroalaField class Cards(models.Model): desc = FroalaField(theme="dark", null=True,blank=True) my forms.py class CardsForm(forms.ModelForm): class Meta: model = Cards fields = ['desc'] i think i have done everything else in settings.py and urls.py because froala toolbar is visible in admin panel. I don't know what i am doing wrong.. please help -
Why we can not define method or class name as a string?
Why we can not define method or class name as a string ? I was trying to use & in a method name, in normal name it was throwing error, So i tried to use method name in a string like as: def 'order_date_&_time'(self, obj): return obj.created_at But it again showing another error(SyntaxError: invalid syntax). So Why i can not define method or class name as a string ? -
Django-ckeditor how to set RichtextField to plain text as default configuration?
Ckeditor erase my uploaded SVG tags whenever I save the fields on my admin page. I would like to keep my Ckeditor as plain text on the admin rather than clicking on "source", how should I configure it ? I haven't found anything about that on their documentation. Here is the only configuration I have : CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } -
NoReverseMatch at Django
and I do not know why and what will be the problem, could they help me? Thanks beforehand, greetings! Reverse for 'entregado' with arguments '()' and keyword arguments '{'cod_experto': 'ASE-0048', 'id_pedido': 1770}' not found. 1 pattern(s) tried: ['solicitar/confirmar/(?P<id_pedido>\\d+)/(?P<cod_experto>\\d+)/$'] Error during template rendering admindata.html, error at line 74: <td><a href="{% url "usuario:entregado" id_pedido=ped.id cod_experto=ped.articulo.cod_experto %}" method='GET' type="submit" class="btn btn-success pull-right" value="editar" onclick="document.location.reload();"/>Entregar</a></td> url global: urlpatterns = [ # Examples: url(r'^solicitar/', include(urls, namespace="usuario")), ] url APP: urlpatterns = [ url(r'^confirmar/(?P<id_pedido>\d+)/(?P<cod_experto>\d+)/$', login_required(Update_stock), name='entregado'), ] and views.py: def Update_stock(request, id_pedido, cod_experto): if request.method == 'GET': pedido = Pedido.objects.get(id=id_pedido) articulo = Articulo.objects.get(id=cod_experto) articulo.stock -= pedido.cantidad stock.save() return render(request, 'admindata.html', {'pedido':pedido, 'articulo':articulo}) -
In the edit form of Django CRUD application the existing data is not showing correctly in the fields
I am new to python and trying to build a Django CRUD webapp. The add and delete forms are working fine but in edit form in the fields instead of actual value of the field, it is displaying <django.db.models.query_utils.DeferredAttribute object at 0x0424AA70> instead of displaying value like John Doe. I am using python 3.6 and Django 1.10.6 I am using function based approach. So in my views.py, I have following: def proposal_update(request, pk,template_name='proposal/proposal_form.html'): server = get_object_or_404(Proposal, pk=pk) form = ProposalForm(request.POST or None, instance=Proposal) if form.is_valid(): form.save() return redirect('list') return render(request, template_name, {'form':form}) and in my models.py, I have following: def get_absolute_url(self): return reverse('proposal_edit', kwargs={'pk': self.pk}) and in my urls.py I have: urlpatterns=[ url(r'^delete/(?P<pk>\d+)$', views.ProposalDelete.as_view(),name='proposal_delete'), url(r'^new$', views.proposal_create, name='proposal_new'), url(r'^edit/(?P<pk>\d+)$', views.proposal_update, name='proposal_edit'), ] -
TypeError during UUID validation
I'm using Django 1.9.6 and Django Rest Framework 3.3.3. Once in a while I receive a following error during UUID field validation: TypeError: '1078b6e1-6dc3-45ab-a93f-781586e519b8' is not a valid UUID. File "django/core/handlers/base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "django/core/handlers/base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "rest_framework/viewsets.py", line 87, in view return self.dispatch(request, *args, **kwargs) File "oauth2_provider/views/mixins.py", line 211, in dispatch return super(ProtectedResourceMixin, self).dispatch(request, *args, **kwargs) File "rest_framework/views.py", line 466, in dispatch response = self.handle_exception(exc) File "rest_framework/views.py", line 463, in dispatch response = handler(request, *args, **kwargs) File "api/views/transcription.py", line 375, in share serializer.is_valid(raise_exception=True) File "rest_framework/serializers.py", line 213, in is_valid self._validated_data = self.run_validation(self.initial_data) File "rest_framework/serializers.py", line 407, in run_validation value = self.to_internal_value(data) File "rest_framework/serializers.py", line 437, in to_internal_value validated_value = field.run_validation(primitive_value) File "rest_framework/relations.py", line 125, in run_validation return super(RelatedField, self).run_validation(data) File "rest_framework/fields.py", line 483, in run_validation self.run_validators(value) File "rest_framework/fields.py", line 497, in run_validators validator(value) File "rest_framework/validators.py", line 62, in __call__ if queryset.exists(): File "django/db/models/query.py", line 651, in exists return self.query.has_results(using=self.db) File "django/db/models/sql/query.py", line 501, in has_results return compiler.has_results() File "django/db/models/sql/compiler.py", line 819, in has_results return bool(self.execute_sql(SINGLE)) File "django/db/models/sql/compiler.py", line 837, in execute_sql sql, params = self.as_sql() File … -
Django get list of objects matching a criteria on a given date
I am using DJango 1.10, and have this model from django.contrib.auth.models import User class ClientStatusHistory(models.Model): client = models.ForeignKey(to=User, related_name="status_history") date = models.DateTimeField(auto_now_add=True, db_index=True) status = models.BooleanField(db_index=True) The table records when a user was marked as active or inactive. I want to select a list of users that were active on a given date. How do I do that using the django ORM? Sorry if the question is worded poorly; basically I am writing function like so: get_users_active_on_date(date_value) -
Join of 2 models having foreign key of 3rd model python django
I have 3 different models in django namely: Security,CurrentPrice,Index where CurrentPrice & Index have foreign key of 'Security' model I want to convert below mysql query to django queryset MYSQL query- select * from CurrentPrice,Index where Currentprice.SecurityCode=Index.SecurityCode and Currentprice.DateTime>='2017-03-17 00:00:00' and Index.RefCode = '017023928.00026005004' order by Currentprice.Percentage desc limit 5 Thank you. -
Using Apache to proxy requests based on URL parameter
I have a back-end application (Django) that requires its static content (assets like images, scripts, stylesheets, etc.) to be served by a web server. At current, I have my Django application serving on localhost:5000. I have this sitting behind an Apache2 server virtual host that is using mod_proxy to send requests to the Django app in the back. I need to configure my VHost so that all of the URI requests for domain.com/static/asset will serve the asset from /path/to/asset statically, while everything else gets proxied to the back-end app localhost:5000. My VHost config looks like this at the moment, the commented bits don't work properly. <VirtualHost *:80> ServerName www.domain.com ServerAlias domain.com ServerAdmin info@domain.com ErrorLog ${APACHE_LOG_DIR}/domain_error.log CustomLog ${APACHE_LOG_DIR}/domain_access.log combined ProxyRequests Off ProxyVia Off <Proxy *> Require all granted </Proxy> # DocumentRoot /path/to/static # <Directory /path/to/static/> # Require all granted # </Directory> ProxyPass / http://localhost:5000/ ProxyPassReverse / http://localhost:5000/ </VirtualHost> -
Django Form Wizard: skip and submit
I'm using the formtools Form Wizard in Django 1.8 to create quite a long (but ultimately quite simple) series of forms. I want to allow users to skip to the end and submit without the need to fill out every form. It's pretty straightforward to add a link to the final page (wizard.steps.last) but it wont run the 'done' method unless all the forms have been validated. Is this possible? I can see you can create conditional forms with 'condition_dict', but I'm not sure if I can modify this for my purpose or not. Thanks! -
How to manage conflicts in generated files
We are using Django and git. We have i18n enabled and run periodically compilemessages and makemessages. Everybody works in a separate branch and periodically we merge them in master. The problem is when two people need to add translations in their branches. Since compilemessages effectively changes the .po file, git cannot merge them and the second person have to manually resolve conflicts in the translations. We can't ignore .po files because translations are important to be in version control system. For now there are two possible ways to deal with the problem: To accumulate translations first and running compilemessages and makemessages only at certain times. To make translations only before merge and be sure to merge the PR with master before running compilemessages. So there are two questions involved: How to manage Django translations in git? And the more general - how to manage machine generated files which should stay in version control? -
Django image thumbnail, override save
I would like to upload an avatar for user and make a thumbnail of it and add as a model field so I could use it to return it in endpoint as a User property. I am trying to override save method in User model but without any success. Here is my code: from __future__ import unicode_literals, absolute_import from django.core.files import File from django.contrib.auth.models import AbstractUser from django.core.urlresolvers import reverse from django.db import models from django.utils.translation import ugettext_lazy as _ from PIL import Image def get_avatar_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'avatars/{0}/{1}'.format(instance.id, filename) def get_small_avatar_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'avatars/{0}/thumb_{1}'.format(instance.id, filename) class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) avatar = models.ImageField(upload_to=get_avatar_path, blank=True) small_avatar = models.ImageField(upload_to=get_small_avatar_path, blank=True) def save(self, *args, **kwargs): # image_resized = kwargs.pop('image_resized', False) super(User, self).save(*args, **kwargs) if self.avatar: size = 200, 200 filename = self.avatar.path small = Image.open(filename) small.thumbnail(size) # self.small_avatar = small self.small_avatar.save('thumb.jpg', small, save=True) # self.save(image_resized=True) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) def get_avatar(self): if self.avatar: return self.avatar.url return "" -
Django + Gunicorn big TTFB time
I'm look at the Google Chrome console ajax request time. I measured at backend, the mysql query is executed for 5 ms. At Chrome console I see enter image description here TTFB time 333.07 ms. I have 9 gunicorn workers, Django framework. What takes so much time? -
Filter on chained models at once with Django rest framework
I am using Python 2.7.9, Django 1.8.4, MySql 5.6 and using django-rest-framework. I am trying to make a filter on chained models, as native as I can. I have something like this: from django.db import models class MyTable(models.Model): name = models.CharField() other_model = models.ForeignKey(OtherModel) rows = None This is a table in my DB that holds entities which represent tables to be shown in my frontend. This tables are unique by name+other_model, and I can have multiple instances of tables. Each table has rows, and this rows are saved on a different table in my db. All of the rows are saved in a single db table, and are distinguished by a foreignkey to MyTable. The row also has a ManyToMany relation with another model, lets call it RowDataModel. The RowDataModel has also complex fields, such as relation to other models. As you can see, I have a bit complex model. class MyTableRows(models.Model): table = models.ForeignKey(MyTable, related_name="rows") row_data = models.ManyToMany(RowDataModel, related_name="my_table_rows) field1 = CharField() field2 = IntegerField() ... So now I need to make a rest-api for my models. I have a model of FilterSet to my table, and this is the entry point to the rest api, as I … -
NoReverseMatch at in Django
and I do not know why and what will be the problem, could they help me? Thanks beforehand, greetings! Reverse for 'entregado' with arguments '()' and keyword arguments '{'cod_experto': 'ASE-0048', 'id_pedido': 1770}' not found. 1 pattern(s) tried: ['solicitar/confirmar/(?P<id_pedido>\\d+)/(?P<cod_experto>\\d+)/$'] Error during template rendering admindata.html, error at line 74: <td><a href="{% url "usuario:entregado" id_pedido=ped.id cod_experto=ped.articulo.cod_experto %}" method='GET' type="submit" class="btn btn-success pull-right" value="editar" onclick="document.location.reload();"/>Entregar</a></td> url: url(r'^confirmar/(?P<id_pedido>\d+)/(?P<cod_experto>\d+)/$', login_required(Update_stock), name='entregado'), and views.py: def Update_stock(request, id_pedido, cod_experto): if request.method == 'GET': pedido = Pedido.objects.get(id=id_pedido) articulo = Articulo.objects.get(id=cod_experto) articulo.stock -= pedido.cantidad stock.save() return render(request, 'admindata.html', {'pedido':pedido, 'articulo':articulo}) -
why doesn't django work the same on dev (runserver) and on prod (gunicorn)
Why does it work fine with python manage.py runserver but throws csrf exceptions when it comes to production server using gunciron. This oblige me to pass all deployement process each iteration to make tests about this csrf bug.