Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DecimalField Omitting Trailing Zeroes
My form contains a DecimalField with the attributes max_digits=8, decimal_places=2, validators=[MinValueValidator(0)], blank=True, null=True. In my view, I receive the model returned by the form: my_model = form.save(False) # Do stuff with returned model ... my_model.save() When I come to access the value of the DecimalField, price, I get it without the trailing zeroes. Say the value entered in the form field was 50: print(my_model.price) # Prints 50 But when I get the model from scratch, then retrieve the price, I get it with the trailing zeroes. my_model = MyModel.objects.get(id=my_model.id) print(my_model.price) # Prints 50.00 I am just wondering why this is the case. -
`Page not found` though the urls are designed carefully
My minimal web has worked smoothly for days, but throw page not found error abruptly just now. I double checked the urls but am unable to locate the error. the request is http://127.0.0.1:8001/user/login/ Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8001/user/login/ Using the URLconf defined in forum.urls, Django tried these URL patterns, in this order: ^admin/ ^$ [name='index'] ^article/ ^user/ ^register$ [name='register'] ^user/ ^activate/(?P<a_code>\w+)$ [name='activate'] ^user/ ^login$ [name='login'] ^user/ ^logout$ [name='logout'] The current path, user/login/, didn't match any of these. The app user.urls: from django.conf.urls import url from django.contrib.auth import urls from django.contrib.auth.views import login, logout from . import views # User app's url urlpatterns = [ # show the register page url(r"^register$", views.register, name="register"), #activate the user account from the registered email url(r"^activate/(?P<a_code>\w+)$", views.activate, name="activate"), # Log in page, override the default registration/login.html url(r"^login$", login, {"template_name":"user/login.html"},name="login"), url(r"^logout$", logout, {"template_name":""},name="logout"), ] The top level urls.py from django.conf.urls import url,include from django.contrib import admin from article import views # Project url urlpatterns = [ url(r'^admin/', admin.site.urls), url(r"^$", views.index, name="index"), url(r'^article/', include('article.urls',namespace='article')), url(r'^user/', include('user.urls',namespace='user')), ] The templates: βββ user βββ activate.html βββ failure.html βββ login.html βββ register.html βββ success.html βββ validate.html 1 directory, 6 files What's the problem might be? -
ImageField set to null after passing through serializer for update profile | DRF | Django Rest Framework
I am trying to update user's profile image. User's profile is being automatically created on the created of the user. At that time a default avatar is set. I am using Token Authentication Authorization : Token a877b60afeb45e1ada12e10ecf4d0c8065b15569 But when trying to update my request.data <QueryDict: {'date_of_birth': ['1990-05-02'], 'profile_image': [<InMemoryUploadedFile: image_5854.jpg (image/jpeg)>]}> serilizer.data {'profile_image': None, 'date_of_birth': '1990-05-02'} Models.py @deconstructible class UploadToPathAndRename(object): def __init__(self, path): self.sub_path = path def __call__(self, instance, filename): ext = filename.split('.')[-1] # get filename if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: # set filename as random string filename = '{}.{}'.format(uuid4().hex, ext) # return the whole path to the file return os.path.join(self.sub_path, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField(null=True, blank=True) profile_image = models.ImageField(upload_to=UploadToPathAndRename(os.path.join('images/avatar/')), default='images/avatar/default.jpg') participated = models.IntegerField(default=0) won = models.IntegerField(default=0) runner_up = models.IntegerField(default=0) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Serializers.py class ProfilePUTSerializer(ModelSerializer): profile_image = ImageField(max_length=None, use_url=True) class Meta: model = Profile fields = ('profile_image', 'date_of_birth',) Views.py class ProfilePUTAPIView(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def put(self, request): print(request.data) print(request.content_type) print(request.stream) serializer = ProfilePUTSerializer(data=request.data) if serializer.is_valid(): serializer.data['profile_image'] = request.data['profile_image'] user = Profile.objects.get(user_id=request.user.pk) user.__dict__.update(serializer.data) user.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Please suggest what to do? Thanks -
Django and Mongodb import: __schema__ issue
I've followed this tutorial to get Django working with Mongodb. When I try: db.__schema__.find(); to check if the last id in __schema__ collection is equal to the last id in MongoDB collection, I get the following error: TypeError: db.__schema__find is not a function : @(shell):1:1 Installed versions: Django: 2.0.5, Mongodb: 3.6.5 What am I doing wrong? -
How to read Django static files from Cloud Buckets
I'm trying to get GAE to read static files from the Google Cloud Storage bucket, in particular, I want to load a keras model. In my settings.py, I have: STATIC_URL = 'https://path_to_gcs_bucket/static/' When working locally, I can do: file_path = 'static/app/model.h5' model = load_model(file_path) # rest of the code For remote, I tried to do: from django.contrib.staticfiles.templatetags.staticfiles import static file_path = static('app/model.h5') model = load_model(file_path) But this gives me error: No such file or directory (although the path is correct). I am able to open this file in the web-browser, and the download starts automatically (even in incognito window). print(file_path) https://path_to_gcs_bucket/static/app/model.h5 -
Django fill modal with initial data
This is a general question concerning populating Modals with initial data when using class based views. In function views, I guess one could just define the initial values when calling the form, but not in class-based views. Also, populating a Modal via get_form_kwargs does not work, because (afaik) that is not triggered when clicking on the modal button. Does that mean that this is impossible (or very difficult) to achieve with modals or is there a generally accepted, reasonable way? -
Trying to "scale" a web app locally - unable to find a bottleneck
I am profiling one of my web app's views. It is a Django view that does is a simple SELECT: @api_view(['GET']) @permission_classes(()) def some_test_view(request): Bot.objects.get(uuid='369ffaa4-68de-484a-86fc-f8d3210657bf') return Response({}) I am running it inside a docker-compose comfiguration which has cache, db, constructor and constructornginx services, and the data flow is as follows: incoming request to port 80 > constructornginx:80 > proxies to constructor:8000 > connects to db:5432 and fetches data. Also, I have duplicated constructor and constructornginx as separate services (named constructor2 and constructornginx2, to imitate horizontal scaling on my local machine. They connect to the same db service but listen on a separate port. The data flow is : incoming request to port 81 > constructornginx:81 > proxies to constructor:8001 > connects to db:5432 and fetches data. The idea is to apply load to both web ports and see how the db service handles load from two web app instances. So, when the load is applied only to one of the web apps, I get about 60 RPS, and dockers stats show the following load: CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 5ab5727d4eb6 ecsdockerfiles_cache_1 0.49% 1.598MiB / 1.952GiB 0.08% 57.8kB / 90.3kB β¦ -
Django - Access specific field from a model to another
I am trying to create in admin panel a status field for different Models which should inherit that attribute from my main model called Students: class Students(models.Model): Username = models.ForeignKey(User) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) Group = models.CharField(max_length=4) status = models.CharField(max_length=1,null=True, choices=STATUS_CHOICES, default='n') def __str__(self): return str(self.Username) + ' ' + self.FirstName +' ' + self.LastName In CatalogStudentsFirstYear I want to store in status only the status value from Students class CatalogStudentsFirstYear(models.Model): catalogFirstYear = models.ForeignKey(CatalogFirstYear) student = models.ForeignKey(Students) grade = models.IntegerField(blank=True, null=True) status = def __str__(self): return str(self.catalogFirstYear) +' ' + str(self.student) And add it to admin.py like this: list_display = ["student", "catalogFirstYear", "grade", "status"] This is how it looks like in Students admin panel And this is how currently looks CatalogStudentsFirstYear Can you please suggest how can I create a FK which takes only status filed from Students and store it it status from CatalogStudentsFirstYear ? Thank you -
How to rename translation fields in django
I have fields in model.py namely name,city which are registered with translation.So automatically two fields name_en and name_he are created in database. I want these fields to display as name_english and name_hebrew in admin portal of django. In my settings.py : LANGUAGES = ( ('en', gettext('English')), ('he', gettext('Hebrew')), ) Any approach to do so.Thanks in advance -
How to split ManyToManyField save as a single data(Django)
I have models as below, when I create a course or test how to split manytomanyfield and save it into a single data including the version of knowledge? We want to distinguish the version of knowledge of different users. class Knowledge(models.Model): name = models.CharField(max_length=100, default="") description = models.TextField(blank=True) version = models.FloatField(default=1, blank=True) class Qualification(models.Model): name = models.CharField(max_length=50, default='') knowledge_course = models.ManyToManyField(Knowledge, related_name="qualifications", blank=True) knowledge_test = models.ManyToManyField(Knowledge, related_name="+", blank=True) class Course(models.Model): name = models.CharField(max_length=50) knowledge = models.ManyToManyField(Knowledge, related_name="courses", blank=True) teacher = models.ForeignKey(User,on_delete=models.CASCADE, null=True, related_name="+") students = models.ManyToManyField(User, related_name="courses",blank=True) class Test(models.Model): name = models.CharField(max_length=50) knowledge = models.ManyToManyField(Knowledge, related_name="courses", blank=True) teacher = models.ForeignKey(User,on_delete=models.CASCADE, null=True, related_name="+") students = models.ManyToManyField(User, related_name="courses",blank=True) To distinguish the version of knowledge, I crated model as below, but I don't know how to save those data as a single data. class UserKnowledge(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, null=True, blank=True) knowledge = models.ForeignKey(Knowledge,on_delete=models.CASCADE, null=True, blank=True) version = models.FloatField(default=1, blank=True) -
django logging can't set maxBytes
I Can't set maxBytes to logging files. My django version is 2.0.3, Python 3.5.2 logging 0.5.1.2 here is exception. Traceback (most recent call last): File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/moon/.env/envpy3/lib/python3.5/site-packages/django/utils/log.py", line 73, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python3.5/logging/config.py", line 566, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'file_database': __init__() got an unexpected keyword argument 'maxBytes' -
django i want leftouterjoin to table
django 2.0.2 python3.4 my model.py table1(models.Model): id = primarykey content = textfield key = foreignkey(table2) blind = integerfield registerdate = datetimefield table2(models.Model): id = primarykey value = charfield myviews.py table = table1.objects.filter(blind=0) table = table.annotate(table2val = Case(When(key__value__isnull=False),then=F("key__value")),output_field=CharField())) i want all if blind is 0 but this return value blind is 0 and must have key i want all if key is null or any -
Django Admin Inline without foreign key
I saw many question and answers but i could not find certain answer. Admin inline without foreign key Django admin inline display but foreign key has opposite relation So can i iterate model fields without relation to other models class CommentTabularInline(admin.TabularInline): model = Comment fields = ('content_type', 'text') extra = 1 class CommentAdmin(admin.ModelAdmin): inlines = [CommentTabularInline] admin.site.register(Comment, CommentAdmin) model class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, CASCADE, 'user_comment') text = models.TextField() content_type = models.ForeignKey(ContentType, CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') created_at = models.DateTimeField(auto_now=True) is_approved = models.BooleanField(default=False) I tried to do this, but i am getting error : (admin.E202) 'main.Comment' has no ForeignKey to 'main.Comment' -
django-rq configuration and installatino in apps.py
I use django-rq in my Django application. Currently, I install django-rq with pip, then add the following content to mysite/settings.py: INSTALLED_APPS += 'django_rq' RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT-TIMEOUT': 360, } } This works well, but I want to distribute my application with an installation process as simple as possible. Is there a way to move the previous content of settings.py to my-app/apps.py or any other file distributed with my application? Something like from django.apps import AppConfig from django.conf import settings class MyAppConfig(AppConfig): name = 'myapp' def ready(self): settings.INSTALLED_APPS += 'django_rq' settings.RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'DEFAULT-TIMEOUT': 360, } } This obviously won't work, but you get the idea. -
security when Django 1.11, apache2 and mod_wsgi is used
I have read a few interesting articles and watched a few videos but I'm afraid I still have a few things I help with understanding. I'm a very new dabbler to all this. 1) The example listed in the blog made sense and I tried to implement it but unfortunately my django project is in home folder and the full wsgi path is /home/serverio/server.io_Tools/server.io/mysite/mysite/wsgi.py. And since www-date needs read and execute permission in order to the open the folders leading up to the last mysite directory, I tried creating a new group which has rwx permission on the static and media folders. This was ok for the static and media folder because I used django collectstatic to move those files into the www folder, which is also has the the group that www-data belongs. The blog did not speak much about for situations like mine where I have wsgi.py in my home folder as shown above. So I tried to make the group of the home folder the same group that www-data belongs(recursively) but the end result was that I could not open the folder even though I also put my username into the same group that is used by β¦ -
AWS lambda in djnago app
I created a simple function in aws lambda for print something. How can I call or invoke that lambda function when I got an API request in my Django application? What all changes I need to do in my Django settings and all? -
Invite Registered Users to vote in voting app
I'm trying to expand the Django tutorial for a school project and make it into a more usable voting app. What I want is to allow users to create Polls and invite other registered users by email to vote on their Poll. Only the invited users will be allowed to vote. My models.py: class Poll(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', auto_now_add=True) is_active = models.BooleanField(default=True) activation_date = models.DateTimeField('Activation Date', blank=True, null=True) expiration_date = models.DateTimeField('Expiration Date', blank=True, null=True) public_key = models.CharField(max_length=30, blank=True) hash = models.CharField(max_length=128, blank=True) timestamp = models.DateTimeField(auto_now=True) def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): question = models.ForeignKey(Poll, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text class EligibleVoters(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) poll = models.ForeignKey(Poll, on_delete=models.CASCADE) email = models.EmailField(null=True) I have a Poll table which contains the Poll Title and other information regarding the Poll. I also created a separate Choices table (like in the tutorial) which has a ForeignKey to the Poll table and contains the poll choices. I figured that in order to invite users as eligible voters I needed a β¦ -
DJANGO // How do I make it so that each user has their own homepage? //
I'm relatively new to Django, but I'm in the process of making a website where each user has their own contacts list that they can add, edit, delete, etc. So far that functionality works. For the majority, I'm almost done, except for the fact that all users are seeing the same page when they register. I want it so that everytime a user is created it displays a blank template homepage. (I should also mention the fact that I have a registration page but not a sign-in/log-in page, so if you could also help me with that it would be great because I haven't been able to find a reliable tutorial having that all of them since my pages to crash.) -
Django Path To Resource Failure?
When I try a GET request on one of my API endpoints it can't find the endpoint. urls.py file looks like this from django.urls import path, include from django.contrib import admin from api.resources import NoteResource note_resource = NoteResource() urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(note_resource.urls)), ] api.resources looks like this from tastypie.resources import ModelResource from api.models import Note class NoteResource(ModelResource): class Meta: queryset = Note.objects.all() resource_name = 'note' Any idea why this is happening? -
django celery worker keyword argument error
I'm trying to setup a simple webhook where incoming request are processed by a celery worker. That's my the hook in the view.py: @method_decorator(csrf_exempt, name='dispatch') class SendGridCallbackView(View): def post(self, request, *args, **kwargs): print('TEST') req_dict = {'request': request.body} sendgrid_email_tracking.apply_async(kwargs=req_dict) return HttpResponse(status=200) The task defined in tasks.py: @shared_task(base=WorkerBase, name='mailer.sendgrid-tracking-mail') def sendgrid_email_tracking(**kwargs): print('GOTCHA') When sending a test email from sendgrid it prints the TEST output but then the celery worker returns an error TypeError: sendgrid_email_tracking() got an unexpected keyword argument 'request' -
`registration/login` rather than `accounts/login`
In Django's 1.11 django.conf.global_setting.py, it configure a constant LOGIN_URL = '/accounts/login/' ################## # AUTHENTICATION # ################## LOGIN_URL = '/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile/' It does redirect to 'registration/login.html'. class LoginView(SuccessURLAllowedHostsMixin, FormView): """ Displays the login form and handles the login action. """ form_class = AuthenticationForm authentication_form = None redirect_field_name = REDIRECT_FIELD_NAME template_name = 'registration/login.html' redirect_authenticated_user = False extra_context = None What confuse me very much is that why it is named as 'registration/login.html' rather than accounts/login.html? -
django1.9 model float field update
I want to know about float field data update. All fields are already made by modelforms. And When i enter the button in template, values in pdmv_data are calculated, and the result is into pdmv_rst. I try to program an application, But It's not working... I appreciate of your help. Thank you. Models.py class pdmv_data(models.Model): pdmv_dis=models.FloatField(name='pdmv_dis', verbose_name=' cc', default=2000, help_text='Displacement') pdmv_no_cyl=models.FloatField(name='pdmv_no_cyl', verbose_name=' EA', default=4, help_text='Number of Cylinder') pdmv_mflow=models.FloatField(name='pdmv_mflow', verbose_name=' kg/s', default=0.1, help_text='Mass flow rate') pdmv_Dp=models.FloatField(name='pdmv_Dp', verbose_name=' kPa', default=10, help_text='Differential pressure (Center muffler)') class pdmv_dataForm(ModelForm): class Meta: model = pdmv_data fields = '__all__' class pdmv_rst2(models.Model): pdmv_t_vol=models.FloatField(name='pdmv_t_vol', verbose_name=' L', default=None, help_text='Total Volume') class pdmv_rst2Form(ModelForm): class Meta: model = pdmv_rst2 fields = '__all__' -
How can I create a dynamic filter
I Have diferent attributes like brand,size and color I want a filter to dynamically as per the choice of user Product.objects.filter(attributes__userchoice=some_value). User can select multiple attribute and their values Example if the user selects size=L the query should be Product.objects.filter(attributes__size='L') -
Django does not use translated labels
I'm tying to send an email in two languages using django. In my settings.py I have it as follows: LANGUAGE_CODE = 'en-us' LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) And my project tree is as follows: The code for sending email is as follows: to_email = [email, ] from_email = 'no-reply@company.com' to_cc_emails = download_documents_cc_emails subject = _('The requested document') html_content = render_to_string('email_templates/download_documents.html', {'name': name}) msg = EmailMultiAlternatives(subject, html_content, from_email, to_email, to_cc_emails) msg.content_subtype = "html" # Main content is now text/html msg.attach_file(file_to_be_sent) msg.send() And download_documents.html is as follows: {% load i18n %} <div> <div>{% trans "Dear" %} {{ name|capfirst }},</div> <div style="margin: 25px 0;"> {% trans "The requested document is attached." %} <br /> </div> <div>{% trans "Best regards" %}</div> </div> When I do django-admin makemessages -l nl inside locale folder the right labels are created: #: main/views.py:68 msgid "The requested document" msgstr "Het aangevraagde document" #: templates/email_templates/download_documents.html:3 msgid "Dear" msgstr "Geachte" #: templates/email_templates/download_documents.html:5 msgid "The requested document is attached." msgstr "In bijlage vindt u het document." #: templates/email_templates/download_documents.html:7 msgid "Best regards" msgstr "Met vriendelijke groeten," But when I get the email it isn't translated. I get the email in English. Any idea what I do wrong? -
Deploying Django on Apache with mod_wsgi
I'm currently trying to set up a Django application on Apache on a Centos server, with the use of mod_wsgi. This is set up to run on https. It is on virtualenv. However, currently it gives a 504 Gateway Timeout error. Error log: (2)No such file or directory: mod_wsgi (pid=15007): Unable to stat Python home /bin/virtualenv:/var/www/django/mysite/mysite/lib/python3.6/site-packages. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' httpd.conf <VirtualHost *:443> ServerName mysite.example.com ServerAlias www.mysite.example.com # DocumentRoot /var/www/django/mysite LogLevel info ErrorLog /etc/httpd/logs/mysite_error.log Alias /static /var/www/django/mysite/static <Directory /var/www/django/mysite/static> Require all granted </Directory> <Directory /var/www/django/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite python-home=/bin/virtualenv:/var/www/django/mysite/mysite/lib/python3.6/site-packages WSGIProcessGroup mysite WSGIScriptAlias / /var/www/django/mysite/mysite/wsgi.py WSGIApplicationGroup %{GLOBAL} SSLEngine on SSLProtocol all -SSLv2 SSLCompression off SSLCertificateFile /etc/pki/tls/certs/mysite.cert.pem SSLCertificateKeyFile /etc/pki/tls/private/mysite.key.pem SSLCertificateChainFile /etc/pki/tls/certs/mysite.chain.pem </VirtualHost>